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.util.Log;
33 import android.util.TypedValue;
34 import android.view.ContextMenu;
35 import android.view.ContextMenu.ContextMenuInfo;
36 import android.view.LayoutInflater;
37 import android.view.View;
38 import android.view.View.OnClickListener;
39 import android.view.ViewGroup;
40 import android.view.inputmethod.EditorInfo;
41 import android.widget.AdapterView.AdapterContextMenuInfo;
42 import android.widget.BaseAdapter;
43 import android.widget.Button;
44 import android.widget.CompoundButton;
45 import android.widget.CompoundButton.OnCheckedChangeListener;
46 import android.widget.FrameLayout;
47 import android.widget.LinearLayout;
48 import android.widget.ListView;
49 import android.widget.TextView;
50 import android.widget.Toast;
51 import android.widget.ToggleButton;
53 import android.support.v7.app.ActionBar;
54 import android.support.v7.app.ActionBarActivity;
55 import android.support.v7.widget.SearchView;
56 import android.support.v7.widget.SearchView.OnQueryTextListener;
57 import android.view.Menu;
58 import android.widget.ListAdapter;
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() {
188 final Intent intent = new Intent();
189 intent.setClassName(DictionaryManagerActivity.class.getPackage().getName(),
190 DictionaryManagerActivity.class.getName());
191 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
196 public void onCreate(Bundle savedInstanceState) {
197 // This must be first, otherwise the actiona bar doesn't get
199 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
201 super.onCreate(savedInstanceState);
202 Log.d(LOG, "onCreate:" + this);
204 application = (DictionaryApplication) getApplication();
206 blockAutoLaunch = false;
209 setContentView(R.layout.dictionary_manager_activity);
211 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
212 getListView().getContext()).inflate(
213 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
215 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
216 getListView().getContext()).inflate(
217 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
219 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
220 .findViewById(R.id.hideDownloadable);
221 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
223 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
224 onShowDownloadableChanged();
228 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
229 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
230 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
231 thanksForUpdatingLatestVersion)) {
232 blockAutoLaunch = true;
233 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
234 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
238 registerReceiver(broadcastReceiver, new IntentFilter(
239 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
242 registerForContextMenu(getListView());
244 final File dictDir = application.getDictDir();
245 if (!dictDir.canRead() || !dictDir.canExecute()) {
246 blockAutoLaunch = true;
248 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
249 builder.setTitle(getString(R.string.error));
250 builder.setMessage(getString(
251 R.string.unableToReadDictionaryDir,
252 dictDir.getAbsolutePath(),
253 Environment.getExternalStorageDirectory()));
254 builder.create().show();
257 onCreateSetupActionBar();
260 private void onCreateSetupActionBar() {
261 ActionBar actionBar = getSupportActionBar();
262 actionBar.setDisplayShowTitleEnabled(false);
264 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
265 filterSearchView.setIconifiedByDefault(false);
266 // filterSearchView.setIconified(false); // puts the magnifying glass in
269 filterSearchView.setQueryHint(getString(R.string.searchText));
270 filterSearchView.setSubmitButtonEnabled(false);
271 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
272 getResources().getDisplayMetrics());
273 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
274 FrameLayout.LayoutParams.WRAP_CONTENT);
275 filterSearchView.setLayoutParams(lp);
276 filterSearchView.setImeOptions(
277 EditorInfo.IME_ACTION_SEARCH |
278 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
279 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
280 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
282 EditorInfo.IME_MASK_ACTION |
283 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
285 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
287 public boolean onQueryTextSubmit(String query) {
292 public boolean onQueryTextChange(String filterText) {
297 filterSearchView.setFocusable(true);
299 actionBar.setCustomView(filterSearchView);
300 actionBar.setDisplayShowCustomEnabled(true);
304 public void onDestroy() {
306 unregisterReceiver(broadcastReceiver);
309 private static int copyStream(final InputStream in, final OutputStream out)
312 final byte[] bytes = new byte[1024 * 16];
313 while ((bytesRead = in.read(bytes)) != -1) {
314 out.write(bytes, 0, bytesRead);
322 protected void onStart() {
324 uiHandler = new Handler();
328 protected void onStop() {
334 protected void onResume() {
337 if (PreferenceActivity.prefsMightHaveChanged) {
338 PreferenceActivity.prefsMightHaveChanged = false;
340 startActivity(getIntent());
343 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
344 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
346 if (!blockAutoLaunch &&
347 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
348 prefs.contains(C.DICT_FILE) &&
349 prefs.contains(C.INDEX_SHORT_NAME)) {
350 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
351 startActivity(DictionaryActivity.getLaunchIntent(
352 new File(prefs.getString(C.DICT_FILE, "")),
353 prefs.getString(C.INDEX_SHORT_NAME, ""),
354 prefs.getString(C.SEARCH_TOKEN, "")));
359 // Remove the active dictionary from the prefs so we won't autolaunch
361 final Editor editor = prefs.edit();
362 editor.remove(C.DICT_FILE);
363 editor.remove(C.INDEX_SHORT_NAME);
364 editor.remove(C.SEARCH_TOKEN);
367 application.backgroundUpdateDictionaries(dictionaryUpdater);
373 public boolean onCreateOptionsMenu(final Menu menu) {
374 application.onCreateGlobalOptionsMenu(this, menu);
379 public void onCreateContextMenu(final ContextMenu menu, final View view,
380 final ContextMenuInfo menuInfo) {
381 super.onCreateContextMenu(menu, view, menuInfo);
382 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
384 final AdapterContextMenuInfo adapterContextMenuInfo =
385 (AdapterContextMenuInfo) menuInfo;
386 final int position = adapterContextMenuInfo.position;
387 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
389 if (row.dictionaryInfo == null) {
393 if (position > 0 && row.onDevice) {
394 final android.view.MenuItem moveToTopMenuItem =
395 menu.add(R.string.moveToTop);
396 moveToTopMenuItem.setOnMenuItemClickListener(new
397 android.view.MenuItem.OnMenuItemClickListener() {
399 public boolean onMenuItemClick(android.view.MenuItem item) {
400 application.moveDictionaryToTop(row.dictionaryInfo);
408 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
410 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
412 public boolean onMenuItemClick(android.view.MenuItem item) {
413 application.deleteDictionary(row.dictionaryInfo);
421 private void onShowDownloadableChanged() {
423 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
424 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
428 class MyListAdapter extends BaseAdapter {
430 List<DictionaryInfo> dictionariesOnDevice;
431 List<DictionaryInfo> downloadableDictionaries;
434 DictionaryInfo dictionaryInfo;
437 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
438 this.dictionaryInfo = dictinoaryInfo;
439 this.onDevice = onDevice;
443 private MyListAdapter(final String[] filters) {
444 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
445 if (showDownloadable.isChecked()) {
446 downloadableDictionaries = application.getDownloadableDictionaries(filters);
448 downloadableDictionaries = Collections.emptyList();
453 public int getCount() {
454 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
458 public Row getItem(int position) {
460 return new Row(null, true);
464 if (position < dictionariesOnDevice.size()) {
465 return new Row(dictionariesOnDevice.get(position), true);
467 position -= dictionariesOnDevice.size();
470 return new Row(null, false);
474 assert position < downloadableDictionaries.size();
475 return new Row(downloadableDictionaries.get(position), false);
479 public long getItemId(int position) {
484 public View getView(int position, View convertView, ViewGroup parent) {
485 if (convertView instanceof LinearLayout &&
486 convertView != dictionariesOnDeviceHeaderRow &&
487 convertView != downloadableDictionariesHeaderRow) {
489 * This is done to try to avoid leaking memory that used to
490 * happen on Android 4.0.3
492 ((LinearLayout) convertView).removeAllViews();
495 final Row row = getItem(position);
498 if (row.dictionaryInfo == null) {
499 return dictionariesOnDeviceHeaderRow;
501 return createDictionaryRow(row.dictionaryInfo, parent, true);
504 if (row.dictionaryInfo == null) {
505 return downloadableDictionariesHeaderRow;
507 return createDictionaryRow(row.dictionaryInfo, parent, false);
512 private void setMyListAdapater() {
513 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
515 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
516 setListAdapter(new MyListAdapter(filters));
519 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
520 final ViewGroup parent, final boolean canLaunch) {
522 View row = LayoutInflater.from(parent.getContext()).inflate(
523 R.layout.dictionary_manager_row, parent, false);
524 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
525 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
526 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
528 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
529 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
530 if (!canLaunch || updateAvailable) {
531 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
534 R.string.downloadButton,
535 downloadable.zipBytes / 1024.0 / 1024.0));
536 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
537 downloadButton.setOnClickListener(new OnClickListener() {
539 public void onClick(View arg0) {
540 downloadDictionary(downloadable.downloadUrl);
544 downloadButton.setVisibility(View.INVISIBLE);
547 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
548 final List<IndexInfo> sortedIndexInfos = application
549 .sortedIndexInfos(dictionaryInfo.indexInfos);
550 final StringBuilder builder = new StringBuilder();
551 if (updateAvailable) {
552 builder.append(getString(R.string.updateAvailable));
554 for (IndexInfo indexInfo : sortedIndexInfos) {
555 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
557 buttons.addView(button);
560 button.setOnClickListener(
561 new IntentLauncher(buttons.getContext(),
562 DictionaryActivity.getLaunchIntent(
563 application.getPath(dictionaryInfo.uncompressedFilename),
564 indexInfo.shortName, "")));
567 button.setEnabled(false);
569 if (builder.length() != 0) {
570 builder.append("; ");
572 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
573 indexInfo.mainTokenCount));
575 details.setText(builder.toString());
578 row.setClickable(true);
579 row.setOnClickListener(new IntentLauncher(parent.getContext(),
580 DictionaryActivity.getLaunchIntent(
581 application.getPath(dictionaryInfo.uncompressedFilename),
582 dictionaryInfo.indexInfos.get(0).shortName, "")));
583 row.setFocusable(true);
584 row.setLongClickable(true);
586 row.setBackgroundResource(android.R.drawable.menuitem_background);
591 private void downloadDictionary(final String downloadUrl) {
592 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
593 Request request = new Request(
594 Uri.parse(downloadUrl));
596 final String destFile = new File(new URL(downloadUrl).getFile())
598 Log.d(LOG, "Downloading to: " + destFile);
600 request.setDestinationUri(Uri.fromFile(new File(Environment
601 .getExternalStorageDirectory(), destFile)));
602 } catch (MalformedURLException e) {
603 throw new RuntimeException(e);
605 downloadManager.enqueue(request);