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) {
145 final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
147 "Download failed: status=" + status +
148 ", reason=" + reason);
149 String msg = Integer.toString(reason);
151 case DownloadManager.ERROR_FILE_ALREADY_EXISTS: msg = "File exists"; break;
152 case DownloadManager.ERROR_FILE_ERROR: msg = "File error"; break;
153 case DownloadManager.ERROR_INSUFFICIENT_SPACE: msg = "Not enough space"; break;
155 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, reason)).setNeutralButton("Close", null).show();
159 Log.w(LOG, "Download finished: " + dest);
160 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
161 Toast.LENGTH_LONG).show();
164 final File localZipFile = new File(Uri.parse(dest).getPath());
166 ZipFile zipFile = new ZipFile(localZipFile);
167 final ZipEntry zipEntry = zipFile.entries().nextElement();
168 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
169 final InputStream zipIn = zipFile.getInputStream(zipEntry);
170 File targetFile = new File(application.getDictDir(), zipEntry.getName());
171 if (targetFile.exists()) {
172 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
173 targetFile = new File(application.getDictDir(), zipEntry.getName());
175 final OutputStream zipOut = new FileOutputStream(targetFile);
176 copyStream(zipIn, zipOut);
178 application.backgroundUpdateDictionaries(dictionaryUpdater);
179 Toast.makeText(context, getString(R.string.installationFinished, dest),
180 Toast.LENGTH_LONG).show();
181 } catch (Exception e) {
182 String msg = getString(R.string.unzippingFailed, dest);
183 File dir = application.getDictDir();
184 if (!dir.canWrite() || !application.checkFileCreate(dir)) {
185 msg = getString(R.string.notWritable, dir.getAbsolutePath());
187 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
188 Log.e(LOG, "Failed to unzip.", e);
190 localZipFile.delete();
196 public static Intent getLaunchIntent(Context c) {
197 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
198 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
203 public void onCreate(Bundle savedInstanceState) {
204 // This must be first, otherwise the actiona bar doesn't get
206 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
208 super.onCreate(savedInstanceState);
209 Log.d(LOG, "onCreate:" + this);
211 application = (DictionaryApplication) getApplication();
213 blockAutoLaunch = false;
216 setContentView(R.layout.dictionary_manager_activity);
218 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
219 getListView().getContext()).inflate(
220 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
222 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
223 getListView().getContext()).inflate(
224 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
226 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
227 .findViewById(R.id.hideDownloadable);
228 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
230 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
231 onShowDownloadableChanged();
235 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
236 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
237 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
238 thanksForUpdatingLatestVersion)) {
239 blockAutoLaunch = true;
240 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
241 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
245 registerReceiver(broadcastReceiver, new IntentFilter(
246 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
249 registerForContextMenu(getListView());
251 final File dictDir = application.getDictDir();
252 if (!dictDir.canRead() || !dictDir.canExecute()) {
253 blockAutoLaunch = true;
255 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
256 builder.setTitle(getString(R.string.error));
257 builder.setMessage(getString(
258 R.string.unableToReadDictionaryDir,
259 dictDir.getAbsolutePath(),
260 Environment.getExternalStorageDirectory()));
261 builder.setNeutralButton("Close", null);
262 builder.create().show();
265 onCreateSetupActionBar();
268 private void onCreateSetupActionBar() {
269 ActionBar actionBar = getSupportActionBar();
270 actionBar.setDisplayShowTitleEnabled(false);
272 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
273 filterSearchView.setIconifiedByDefault(false);
274 // filterSearchView.setIconified(false); // puts the magnifying glass in
277 filterSearchView.setQueryHint(getString(R.string.searchText));
278 filterSearchView.setSubmitButtonEnabled(false);
279 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
280 getResources().getDisplayMetrics());
281 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
282 FrameLayout.LayoutParams.WRAP_CONTENT);
283 filterSearchView.setLayoutParams(lp);
284 filterSearchView.setImeOptions(
285 EditorInfo.IME_ACTION_SEARCH |
286 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
287 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
288 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
290 EditorInfo.IME_MASK_ACTION |
291 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
293 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
295 public boolean onQueryTextSubmit(String query) {
300 public boolean onQueryTextChange(String filterText) {
305 filterSearchView.setFocusable(true);
307 actionBar.setCustomView(filterSearchView);
308 actionBar.setDisplayShowCustomEnabled(true);
312 public void onDestroy() {
314 unregisterReceiver(broadcastReceiver);
317 private static int copyStream(final InputStream in, final OutputStream out)
320 final byte[] bytes = new byte[1024 * 16];
321 while ((bytesRead = in.read(bytes)) != -1) {
322 out.write(bytes, 0, bytesRead);
330 protected void onStart() {
332 uiHandler = new Handler();
336 protected void onStop() {
342 protected void onResume() {
345 if (PreferenceActivity.prefsMightHaveChanged) {
346 PreferenceActivity.prefsMightHaveChanged = false;
348 startActivity(getIntent());
351 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
352 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
354 if (!blockAutoLaunch &&
355 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
356 prefs.contains(C.DICT_FILE) &&
357 prefs.contains(C.INDEX_SHORT_NAME)) {
358 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
359 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
360 new File(prefs.getString(C.DICT_FILE, "")),
361 prefs.getString(C.INDEX_SHORT_NAME, ""),
362 prefs.getString(C.SEARCH_TOKEN, "")));
367 // Remove the active dictionary from the prefs so we won't autolaunch
369 final Editor editor = prefs.edit();
370 editor.remove(C.DICT_FILE);
371 editor.remove(C.INDEX_SHORT_NAME);
372 editor.remove(C.SEARCH_TOKEN);
375 application.backgroundUpdateDictionaries(dictionaryUpdater);
381 public boolean onCreateOptionsMenu(final Menu menu) {
382 application.onCreateGlobalOptionsMenu(this, menu);
387 public void onCreateContextMenu(final ContextMenu menu, final View view,
388 final ContextMenuInfo menuInfo) {
389 super.onCreateContextMenu(menu, view, menuInfo);
390 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
392 final AdapterContextMenuInfo adapterContextMenuInfo =
393 (AdapterContextMenuInfo) menuInfo;
394 final int position = adapterContextMenuInfo.position;
395 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
397 if (row.dictionaryInfo == null) {
401 if (position > 0 && row.onDevice) {
402 final android.view.MenuItem moveToTopMenuItem =
403 menu.add(R.string.moveToTop);
404 moveToTopMenuItem.setOnMenuItemClickListener(new
405 android.view.MenuItem.OnMenuItemClickListener() {
407 public boolean onMenuItemClick(android.view.MenuItem item) {
408 application.moveDictionaryToTop(row.dictionaryInfo);
416 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
418 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
420 public boolean onMenuItemClick(android.view.MenuItem item) {
421 application.deleteDictionary(row.dictionaryInfo);
429 private void onShowDownloadableChanged() {
431 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
432 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
436 class MyListAdapter extends BaseAdapter {
438 List<DictionaryInfo> dictionariesOnDevice;
439 List<DictionaryInfo> downloadableDictionaries;
442 DictionaryInfo dictionaryInfo;
445 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
446 this.dictionaryInfo = dictinoaryInfo;
447 this.onDevice = onDevice;
451 private MyListAdapter(final String[] filters) {
452 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
453 if (showDownloadable.isChecked()) {
454 downloadableDictionaries = application.getDownloadableDictionaries(filters);
456 downloadableDictionaries = Collections.emptyList();
461 public int getCount() {
462 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
466 public Row getItem(int position) {
468 return new Row(null, true);
472 if (position < dictionariesOnDevice.size()) {
473 return new Row(dictionariesOnDevice.get(position), true);
475 position -= dictionariesOnDevice.size();
478 return new Row(null, false);
482 assert position < downloadableDictionaries.size();
483 return new Row(downloadableDictionaries.get(position), false);
487 public long getItemId(int position) {
492 public View getView(int position, View convertView, ViewGroup parent) {
493 if (convertView instanceof LinearLayout &&
494 convertView != dictionariesOnDeviceHeaderRow &&
495 convertView != downloadableDictionariesHeaderRow) {
497 * This is done to try to avoid leaking memory that used to
498 * happen on Android 4.0.3
500 ((LinearLayout) convertView).removeAllViews();
503 final Row row = getItem(position);
506 if (row.dictionaryInfo == null) {
507 return dictionariesOnDeviceHeaderRow;
509 return createDictionaryRow(row.dictionaryInfo, parent, true);
512 if (row.dictionaryInfo == null) {
513 return downloadableDictionariesHeaderRow;
515 return createDictionaryRow(row.dictionaryInfo, parent, false);
520 private void setMyListAdapater() {
521 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
523 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
524 setListAdapter(new MyListAdapter(filters));
527 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
528 final ViewGroup parent, boolean canLaunch) {
530 View row = LayoutInflater.from(parent.getContext()).inflate(
531 R.layout.dictionary_manager_row, parent, false);
532 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
533 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
534 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
536 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
537 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
538 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
539 boolean broken = false;
540 if (!dictionaryInfo.isValid()) {
544 if (downloadable != null && (!canLaunch || updateAvailable)) {
547 R.string.downloadButton,
548 downloadable.zipBytes / 1024.0 / 1024.0));
549 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
550 downloadButton.setOnClickListener(new OnClickListener() {
552 public void onClick(View arg0) {
553 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
557 downloadButton.setVisibility(View.INVISIBLE);
560 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
561 final List<IndexInfo> sortedIndexInfos = application
562 .sortedIndexInfos(dictionaryInfo.indexInfos);
563 final StringBuilder builder = new StringBuilder();
564 if (updateAvailable) {
565 builder.append(getString(R.string.updateAvailable));
567 for (IndexInfo indexInfo : sortedIndexInfos) {
568 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
570 buttons.addView(button);
573 button.setOnClickListener(
574 new IntentLauncher(buttons.getContext(),
575 DictionaryActivity.getLaunchIntent(getApplicationContext(),
576 application.getPath(dictionaryInfo.uncompressedFilename),
577 indexInfo.shortName, "")));
580 button.setEnabled(false);
582 if (builder.length() != 0) {
583 builder.append("; ");
585 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
586 indexInfo.mainTokenCount));
588 if (downloadable != null || dictionaryInfo != null) {
589 builder.append("; ");
590 builder.append(getString(R.string.downloadButton, (dictionaryInfo != null ? dictionaryInfo.uncompressedBytes : downloadable.uncompressedBytes) / 1024.0 / 1024.0));
593 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
594 builder.append("; Cannot be used, redownload, check hardware/file system");
595 // Allow deleting, but cannot open
596 row.setLongClickable(true);
598 details.setText(builder.toString());
601 row.setClickable(true);
602 row.setOnClickListener(new IntentLauncher(parent.getContext(),
603 DictionaryActivity.getLaunchIntent(getApplicationContext(),
604 application.getPath(dictionaryInfo.uncompressedFilename),
605 dictionaryInfo.indexInfos.get(0).shortName, "")));
606 row.setFocusable(true);
607 row.setLongClickable(true);
609 row.setBackgroundResource(android.R.drawable.menuitem_background);
614 private void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
615 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
616 final DownloadManager.Query query = new DownloadManager.Query();
617 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
618 final Cursor cursor = downloadManager.query(query);
619 while (cursor.moveToNext()) {
620 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
623 if (!cursor.isAfterLast()) {
624 downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
627 R.string.downloadButton,
628 bytes / 1024.0 / 1024.0));
633 Request request = new Request(
634 Uri.parse(downloadUrl));
636 final String destFile = new File(new URL(downloadUrl).getFile())
638 Log.d(LOG, "Downloading to: " + destFile);
640 request.setDestinationInExternalFilesDir(getApplicationContext(), null, destFile);
641 } catch (MalformedURLException e) {
642 throw new RuntimeException(e);
644 downloadManager.enqueue(request);
645 downloadButton.setText("X");