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.annotation.SuppressLint;
18 import android.app.Dialog;
19 import android.content.Context;
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.graphics.Color;
23 import android.graphics.Typeface;
24 import android.net.Uri;
25 import android.os.Bundle;
26 import android.os.Handler;
27 import android.preference.PreferenceManager;
28 import android.speech.tts.TextToSpeech;
29 import android.speech.tts.TextToSpeech.OnInitListener;
30 import android.text.ClipboardManager;
31 import android.text.Editable;
32 import android.text.Selection;
33 import android.text.Spannable;
34 import android.text.TextWatcher;
35 import android.text.method.LinkMovementMethod;
36 import android.text.style.ClickableSpan;
37 import android.text.style.StyleSpan;
38 import android.util.Log;
39 import android.util.TypedValue;
40 import android.view.ContextMenu;
41 import android.view.ContextMenu.ContextMenuInfo;
42 import android.view.KeyEvent;
43 import android.view.LayoutInflater;
44 import android.view.MotionEvent;
45 import android.view.View;
46 import android.view.View.OnClickListener;
47 import android.view.View.OnFocusChangeListener;
48 import android.view.View.OnLongClickListener;
49 import android.view.ViewGroup;
50 import android.view.WindowManager;
51 import android.view.inputmethod.EditorInfo;
52 import android.view.inputmethod.InputMethodManager;
53 import android.widget.AdapterView.AdapterContextMenuInfo;
54 import android.widget.BaseAdapter;
55 import android.widget.Button;
56 import android.widget.EditText;
57 import android.widget.FrameLayout;
58 import android.widget.ImageButton;
59 import android.widget.ImageView;
60 import android.widget.LinearLayout;
61 import android.widget.ListAdapter;
62 import android.widget.ListView;
63 import android.widget.TableLayout;
64 import android.widget.TableRow;
65 import android.widget.TextView;
66 import android.widget.TextView.BufferType;
67 import android.widget.Toast;
69 import com.actionbarsherlock.app.ActionBar;
70 import com.actionbarsherlock.app.SherlockListActivity;
71 import com.actionbarsherlock.view.Menu;
72 import com.actionbarsherlock.view.MenuItem;
73 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
74 import com.actionbarsherlock.widget.SearchView;
75 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
76 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
77 import com.hughes.android.dictionary.engine.Dictionary;
78 import com.hughes.android.dictionary.engine.EntrySource;
79 import com.hughes.android.dictionary.engine.HtmlEntry;
80 import com.hughes.android.dictionary.engine.Index;
81 import com.hughes.android.dictionary.engine.Index.IndexEntry;
82 import com.hughes.android.dictionary.engine.Language;
83 import com.hughes.android.dictionary.engine.Language.LanguageResources;
84 import com.hughes.android.dictionary.engine.PairEntry;
85 import com.hughes.android.dictionary.engine.PairEntry.Pair;
86 import com.hughes.android.dictionary.engine.RowBase;
87 import com.hughes.android.dictionary.engine.TokenRow;
88 import com.hughes.android.dictionary.engine.TransliteratorManager;
89 import com.hughes.android.util.IntentLauncher;
90 import com.hughes.android.util.NonLinkClickableSpan;
91 import com.hughes.util.StringUtil;
94 import java.io.FileWriter;
95 import java.io.IOException;
96 import java.io.PrintWriter;
97 import java.io.RandomAccessFile;
98 import java.text.SimpleDateFormat;
99 import java.util.Arrays;
100 import java.util.Collections;
101 import java.util.Date;
102 import java.util.HashMap;
103 import java.util.LinkedHashSet;
104 import java.util.List;
105 import java.util.Locale;
106 import java.util.Random;
107 import java.util.Set;
108 import java.util.concurrent.Executor;
109 import java.util.concurrent.Executors;
110 import java.util.concurrent.ThreadFactory;
111 import java.util.concurrent.atomic.AtomicBoolean;
112 import java.util.regex.Matcher;
113 import java.util.regex.Pattern;
115 public class DictionaryActivity extends SherlockListActivity {
117 static final String LOG = "QuickDic";
119 DictionaryApplication application;
121 File dictFile = null;
122 RandomAccessFile dictRaf = null;
124 Dictionary dictionary = null;
130 List<RowBase> rowsToShow = null; // if not null, just show these rows.
132 final Handler uiHandler = new Handler();
134 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
136 public Thread newThread(Runnable r) {
137 return new Thread(r, "searchExecutor");
141 private SearchOperation currentSearchOperation = null;
144 TextToSpeech textToSpeech;
145 volatile boolean ttsReady;
148 C.Theme theme = C.Theme.LIGHT;
149 int textColorFg = Color.BLACK;
152 SearchView searchView;
153 ImageView searchHintIcon;
154 SearchView.OnQueryTextListener onQueryTextListener;
156 MenuItem nextWordMenuItem, previousWordMenuItem;
159 private File wordList = null;
160 private boolean saveOnlyFirstSubentry = false;
161 private boolean clickOpensContextMenu = false;
163 // Visible for testing.
164 ListAdapter indexAdapter = null;
167 * For some languages, loading the transliterators used in this search takes
168 * a long time, so we fire it up on a different thread, and don't invoke it
169 * from the main thread until it's already finished once.
171 private volatile boolean indexPrepFinished = false;
173 public DictionaryActivity() {
176 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
177 final String searchToken) {
178 final Intent intent = new Intent();
179 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
180 DictionaryActivity.class.getName());
181 intent.putExtra(C.DICT_FILE, dictFile.getPath());
182 intent.putExtra(C.INDEX_INDEX, indexIndex);
183 intent.putExtra(C.SEARCH_TOKEN, searchToken);
188 protected void onSaveInstanceState(final Bundle outState) {
189 super.onSaveInstanceState(outState);
190 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
191 outState.putInt(C.INDEX_INDEX, indexIndex);
192 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
196 protected void onRestoreInstanceState(final Bundle outState) {
197 super.onRestoreInstanceState(outState);
198 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
203 public void onCreate(Bundle savedInstanceState) {
204 Log.d(LOG, "onCreate:" + this);
205 super.onCreate(savedInstanceState);
207 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
209 // Don't auto-launch if this fails.
210 prefs.edit().remove(C.INDEX_INDEX).commit();
212 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
214 application = (DictionaryApplication) getApplication();
215 theme = application.getSelectedTheme();
216 textColorFg = getResources().getColor(theme.tokenRowFgColor);
218 final Intent intent = getIntent();
219 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
222 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
224 public void onInit(int status) {
231 final String name = application.getDictionaryName(dictFile.getName());
232 this.setTitle("QuickDic: " + name);
233 dictRaf = new RandomAccessFile(dictFile, "r");
234 dictionary = new Dictionary(dictRaf);
235 } catch (Exception e) {
236 Log.e(LOG, "Unable to load dictionary.", e);
237 if (dictRaf != null) {
240 } catch (IOException e1) {
241 Log.e(LOG, "Unable to close dictRaf.", e1);
245 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
246 Toast.LENGTH_LONG).show();
247 startActivity(DictionaryManagerActivity.getLaunchIntent());
251 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
252 if (savedInstanceState != null) {
253 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
255 indexIndex %= dictionary.indices.size();
256 Log.d(LOG, "Loading index " + indexIndex);
257 index = dictionary.indices.get(indexIndex);
258 setListAdapter(new IndexAdapter(index));
260 // Pre-load the collators.
261 new Thread(new Runnable() {
263 final long startMillis = System.currentTimeMillis();
265 TransliteratorManager.init(new TransliteratorManager.Callback() {
267 public void onTransliteratorReady() {
268 uiHandler.post(new Runnable() {
271 onSearchTextChange(searchView.getQuery().toString());
277 for (final Index index : dictionary.indices) {
278 final String searchToken = index.sortedIndexEntries.get(0).token;
279 final IndexEntry entry = index.findExact(searchToken);
280 if (!searchToken.equals(entry.token)) {
281 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
284 indexPrepFinished = true;
285 } catch (Exception e) {
287 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
289 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
293 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
294 if ("SYSTEM".equals(fontName)) {
295 typeface = Typeface.DEFAULT;
298 typeface = Typeface.createFromAsset(getAssets(), fontName);
299 } catch (Exception e) {
300 Log.w(LOG, "Exception trying to use typeface, using default.", e);
301 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
302 Toast.LENGTH_LONG).show();
305 if (typeface == null) {
306 Log.w(LOG, "Unable to create typeface, using default.");
307 typeface = Typeface.DEFAULT;
309 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
311 fontSizeSp = Integer.parseInt(fontSize.trim());
312 } catch (NumberFormatException e) {
316 setContentView(R.layout.dictionary_activity);
319 registerForContextMenu(getListView());
322 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
323 getString(R.string.wordListFileDefault)));
324 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
326 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
328 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
330 onCreateSetupActionBarAndSearchView();
332 // Set the search text from the intent, then the saved state.
333 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
334 if (savedInstanceState != null) {
335 text = savedInstanceState.getString(C.SEARCH_TOKEN);
340 setSearchText(text, true);
341 Log.d(LOG, "Trying to restore searchText=" + text);
343 setDictionaryPrefs(this, dictFile, indexIndex, searchView.getQuery().toString());
348 private void onCreateSetupActionBarAndSearchView() {
349 ActionBar actionBar = getSupportActionBar();
350 actionBar.setDisplayShowTitleEnabled(false);
352 searchView = new SearchView(getSupportActionBar().getThemedContext());
353 searchView.setIconifiedByDefault(false);
354 // searchView.setIconified(false); // puts the magifying glass in the
356 searchView.setQueryHint(getString(R.string.searchText));
357 searchView.setSubmitButtonEnabled(false);
358 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
359 getResources().getDisplayMetrics());
360 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
361 FrameLayout.LayoutParams.WRAP_CONTENT);
362 searchView.setLayoutParams(lp);
363 searchView.setImeOptions(
364 EditorInfo.IME_ACTION_SEARCH |
365 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
366 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
367 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
369 EditorInfo.IME_MASK_ACTION |
370 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
371 onQueryTextListener = new OnQueryTextListener() {
373 public boolean onQueryTextSubmit(String query) {
374 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
379 public boolean onQueryTextChange(String newText) {
380 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
381 onSearchTextChange(searchView.getQuery().toString());
385 searchView.setOnQueryTextListener(onQueryTextListener);
387 searchHintIcon = (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
388 searchHintIcon.setOnClickListener(new OnClickListener() {
390 public void onClick(View arg0) {
391 onLanguageButtonClick();
394 searchHintIcon.setOnLongClickListener(new OnLongClickListener() {
396 public boolean onLongClick(View v) {
397 onLanguageButtonLongClick(v.getContext());
401 actionBar.setCustomView(searchView);
402 actionBar.setDisplayShowCustomEnabled(true);
406 protected void onResume() {
407 Log.d(LOG, "onResume");
409 if (SettingsActivity.settingsMightHaveChanged) {
410 SettingsActivity.settingsMightHaveChanged = false;
412 startActivity(getIntent());
418 protected void onPause() {
424 * Invoked when MyWebView returns, since the user might have clicked some
425 * hypertext in the MyWebView.
427 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
428 super.onActivityResult(requestCode, resultCode, result);
429 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
430 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
431 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
435 private static void setDictionaryPrefs(final Context context, final File dictFile,
436 final int indexIndex, final String searchToken) {
437 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
439 prefs.putString(C.DICT_FILE, dictFile.getPath());
440 prefs.putInt(C.INDEX_INDEX, indexIndex);
441 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
446 protected void onDestroy() {
448 if (dictRaf == null) {
452 final SearchOperation searchOperation = currentSearchOperation;
453 currentSearchOperation = null;
455 // Before we close the RAF, we have to wind the current search down.
456 if (searchOperation != null) {
457 Log.d(LOG, "Interrupting search to shut down.");
458 currentSearchOperation = null;
459 searchOperation.interrupted.set(true);
463 Log.d(LOG, "Closing RAF.");
465 } catch (IOException e) {
466 Log.e(LOG, "Failed to close dictionary", e);
471 // --------------------------------------------------------------------------
473 // --------------------------------------------------------------------------
475 private void showKeyboard() {
476 // searchText.postDelayed(new Runnable() {
478 // public void run() {
479 // Log.d(LOG, "Trying to show soft keyboard.");
480 // final boolean searchTextHadFocus = searchText.hasFocus();
481 // searchText.requestFocus();
482 // final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
483 // manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
484 // if (!searchTextHadFocus) {
485 // defocusSearchText();
490 void updateLangButton() {
491 final LanguageResources languageResources =
492 Language.isoCodeToResources.get(index.shortName);
493 if (languageResources != null && languageResources.flagId != 0) {
494 searchHintIcon.setImageResource(languageResources.flagId);
496 if (indexIndex % 2 == 0) {
497 searchHintIcon.setImageResource(android.R.drawable.ic_media_next);
499 searchHintIcon.setImageResource(android.R.drawable.ic_media_previous);
505 private void updateTTSLanuage() {
506 if (!ttsReady || index == null || textToSpeech == null) {
507 Log.d(LOG, "Can't updateTTSLanguage.");
510 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
511 Log.d(LOG, "Setting TTS locale to: " + locale);
512 final int ttsResult = textToSpeech.setLanguage(locale);
513 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
514 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
515 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
519 void onLanguageButtonClick() {
520 if (currentSearchOperation != null) {
521 currentSearchOperation.interrupted.set(true);
522 currentSearchOperation = null;
524 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(), searchView.getQuery().toString());
527 void onLanguageButtonLongClick(final Context context) {
528 final Dialog dialog = new Dialog(context);
529 dialog.setContentView(R.layout.select_dictionary_dialog);
530 dialog.setTitle(R.string.selectDictionary);
532 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
535 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
537 final Button button = new Button(listView.getContext());
538 final String name = getString(R.string.dictionaryManager);
539 button.setText(name);
540 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
541 DictionaryManagerActivity.getLaunchIntent()) {
543 protected void onGo() {
545 DictionaryActivity.this.finish();
548 button.setOnClickListener(intentLauncher);
549 listView.addHeaderView(button);
551 listView.setAdapter(new BaseAdapter() {
553 public View getView(int position, View convertView, ViewGroup parent) {
554 final DictionaryInfo dictionaryInfo = getItem(position);
556 final LinearLayout result = new LinearLayout(parent.getContext());
558 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
560 final TextView dash = new TextView(parent.getContext());
562 result.addView(dash);
565 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
566 final Button button = new Button(parent.getContext());
567 button.setText(indexInfo.shortName);
568 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
570 application.getPath(dictionaryInfo.uncompressedFilename),
571 i, searchView.getQuery().toString())) {
573 protected void onGo() {
575 DictionaryActivity.this.finish();
578 button.setOnClickListener(intentLauncher);
579 result.addView(button);
583 final TextView nameView = new TextView(parent.getContext());
584 final String name = application
585 .getDictionaryName(dictionaryInfo.uncompressedFilename);
586 nameView.setText(name);
587 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
588 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
589 layoutParams.width = 0;
590 layoutParams.weight = 1.0f;
591 nameView.setLayoutParams(layoutParams);
592 result.addView(nameView);
598 public long getItemId(int position) {
603 public DictionaryInfo getItem(int position) {
604 return installedDicts.get(position);
608 public int getCount() {
609 return installedDicts.size();
616 void onUpDownButton(final boolean up) {
620 final int firstVisibleRow = getListView().getFirstVisiblePosition();
621 final RowBase row = index.rows.get(firstVisibleRow);
622 final TokenRow tokenRow = row.getTokenRow(true);
623 final int destIndexEntry;
625 if (row != tokenRow) {
626 destIndexEntry = tokenRow.referenceIndex;
628 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
632 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
634 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
635 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
636 setSearchText(dest.token, false);
637 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
641 // --------------------------------------------------------------------------
643 // --------------------------------------------------------------------------
645 final Random random = new Random();
648 public boolean onCreateOptionsMenu(final Menu menu) {
650 if (PreferenceManager.getDefaultSharedPreferences(this)
651 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
653 nextWordMenuItem = menu.add(getString(R.string.nextWord))
654 .setIcon(R.drawable.arrow_down_float);
655 nextWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
656 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
658 public boolean onMenuItemClick(MenuItem item) {
659 onUpDownButton(false);
665 previousWordMenuItem = menu.add(getString(R.string.previousWord))
666 .setIcon(R.drawable.arrow_up_float);
667 previousWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
668 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
670 public boolean onMenuItemClick(MenuItem item) {
671 onUpDownButton(true);
677 application.onCreateGlobalOptionsMenu(this, menu);
680 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
681 dictionaryList.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
682 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
683 public boolean onMenuItemClick(final MenuItem menuItem) {
684 startActivity(DictionaryManagerActivity.getLaunchIntent());
692 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
693 aboutDictionary.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
694 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
695 public boolean onMenuItemClick(final MenuItem menuItem) {
696 final Context context = getListView().getContext();
697 final Dialog dialog = new Dialog(context);
698 dialog.setContentView(R.layout.about_dictionary_dialog);
699 final TextView textView = (TextView) dialog.findViewById(R.id.text);
701 final String name = application.getDictionaryName(dictFile.getName());
702 dialog.setTitle(name);
704 final StringBuilder builder = new StringBuilder();
705 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
706 dictionaryInfo.uncompressedBytes = dictFile.length();
707 if (dictionaryInfo != null) {
708 builder.append(dictionaryInfo.dictInfo).append("\n\n");
709 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
712 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
715 getString(R.string.dictionaryCreationTime,
716 dictionaryInfo.creationMillis)).append("\n");
717 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
718 builder.append("\n");
719 builder.append(getString(R.string.indexName, indexInfo.shortName))
722 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
725 builder.append("\n");
726 builder.append(getString(R.string.sources)).append("\n");
727 for (final EntrySource source : dictionary.sources) {
729 getString(R.string.sourceInfo, source.getName(),
730 source.getNumEntries())).append("\n");
733 textView.setText(builder.toString());
736 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
737 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
738 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
739 dialog.getWindow().setAttributes(layoutParams);
748 // --------------------------------------------------------------------------
749 // Context Menu + clicks
750 // --------------------------------------------------------------------------
753 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
754 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
755 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
757 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
758 wordList.getName()));
759 addToWordlist.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
760 public boolean onMenuItemClick(android.view.MenuItem item) {
761 onAppendToWordList(row);
766 final android.view.MenuItem share = menu.add("Share");
767 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
768 public boolean onMenuItemClick(android.view.MenuItem item) {
769 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
770 shareIntent.setType("text/plain");
771 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true).getToken());
772 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, row.getRawText(saveOnlyFirstSubentry));
773 startActivity(shareIntent);
778 final android.view.MenuItem copy = menu.add(android.R.string.copy);
779 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
780 public boolean onMenuItemClick(android.view.MenuItem item) {
786 if (selectedSpannableText != null) {
787 final String selectedText = selectedSpannableText;
788 final android.view.MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
789 selectedSpannableText));
790 searchForSelection.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
791 public boolean onMenuItemClick(android.view.MenuItem item) {
792 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
798 if (row instanceof TokenRow && ttsReady) {
799 final android.view.MenuItem speak = menu.add(R.string.speak);
800 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
802 public boolean onMenuItemClick(android.view.MenuItem item) {
803 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
804 new HashMap<String, String>());
811 private void jumpToTextFromHyperLink(
812 final String selectedText, final int defaultIndexToUse) {
814 for (int i = 0; i < dictionary.indices.size(); ++i) {
815 final Index index = dictionary.indices.get(i);
816 if (indexPrepFinished) {
817 System.out.println("Doing index lookup: on " + selectedText);
818 final IndexEntry indexEntry = index.findExact(selectedText);
819 if (indexEntry != null) {
820 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
822 if (tokenRow != null && tokenRow.hasMainEntry) {
828 Log.w(LOG, "Skipping findExact on index " + index.shortName);
831 if (indexToUse == -1) {
832 indexToUse = defaultIndexToUse;
834 setIndexAndSearchText(indexToUse, selectedText);
838 * Called when user clicks outside of search text, so that they can start
839 * typing again immediately.
841 void defocusSearchText() {
842 // Log.d(LOG, "defocusSearchText");
843 // Request focus so that if we start typing again, it clears the text
845 getListView().requestFocus();
847 // Visual indication that a new keystroke will clear the search text.
848 // Doesn't seem to work unless earchText has focus.
849 // searchView.selectAll();
853 protected void onListItemClick(ListView l, View v, int row, long id) {
855 if (clickOpensContextMenu && dictRaf != null) {
860 @SuppressLint("SimpleDateFormat")
861 void onAppendToWordList(final RowBase row) {
864 final StringBuilder rawText = new StringBuilder();
865 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
866 rawText.append(index.longName).append("\t");
867 rawText.append(row.getTokenRow(true).getToken()).append("\t");
868 rawText.append(row.getRawText(saveOnlyFirstSubentry));
869 Log.d(LOG, "Writing : " + rawText);
872 wordList.getParentFile().mkdirs();
873 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
874 out.println(rawText.toString());
876 } catch (IOException e) {
877 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
879 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
880 Toast.LENGTH_LONG).show();
885 @SuppressWarnings("deprecation")
886 void onCopy(final RowBase row) {
889 Log.d(LOG, "Copy, row=" + row);
890 final StringBuilder result = new StringBuilder();
891 result.append(row.getRawText(false));
892 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
893 clipboardManager.setText(result.toString());
894 Log.d(LOG, "Copied: " + result);
898 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
899 if (event.getUnicodeChar() != 0) {
900 if (!searchView.hasFocus()) {
901 setSearchText("" + (char) event.getUnicodeChar(), true);
903 searchView.requestFocus();
906 if (keyCode == KeyEvent.KEYCODE_BACK) {
907 // Log.d(LOG, "Clearing dictionary prefs.");
908 // Pretend that we just autolaunched so that we won't do it again.
909 // DictionaryManagerActivity.lastAutoLaunchMillis =
910 // System.currentTimeMillis();
912 if (keyCode == KeyEvent.KEYCODE_ENTER) {
913 Log.d(LOG, "Trying to hide soft keyboard.");
914 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
915 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
916 InputMethodManager.HIDE_NOT_ALWAYS);
919 return super.onKeyDown(keyCode, event);
922 private void setIndexAndSearchText(int newIndex, String newSearchText) {
923 Log.d(LOG, "Changing index to: " + newIndex);
924 if (newIndex == -1) {
925 Log.e(LOG, "Invalid index.");
928 if (newIndex != indexIndex) {
929 indexIndex = newIndex;
930 index = dictionary.indices.get(indexIndex);
931 indexAdapter = new IndexAdapter(index);
932 setListAdapter(indexAdapter);
933 Log.d(LOG, "changingIndex, newLang=" + index.longName);
934 setDictionaryPrefs(this, dictFile, indexIndex, searchView.getQuery().toString());
937 setSearchText(newSearchText, true);
940 private void setSearchText(final String text, final boolean triggerSearch) {
941 if (!triggerSearch) {
942 searchView.setOnQueryTextListener(null);
944 searchView.setQuery(text, false);
946 if (!triggerSearch) {
947 searchView.setOnQueryTextListener(onQueryTextListener);
949 onQueryTextListener.onQueryTextChange(text);
953 // private long cursorDelayMillis = 100;
954 private void moveCursorToRight() {
955 // if (searchText.getLayout() != null) {
956 // cursorDelayMillis = 100;
957 // // Surprising, but this can crash when you rotate...
958 // Selection.moveToRightEdge(searchView.getQuery(), searchText.getLayout());
960 // uiHandler.postDelayed(new Runnable() {
962 // public void run() {
963 // moveCursorToRight();
965 // }, cursorDelayMillis);
966 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
970 // --------------------------------------------------------------------------
972 // --------------------------------------------------------------------------
974 private void searchFinished(final SearchOperation searchOperation) {
975 if (searchOperation.interrupted.get()) {
976 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
979 if (searchOperation != this.currentSearchOperation) {
980 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
984 final Index.IndexEntry searchResult = searchOperation.searchResult;
985 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
987 currentSearchOperation = null;
988 uiHandler.postDelayed(new Runnable() {
991 if (currentSearchOperation == null) {
992 if (searchResult != null) {
996 jumpToRow(searchResult.startRow);
997 } else if (searchOperation.multiWordSearchResult != null) {
998 // Multi-row search....
999 setFiltered(searchOperation);
1001 throw new IllegalStateException("This should never happen.");
1004 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1010 private final void jumpToRow(final int row) {
1011 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1012 // getListView().requestFocusFromTouch();
1013 getListView().setSelectionFromTop(row, 0);
1014 getListView().setSelected(true);
1017 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1019 final class SearchOperation implements Runnable {
1021 final AtomicBoolean interrupted = new AtomicBoolean(false);
1023 final String searchText;
1025 List<String> searchTokens; // filled in for multiWord.
1029 long searchStartMillis;
1031 Index.IndexEntry searchResult;
1033 List<RowBase> multiWordSearchResult;
1035 boolean done = false;
1037 SearchOperation(final String searchText, final Index index) {
1038 this.searchText = StringUtil.normalizeWhitespace(searchText);
1042 public String toString() {
1043 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1049 searchStartMillis = System.currentTimeMillis();
1050 final String[] searchTokenArray = WHITESPACE.split(searchText);
1051 if (searchTokenArray.length == 1) {
1052 searchResult = index.findInsertionPoint(searchText, interrupted);
1054 searchTokens = Arrays.asList(searchTokenArray);
1055 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens, interrupted);
1058 "searchText=" + searchText + ", searchDuration="
1059 + (System.currentTimeMillis() - searchStartMillis)
1060 + ", interrupted=" + interrupted.get());
1061 if (!interrupted.get()) {
1062 uiHandler.post(new Runnable() {
1065 searchFinished(SearchOperation.this);
1069 Log.d(LOG, "interrupted, skipping searchFinished.");
1071 } catch (Exception e) {
1072 Log.e(LOG, "Failure during search (can happen during Activity close.");
1074 synchronized (this) {
1082 // --------------------------------------------------------------------------
1084 // --------------------------------------------------------------------------
1086 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1087 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1089 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1090 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1092 final class IndexAdapter extends BaseAdapter {
1094 private static final float PADDING_DEFAULT_DP = 8;
1096 private static final float PADDING_LARGE_DP = 16;
1100 final List<RowBase> rows;
1102 final Set<String> toHighlight;
1104 private int mPaddingDefault;
1106 private int mPaddingLarge;
1108 IndexAdapter(final Index index) {
1111 this.toHighlight = null;
1115 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1118 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1122 private void getMetrics() {
1123 // Get the screen's density scale
1124 final float scale = getResources().getDisplayMetrics().density;
1125 // Convert the dps to pixels, based on density scale
1126 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1127 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1131 public int getCount() {
1136 public RowBase getItem(int position) {
1137 return rows.get(position);
1141 public long getItemId(int position) {
1142 return getItem(position).index();
1146 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1147 final TableLayout result;
1148 if (convertView instanceof TableLayout) {
1149 result = (TableLayout) convertView;
1150 result.removeAllViews();
1152 result = new TableLayout(parent.getContext());
1154 final RowBase row = getItem(position);
1155 if (row instanceof PairEntry.Row) {
1156 return getView(position, (PairEntry.Row) row, parent, result);
1157 } else if (row instanceof TokenRow) {
1158 return getView((TokenRow) row, parent, result);
1159 } else if (row instanceof HtmlEntry.Row) {
1160 return getView((HtmlEntry.Row) row, parent, result);
1162 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1166 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1167 final TableLayout result) {
1168 final PairEntry entry = row.getEntry();
1169 final int rowCount = entry.pairs.size();
1171 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1172 layoutParams.weight = 0.5f;
1173 layoutParams.leftMargin = mPaddingLarge;
1175 for (int r = 0; r < rowCount; ++r) {
1176 final TableRow tableRow = new TableRow(result.getContext());
1178 final TextView col1 = new TextView(tableRow.getContext());
1179 final TextView col2 = new TextView(tableRow.getContext());
1181 // Set the columns in the table.
1183 final TextView bullet = new TextView(tableRow.getContext());
1184 bullet.setText(" • ");
1185 tableRow.addView(bullet);
1187 tableRow.addView(col1, layoutParams);
1188 final TextView margin = new TextView(tableRow.getContext());
1189 margin.setText(" ");
1190 tableRow.addView(margin);
1192 final TextView bullet = new TextView(tableRow.getContext());
1193 bullet.setText(" • ");
1194 tableRow.addView(bullet);
1196 tableRow.addView(col2, layoutParams);
1200 // Set what's in the columns.
1202 final Pair pair = entry.pairs.get(r);
1203 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1204 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1206 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1207 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1209 // Bold the token instances in col1.
1210 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1211 .singleton(row.getTokenRow(true).getToken());
1212 final Spannable col1Spannable = (Spannable) col1.getText();
1213 for (final String token : toBold) {
1215 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1216 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1217 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1218 startPos += token.length();
1222 createTokenLinkSpans(col1, col1Spannable, col1Text);
1223 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1225 col1.setTypeface(typeface);
1226 col2.setTypeface(typeface);
1227 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1228 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1229 // col2.setBackgroundResource(theme.otherLangBg);
1231 if (index.swapPairEntries) {
1232 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1233 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1235 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1236 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1239 result.addView(tableRow);
1242 // Because we have a Button inside a ListView row:
1243 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1244 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1245 result.setClickable(true);
1246 result.setFocusable(true);
1247 result.setLongClickable(true);
1248 result.setBackgroundResource(android.R.drawable.menuitem_background);
1249 result.setOnClickListener(new TextView.OnClickListener() {
1251 public void onClick(View v) {
1252 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1259 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1260 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1261 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1262 final Context context = parent.getContext();
1264 final TableRow tableRow = new TableRow(result.getContext());
1265 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1266 : theme.tokenRowOtherBg);
1268 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1270 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1272 result.addView(tableRow);
1274 // Make it so we can long-click on these token rows, too:
1275 final TextView textView = new TextView(context);
1276 textView.setText(text, BufferType.SPANNABLE);
1277 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1278 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1280 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1281 result.setLongClickable(true);
1284 // textView.setTextColor(android.R.color.secondary_text_light);
1285 textView.setTypeface(typeface);
1286 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1288 textView.setTextAppearance(context, theme.tokenRowFg);
1289 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1291 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1295 textView.setLayoutParams(lp);
1296 tableRow.addView(textView);
1298 if (!htmlEntries.isEmpty()) {
1299 final ClickableSpan clickableSpan = new ClickableSpan() {
1301 public void onClick(View widget) {
1304 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1305 result.setClickable(true);
1306 textView.setClickable(true);
1307 textView.setMovementMethod(LinkMovementMethod.getInstance());
1308 textView.setOnClickListener(new OnClickListener() {
1310 public void onClick(View v) {
1311 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1312 //Log.d(LOG, "html=" + html);
1313 startActivityForResult(
1314 HtmlDisplayActivity.getHtmlIntent(String.format(
1315 "<html><head></head><body>%s</body></html>", html),
1316 htmlTextToHighlight, false),
1324 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1325 final IndexEntry indexEntry = row.getIndexEntry();
1326 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1327 indexEntry.htmlEntries, null, parent, result);
1330 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1331 final HtmlEntry htmlEntry = row.getEntry();
1332 final TokenRow tokenRow = row.getTokenRow(true);
1333 return getPossibleLinkToHtmlEntryView(false,
1334 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1335 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1341 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1343 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1344 final String text) {
1345 // Saw from the source code that LinkMovementMethod sets the selection!
1346 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1347 textView.setMovementMethod(LinkMovementMethod.getInstance());
1348 final Matcher matcher = CHAR_DASH.matcher(text);
1349 while (matcher.find()) {
1350 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
1351 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1355 String selectedSpannableText = null;
1357 int selectedSpannableIndex = -1;
1360 public boolean onTouchEvent(MotionEvent event) {
1361 selectedSpannableText = null;
1362 selectedSpannableIndex = -1;
1363 return super.onTouchEvent(event);
1366 private class TextViewLongClickListener implements OnLongClickListener {
1369 private TextViewLongClickListener(final int index) {
1374 public boolean onLongClick(final View v) {
1375 final TextView textView = (TextView) v;
1376 final int start = textView.getSelectionStart();
1377 final int end = textView.getSelectionEnd();
1378 if (start >= 0 && end >= 0) {
1379 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1380 selectedSpannableIndex = index;
1386 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1389 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1392 // --------------------------------------------------------------------------
1394 // --------------------------------------------------------------------------
1396 void onSearchTextChange(final String text) {
1397 if ("thadolina".equals(text)) {
1398 final Dialog dialog = new Dialog(getListView().getContext());
1399 dialog.setContentView(R.layout.thadolina_dialog);
1400 dialog.setTitle("Ti amo, amore mio!");
1401 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1402 imageView.setOnClickListener(new OnClickListener() {
1404 public void onClick(View v) {
1405 final Intent intent = new Intent(Intent.ACTION_VIEW);
1406 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1407 startActivity(intent);
1412 if (dictRaf == null) {
1413 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1416 // if (!searchView.hasFocus()) {
1417 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1420 Log.d(LOG, "onSearchTextChange: " + text);
1421 if (currentSearchOperation != null) {
1422 Log.d(LOG, "Interrupting currentSearchOperation.");
1423 currentSearchOperation.interrupted.set(true);
1425 currentSearchOperation = new SearchOperation(text, index);
1426 searchExecutor.execute(currentSearchOperation);
1429 // --------------------------------------------------------------------------
1430 // Filtered results.
1431 // --------------------------------------------------------------------------
1433 boolean isFiltered() {
1434 return rowsToShow != null;
1437 void setFiltered(final SearchOperation searchOperation) {
1438 if (nextWordMenuItem != null) {
1439 nextWordMenuItem.setEnabled(false);
1440 previousWordMenuItem.setEnabled(false);
1442 rowsToShow = searchOperation.multiWordSearchResult;
1443 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1446 void clearFiltered() {
1447 if (nextWordMenuItem != null) {
1448 nextWordMenuItem.setEnabled(true);
1449 previousWordMenuItem.setEnabled(true);
1451 setListAdapter(new IndexAdapter(index));