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.ImageButton;
58 import android.widget.ImageView;
59 import android.widget.LinearLayout;
60 import android.widget.ListAdapter;
61 import android.widget.ListView;
62 import android.widget.TableLayout;
63 import android.widget.TableRow;
64 import android.widget.TextView;
65 import android.widget.TextView.BufferType;
66 import android.widget.Toast;
68 import com.actionbarsherlock.app.ActionBar;
69 import com.actionbarsherlock.app.SherlockListActivity;
70 import com.actionbarsherlock.view.Menu;
71 import com.actionbarsherlock.view.MenuItem;
72 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
73 import com.actionbarsherlock.widget.SearchView;
74 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
75 import com.hughes.android.dictionary.engine.Dictionary;
76 import com.hughes.android.dictionary.engine.EntrySource;
77 import com.hughes.android.dictionary.engine.HtmlEntry;
78 import com.hughes.android.dictionary.engine.Index;
79 import com.hughes.android.dictionary.engine.Index.IndexEntry;
80 import com.hughes.android.dictionary.engine.PairEntry;
81 import com.hughes.android.dictionary.engine.PairEntry.Pair;
82 import com.hughes.android.dictionary.engine.RowBase;
83 import com.hughes.android.dictionary.engine.TokenRow;
84 import com.hughes.android.dictionary.engine.TransliteratorManager;
85 import com.hughes.android.util.IntentLauncher;
86 import com.hughes.android.util.NonLinkClickableSpan;
87 import com.hughes.util.StringUtil;
90 import java.io.FileWriter;
91 import java.io.IOException;
92 import java.io.PrintWriter;
93 import java.io.RandomAccessFile;
94 import java.text.SimpleDateFormat;
95 import java.util.Arrays;
96 import java.util.Collections;
97 import java.util.Date;
98 import java.util.HashMap;
99 import java.util.LinkedHashSet;
100 import java.util.List;
101 import java.util.Locale;
102 import java.util.Random;
103 import java.util.Set;
104 import java.util.concurrent.Executor;
105 import java.util.concurrent.Executors;
106 import java.util.concurrent.ThreadFactory;
107 import java.util.concurrent.atomic.AtomicBoolean;
108 import java.util.regex.Matcher;
109 import java.util.regex.Pattern;
111 public class DictionaryActivity extends SherlockListActivity {
113 static final String LOG = "QuickDic";
115 DictionaryApplication application;
117 File dictFile = null;
119 RandomAccessFile dictRaf = null;
121 Dictionary dictionary = null;
127 List<RowBase> rowsToShow = null; // if not null, just show these rows.
130 final Handler uiHandler = new Handler();
132 TextToSpeech textToSpeech;
133 volatile boolean ttsReady;
135 int textColorFg = Color.BLACK;
138 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
140 public Thread newThread(Runnable r) {
141 return new Thread(r, "searchExecutor");
145 private SearchOperation currentSearchOperation = null;
147 C.Theme theme = C.Theme.LIGHT;
157 MenuItem nextWordMenuItem, previousWordMenuItem;
160 private File wordList = null;
162 private boolean saveOnlyFirstSubentry = false;
164 private boolean clickOpensContextMenu = false;
166 // Visible for testing.
167 ListAdapter indexAdapter = null;
169 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
172 * For some languages, loading the transliterators used in this search takes
173 * a long time, so we fire it up on a different thread, and don't invoke it
174 * from the main thread until it's already finished once.
176 private volatile boolean indexPrepFinished = false;
178 public DictionaryActivity() {
181 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
182 final String searchToken) {
183 final Intent intent = new Intent();
184 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
185 DictionaryActivity.class.getName());
186 intent.putExtra(C.DICT_FILE, dictFile.getPath());
187 intent.putExtra(C.INDEX_INDEX, indexIndex);
188 intent.putExtra(C.SEARCH_TOKEN, searchToken);
193 protected void onSaveInstanceState(final Bundle outState) {
194 super.onSaveInstanceState(outState);
195 Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
196 outState.putInt(C.INDEX_INDEX, indexIndex);
197 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
201 protected void onRestoreInstanceState(final Bundle outState) {
202 super.onRestoreInstanceState(outState);
203 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
208 public void onCreate(Bundle savedInstanceState) {
209 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
210 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
213 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
215 Log.d(LOG, "onCreate:" + this);
216 super.onCreate(savedInstanceState);
218 application = (DictionaryApplication) getApplication();
219 theme = application.getSelectedTheme();
220 textColorFg = getResources().getColor(theme.tokenRowFgColor);
222 final Intent intent = getIntent();
223 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
226 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
228 public void onInit(int status) {
235 final String name = application.getDictionaryName(dictFile.getName());
236 this.setTitle("QuickDic: " + name);
237 dictRaf = new RandomAccessFile(dictFile, "r");
238 dictionary = new Dictionary(dictRaf);
239 } catch (Exception e) {
240 Log.e(LOG, "Unable to load dictionary.", e);
241 if (dictRaf != null) {
244 } catch (IOException e1) {
245 Log.e(LOG, "Unable to close dictRaf.", e1);
249 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
250 Toast.LENGTH_LONG).show();
251 startActivity(DictionaryManagerActivity.getLaunchIntent());
255 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
256 if (savedInstanceState != null) {
257 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
259 indexIndex %= dictionary.indices.size();
260 Log.d(LOG, "Loading index " + indexIndex);
261 index = dictionary.indices.get(indexIndex);
262 setListAdapter(new IndexAdapter(index));
264 // Pre-load the collators.
265 new Thread(new Runnable() {
267 final long startMillis = System.currentTimeMillis();
269 TransliteratorManager.init(new TransliteratorManager.Callback() {
271 public void onTransliteratorReady() {
272 uiHandler.post(new Runnable() {
275 onSearchTextChange(searchText.getText().toString());
281 for (final Index index : dictionary.indices) {
282 final String searchToken = index.sortedIndexEntries.get(0).token;
283 final IndexEntry entry = index.findExact(searchToken);
284 if (!searchToken.equals(entry.token)) {
285 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
288 indexPrepFinished = true;
289 } catch (Exception e) {
291 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
293 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
297 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
298 if ("SYSTEM".equals(fontName)) {
299 typeface = Typeface.DEFAULT;
302 typeface = Typeface.createFromAsset(getAssets(), fontName);
303 } catch (Exception e) {
304 Log.w(LOG, "Exception trying to use typeface, using default.", e);
305 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
306 Toast.LENGTH_LONG).show();
309 // if (!"SYSTEM".equals(fontName)) {
310 // throw new RuntimeException("Test force using system font: " +
313 if (typeface == null) {
314 Log.w(LOG, "Unable to create typeface, using default.");
315 typeface = Typeface.DEFAULT;
317 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
319 fontSizeSp = Integer.parseInt(fontSize.trim());
320 } catch (NumberFormatException e) {
324 setContentView(R.layout.dictionary_activity);
325 searchText = (EditText) findViewById(R.id.SearchText);
326 searchText.requestFocus();
327 searchText.addTextChangedListener(searchTextWatcher);
328 searchText.setOnFocusChangeListener(new OnFocusChangeListener() {
330 public void onFocusChange(View v, boolean hasFocus) {
331 Log.d(LOG, "searchText onFocusChange hasFocus=" + hasFocus);
335 // Set the search text from the intent, then the saved state.
336 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
337 if (savedInstanceState != null) {
338 text = savedInstanceState.getString(C.SEARCH_TOKEN);
343 setSearchText(text, true);
344 Log.d(LOG, "Trying to restore searchText=" + text);
346 final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
347 clearSearchTextButton.setOnClickListener(new OnClickListener() {
348 public void onClick(View v) {
349 onClearSearchTextButton();
352 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
353 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
356 langButton = (Button) findViewById(R.id.LangButton);
357 langButton.setOnClickListener(new OnClickListener() {
358 public void onClick(View v) {
362 langButton.setOnLongClickListener(new OnLongClickListener() {
364 public boolean onLongClick(View v) {
365 onLanguageButtonLongClick(v.getContext());
371 // getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
373 // public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
375 // if (!searchText.isFocused()) {
376 // if (!isFiltered()) {
377 // final RowBase row = (RowBase) getListAdapter().getItem(position);
378 // Log.d(LOG, "onItemSelected: " + row.index());
379 // final TokenRow tokenRow = row.getTokenRow(true);
380 // searchText.setText(tokenRow.getToken());
386 // public void onNothingSelected(AdapterView<?> arg0) {
391 registerForContextMenu(getListView());
394 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
395 getString(R.string.wordListFileDefault)));
396 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
398 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
400 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
402 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
404 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
406 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
408 ActionBar actionBar = getSupportActionBar();
409 actionBar.setDisplayShowTitleEnabled(false);
411 //Inflate the custom view
412 // View customNav = LayoutInflater.from(this).inflate(R.layout.dictionary_search_view, null);
413 SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
414 searchView.setIconifiedByDefault(false);
415 searchView.setQueryHint(getString(R.string.searchText));
416 searchView.setSubmitButtonEnabled(false);
417 // searchView.setMaxWidth(200);
418 searchView.setImeOptions(
419 EditorInfo.IME_ACTION_SEARCH |
420 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
421 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
422 // EditorInfo.IME_FLAG_NO_FULLSCREEN |
423 EditorInfo.IME_MASK_ACTION |
424 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
425 // searchView.setOnQueryTextListener(this);
426 // menu.add("Search")
427 //// .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.abs__ic_search)
428 // .setActionView(searchView)
429 // .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
430 actionBar.setCustomView(searchView);
431 actionBar.setDisplayShowCustomEnabled(true);
435 protected void onResume() {
436 Log.d(LOG, "onResume");
438 if (SettingsActivity.settingsMightHaveChanged) {
439 SettingsActivity.settingsMightHaveChanged = false;
441 startActivity(getIntent());
447 protected void onPause() {
452 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
453 super.onActivityResult(requestCode, resultCode, result);
454 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
455 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
456 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
460 private static void setDictionaryPrefs(final Context context, final File dictFile,
461 final int indexIndex, final String searchToken) {
462 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
464 prefs.putString(C.DICT_FILE, dictFile.getPath());
465 prefs.putInt(C.INDEX_INDEX, indexIndex);
466 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
471 protected void onDestroy() {
473 if (dictRaf == null) {
477 final SearchOperation searchOperation = currentSearchOperation;
478 currentSearchOperation = null;
480 // Before we close the RAF, we have to wind the current search down.
481 if (searchOperation != null) {
482 Log.d(LOG, "Interrupting search to shut down.");
483 currentSearchOperation = null;
484 searchOperation.interrupted.set(true);
488 Log.d(LOG, "Closing RAF.");
490 } catch (IOException e) {
491 Log.e(LOG, "Failed to close dictionary", e);
496 // --------------------------------------------------------------------------
498 // --------------------------------------------------------------------------
500 private void onClearSearchTextButton() {
501 setSearchText("", true);
505 private void showKeyboard() {
506 searchText.postDelayed(new Runnable() {
509 Log.d(LOG, "Trying to show soft keyboard.");
510 final boolean searchTextHadFocus = searchText.hasFocus();
511 searchText.requestFocus();
512 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
513 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
514 if (!searchTextHadFocus) {
520 void updateLangButton() {
521 // final LanguageResources languageResources =
522 // Language.isoCodeToResources.get(index.shortName);
523 // if (languageResources != null && languageResources.flagId != 0) {
524 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
525 // languageResources.flagId, 0);
527 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
528 langButton.setText(index.shortName);
533 private void updateTTSLanuage() {
534 if (!ttsReady || index == null || textToSpeech == null) {
535 Log.d(LOG, "Can't updateTTSLanguage.");
538 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
539 Log.d(LOG, "Setting TTS locale to: " + locale);
540 final int ttsResult = textToSpeech.setLanguage(locale);
541 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
542 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
543 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
547 void onLanguageButton() {
548 if (currentSearchOperation != null) {
549 currentSearchOperation.interrupted.set(true);
550 currentSearchOperation = null;
552 changeIndexAndResearch((indexIndex + 1) % dictionary.indices.size());
555 void onLanguageButtonLongClick(final Context context) {
556 final Dialog dialog = new Dialog(context);
557 dialog.setContentView(R.layout.select_dictionary_dialog);
558 dialog.setTitle(R.string.selectDictionary);
560 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
563 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
565 // final LinearLayout.LayoutParams layoutParams = new
566 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
567 // ViewGroup.LayoutParams.WRAP_CONTENT);
568 // layoutParams.width = 0;
569 // layoutParams.weight = 1.0f;
571 final Button button = new Button(listView.getContext());
572 final String name = getString(R.string.dictionaryManager);
573 button.setText(name);
574 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
575 DictionaryManagerActivity.getLaunchIntent()) {
577 protected void onGo() {
579 DictionaryActivity.this.finish();
582 button.setOnClickListener(intentLauncher);
583 // button.setLayoutParams(layoutParams);
584 listView.addHeaderView(button);
585 // listView.setHeaderDividersEnabled(true);
587 listView.setAdapter(new BaseAdapter() {
589 public View getView(int position, View convertView, ViewGroup parent) {
590 final DictionaryInfo dictionaryInfo = getItem(position);
592 final LinearLayout result = new LinearLayout(parent.getContext());
594 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
596 final TextView dash = new TextView(parent.getContext());
598 result.addView(dash);
601 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
602 final Button button = new Button(parent.getContext());
603 button.setText(indexInfo.shortName);
604 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
606 application.getPath(dictionaryInfo.uncompressedFilename),
607 i, searchText.getText().toString())) {
609 protected void onGo() {
611 DictionaryActivity.this.finish();
614 button.setOnClickListener(intentLauncher);
615 result.addView(button);
619 final TextView nameView = new TextView(parent.getContext());
620 final String name = application
621 .getDictionaryName(dictionaryInfo.uncompressedFilename);
622 nameView.setText(name);
623 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
624 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
625 layoutParams.width = 0;
626 layoutParams.weight = 1.0f;
627 nameView.setLayoutParams(layoutParams);
628 result.addView(nameView);
634 public long getItemId(int position) {
639 public DictionaryInfo getItem(int position) {
640 return installedDicts.get(position);
644 public int getCount() {
645 return installedDicts.size();
652 private void changeIndexAndResearch(int newIndex) {
653 Log.d(LOG, "Changing index to: " + newIndex);
654 if (newIndex == -1) {
655 Log.e(LOG, "Invalid index.");
658 indexIndex = newIndex;
659 index = dictionary.indices.get(indexIndex);
660 indexAdapter = new IndexAdapter(index);
661 Log.d(LOG, "changingIndex, newLang=" + index.longName);
662 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
663 setListAdapter(indexAdapter);
665 setSearchText(searchText.getText().toString(), true);
668 void onUpDownButton(final boolean up) {
672 final int firstVisibleRow = getListView().getFirstVisiblePosition();
673 final RowBase row = index.rows.get(firstVisibleRow);
674 final TokenRow tokenRow = row.getTokenRow(true);
675 final int destIndexEntry;
677 if (row != tokenRow) {
678 destIndexEntry = tokenRow.referenceIndex;
680 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
684 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
686 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
687 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
688 setSearchText(dest.token, false);
689 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
693 // --------------------------------------------------------------------------
695 // --------------------------------------------------------------------------
697 final Random random = new Random();
700 public boolean onCreateOptionsMenu(final Menu menu) {
701 //Create the search view
702 // SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
703 // searchView.setIconifiedByDefault(false);
704 // searchView.setQueryHint(getString(R.string.searchText));
705 // searchView.setSubmitButtonEnabled(false);
706 // searchView.setMaxWidth(200);
707 // searchView.setImeOptions(
708 // EditorInfo.IME_ACTION_SEARCH |
709 // EditorInfo.IME_FLAG_NO_EXTRACT_UI |
710 // EditorInfo.IME_FLAG_NO_ENTER_ACTION |
711 //// EditorInfo.IME_FLAG_NO_FULLSCREEN |
712 // EditorInfo.IME_MASK_ACTION |
713 // EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
714 //// searchView.setOnQueryTextListener(this);
715 // menu.add("Search")
716 //// .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.abs__ic_search)
717 // .setActionView(searchView)
718 // .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
721 if (PreferenceManager.getDefaultSharedPreferences(this)
722 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
724 nextWordMenuItem = menu.add(getString(R.string.nextWord))
725 .setIcon(R.drawable.arrow_down_float);
726 nextWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
727 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
729 public boolean onMenuItemClick(MenuItem item) {
730 onUpDownButton(true);
736 previousWordMenuItem = menu.add(getString(R.string.previousWord))
737 .setIcon(R.drawable.arrow_up_float);
738 previousWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
739 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
741 public boolean onMenuItemClick(MenuItem item) {
742 onUpDownButton(false);
748 application.onCreateGlobalOptionsMenu(this, menu);
751 // final MenuItem randomWord = menu.add(getString(R.string.randomWord));
752 // randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
753 // public boolean onMenuItemClick(final MenuItem menuItem) {
754 // final String word = index.sortedIndexEntries.get(random
755 // .nextInt(index.sortedIndexEntries.size())).token;
756 // setSearchText(word, true);
763 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
764 dictionaryList.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
765 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
766 public boolean onMenuItemClick(final MenuItem menuItem) {
767 startActivity(DictionaryManagerActivity.getLaunchIntent());
775 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
776 aboutDictionary.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
777 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
778 public boolean onMenuItemClick(final MenuItem menuItem) {
779 final Context context = getListView().getContext();
780 final Dialog dialog = new Dialog(context);
781 dialog.setContentView(R.layout.about_dictionary_dialog);
782 final TextView textView = (TextView) dialog.findViewById(R.id.text);
784 final String name = application.getDictionaryName(dictFile.getName());
785 dialog.setTitle(name);
787 final StringBuilder builder = new StringBuilder();
788 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
789 dictionaryInfo.uncompressedBytes = dictFile.length();
790 if (dictionaryInfo != null) {
791 builder.append(dictionaryInfo.dictInfo).append("\n\n");
792 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
795 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
798 getString(R.string.dictionaryCreationTime,
799 dictionaryInfo.creationMillis)).append("\n");
800 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
801 builder.append("\n");
802 builder.append(getString(R.string.indexName, indexInfo.shortName))
805 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
808 builder.append("\n");
809 builder.append(getString(R.string.sources)).append("\n");
810 for (final EntrySource source : dictionary.sources) {
812 getString(R.string.sourceInfo, source.getName(),
813 source.getNumEntries())).append("\n");
817 // builder.append(getString(R.string.invalidDictionary));
819 textView.setText(builder.toString());
822 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
823 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
824 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
825 dialog.getWindow().setAttributes(layoutParams);
834 // --------------------------------------------------------------------------
835 // Context Menu + clicks
836 // --------------------------------------------------------------------------
839 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
840 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
841 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
843 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
844 wordList.getName()));
845 addToWordlist.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
846 public boolean onMenuItemClick(android.view.MenuItem item) {
847 onAppendToWordList(row);
852 final android.view.MenuItem share = menu.add("Share");
853 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
854 public boolean onMenuItemClick(android.view.MenuItem item) {
855 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
856 shareIntent.setType("text/plain");
857 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true).getToken());
858 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, row.getRawText(saveOnlyFirstSubentry));
859 startActivity(shareIntent);
864 final android.view.MenuItem copy = menu.add(android.R.string.copy);
865 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
866 public boolean onMenuItemClick(android.view.MenuItem item) {
872 if (selectedSpannableText != null) {
873 final String selectedText = selectedSpannableText;
874 final android.view.MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
875 selectedSpannableText));
876 searchForSelection.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
877 public boolean onMenuItemClick(android.view.MenuItem item) {
878 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
884 if (row instanceof TokenRow && ttsReady) {
885 final android.view.MenuItem speak = menu.add(R.string.speak);
886 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
888 public boolean onMenuItemClick(android.view.MenuItem item) {
889 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
890 new HashMap<String, String>());
897 private void jumpToTextFromHyperLink(final String selectedText, final int defaultIndexToUse) {
899 for (int i = 0; i < dictionary.indices.size(); ++i) {
900 final Index index = dictionary.indices.get(i);
901 if (indexPrepFinished) {
902 System.out.println("Doing index lookup: on " + selectedText);
903 final IndexEntry indexEntry = index.findExact(selectedText);
904 if (indexEntry != null) {
905 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
907 if (tokenRow != null && tokenRow.hasMainEntry) {
913 Log.w(LOG, "Skipping findExact on index " + index.shortName);
916 if (indexToUse == -1) {
917 indexToUse = defaultIndexToUse;
919 final boolean changeIndex = indexIndex != indexToUse;
921 setSearchText(selectedText, false);
922 changeIndexAndResearch(indexToUse);
924 setSearchText(selectedText, true);
929 protected void onListItemClick(ListView l, View v, int row, long id) {
931 if (clickOpensContextMenu && dictRaf != null) {
936 @SuppressLint("SimpleDateFormat")
937 void onAppendToWordList(final RowBase row) {
940 final StringBuilder rawText = new StringBuilder();
941 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
942 rawText.append(index.longName).append("\t");
943 rawText.append(row.getTokenRow(true).getToken()).append("\t");
944 rawText.append(row.getRawText(saveOnlyFirstSubentry));
945 Log.d(LOG, "Writing : " + rawText);
948 wordList.getParentFile().mkdirs();
949 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
950 out.println(rawText.toString());
952 } catch (IOException e) {
953 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
955 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
956 Toast.LENGTH_LONG).show();
962 * Called when user clicks outside of search text, so that they can start
963 * typing again immediately.
965 void defocusSearchText() {
966 // Log.d(LOG, "defocusSearchText");
967 // Request focus so that if we start typing again, it clears the text
969 getListView().requestFocus();
971 // Visual indication that a new keystroke will clear the search text.
972 // Doesn't seem to work unless earchText has focus.
973 // searchText.selectAll();
976 @SuppressWarnings("deprecation")
977 void onCopy(final RowBase row) {
980 Log.d(LOG, "Copy, row=" + row);
981 final StringBuilder result = new StringBuilder();
982 result.append(row.getRawText(false));
983 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
984 clipboardManager.setText(result.toString());
985 Log.d(LOG, "Copied: " + result);
989 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
990 if (event.getUnicodeChar() != 0) {
991 if (!searchText.hasFocus()) {
992 setSearchText("" + (char) event.getUnicodeChar(), true);
996 if (keyCode == KeyEvent.KEYCODE_BACK) {
997 // Log.d(LOG, "Clearing dictionary prefs.");
998 // Pretend that we just autolaunched so that we won't do it again.
999 // DictionaryManagerActivity.lastAutoLaunchMillis =
1000 // System.currentTimeMillis();
1002 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1003 Log.d(LOG, "Trying to hide soft keyboard.");
1004 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1005 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
1006 InputMethodManager.HIDE_NOT_ALWAYS);
1009 return super.onKeyDown(keyCode, event);
1012 private void setSearchText(final String text, final boolean triggerSearch) {
1013 if (!triggerSearch) {
1014 getListView().requestFocus();
1016 searchText.setText(text);
1017 searchText.requestFocus();
1018 moveCursorToRight();
1019 if (triggerSearch) {
1020 onSearchTextChange(text);
1024 private long cursorDelayMillis = 100;
1026 private void moveCursorToRight() {
1027 if (searchText.getLayout() != null) {
1028 cursorDelayMillis = 100;
1029 // Surprising, but this can crash when you rotate...
1030 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
1032 uiHandler.postDelayed(new Runnable() {
1035 moveCursorToRight();
1037 }, cursorDelayMillis);
1038 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1042 // --------------------------------------------------------------------------
1044 // --------------------------------------------------------------------------
1046 private void searchFinished(final SearchOperation searchOperation) {
1047 if (searchOperation.interrupted.get()) {
1048 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1051 if (searchOperation != this.currentSearchOperation) {
1052 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1056 final Index.IndexEntry searchResult = searchOperation.searchResult;
1057 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1059 currentSearchOperation = null;
1060 uiHandler.postDelayed(new Runnable() {
1063 if (currentSearchOperation == null) {
1064 if (searchResult != null) {
1068 jumpToRow(searchResult.startRow);
1069 } else if (searchOperation.multiWordSearchResult != null) {
1070 // Multi-row search....
1071 setFiltered(searchOperation);
1073 throw new IllegalStateException("This should never happen.");
1076 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1082 private final void jumpToRow(final int row) {
1083 final boolean refocusSearchText = searchText.hasFocus();
1084 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + refocusSearchText);
1085 getListView().requestFocusFromTouch();
1086 getListView().setSelectionFromTop(row, 0);
1087 getListView().setSelected(true);
1088 if (refocusSearchText) {
1089 searchText.requestFocus();
1091 //Log.d(LOG, "getSelectedItemPosition():" + getSelectedItemPosition());
1094 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1096 final class SearchOperation implements Runnable {
1098 final AtomicBoolean interrupted = new AtomicBoolean(false);
1100 final String searchText;
1102 List<String> searchTokens; // filled in for multiWord.
1106 long searchStartMillis;
1108 Index.IndexEntry searchResult;
1110 List<RowBase> multiWordSearchResult;
1112 boolean done = false;
1114 SearchOperation(final String searchText, final Index index) {
1115 this.searchText = StringUtil.normalizeWhitespace(searchText);
1119 public String toString() {
1120 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1126 searchStartMillis = System.currentTimeMillis();
1127 final String[] searchTokenArray = WHITESPACE.split(searchText);
1128 if (searchTokenArray.length == 1) {
1129 searchResult = index.findInsertionPoint(searchText, interrupted);
1131 searchTokens = Arrays.asList(searchTokenArray);
1132 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens, interrupted);
1135 "searchText=" + searchText + ", searchDuration="
1136 + (System.currentTimeMillis() - searchStartMillis)
1137 + ", interrupted=" + interrupted.get());
1138 if (!interrupted.get()) {
1139 uiHandler.post(new Runnable() {
1142 searchFinished(SearchOperation.this);
1146 Log.d(LOG, "interrupted, skipping searchFinished.");
1148 } catch (Exception e) {
1149 Log.e(LOG, "Failure during search (can happen during Activity close.");
1151 synchronized (this) {
1159 // --------------------------------------------------------------------------
1161 // --------------------------------------------------------------------------
1163 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1164 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1166 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1167 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1169 final class IndexAdapter extends BaseAdapter {
1171 private static final float PADDING_DEFAULT_DP = 8;
1173 private static final float PADDING_LARGE_DP = 16;
1177 final List<RowBase> rows;
1179 final Set<String> toHighlight;
1181 private int mPaddingDefault;
1183 private int mPaddingLarge;
1185 IndexAdapter(final Index index) {
1188 this.toHighlight = null;
1192 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1195 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1199 private void getMetrics() {
1200 // Get the screen's density scale
1201 final float scale = getResources().getDisplayMetrics().density;
1202 // Convert the dps to pixels, based on density scale
1203 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1204 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1208 public int getCount() {
1213 public RowBase getItem(int position) {
1214 return rows.get(position);
1218 public long getItemId(int position) {
1219 return getItem(position).index();
1223 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1224 final TableLayout result;
1225 if (convertView instanceof TableLayout) {
1226 result = (TableLayout) convertView;
1227 result.removeAllViews();
1229 result = new TableLayout(parent.getContext());
1231 final RowBase row = getItem(position);
1232 if (row instanceof PairEntry.Row) {
1233 return getView(position, (PairEntry.Row) row, parent, result);
1234 } else if (row instanceof TokenRow) {
1235 return getView((TokenRow) row, parent, result);
1236 } else if (row instanceof HtmlEntry.Row) {
1237 return getView((HtmlEntry.Row) row, parent, result);
1239 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1243 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1244 final TableLayout result) {
1245 final PairEntry entry = row.getEntry();
1246 final int rowCount = entry.pairs.size();
1248 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1249 layoutParams.weight = 0.5f;
1250 layoutParams.leftMargin = mPaddingLarge;
1252 for (int r = 0; r < rowCount; ++r) {
1253 final TableRow tableRow = new TableRow(result.getContext());
1255 final TextView col1 = new TextView(tableRow.getContext());
1256 final TextView col2 = new TextView(tableRow.getContext());
1258 // Set the columns in the table.
1260 final TextView bullet = new TextView(tableRow.getContext());
1261 bullet.setText(" • ");
1262 tableRow.addView(bullet);
1264 tableRow.addView(col1, layoutParams);
1265 final TextView margin = new TextView(tableRow.getContext());
1266 margin.setText(" ");
1267 tableRow.addView(margin);
1269 final TextView bullet = new TextView(tableRow.getContext());
1270 bullet.setText(" • ");
1271 tableRow.addView(bullet);
1273 tableRow.addView(col2, layoutParams);
1277 // Set what's in the columns.
1279 final Pair pair = entry.pairs.get(r);
1280 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1281 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1283 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1284 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1286 // Bold the token instances in col1.
1287 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1288 .singleton(row.getTokenRow(true).getToken());
1289 final Spannable col1Spannable = (Spannable) col1.getText();
1290 for (final String token : toBold) {
1292 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1293 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1294 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1295 startPos += token.length();
1299 createTokenLinkSpans(col1, col1Spannable, col1Text);
1300 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1302 col1.setTypeface(typeface);
1303 col2.setTypeface(typeface);
1304 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1305 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1306 // col2.setBackgroundResource(theme.otherLangBg);
1308 if (index.swapPairEntries) {
1309 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1310 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1312 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1313 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1316 result.addView(tableRow);
1319 // Because we have a Button inside a ListView row:
1320 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1321 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1322 result.setClickable(true);
1323 result.setFocusable(true);
1324 result.setLongClickable(true);
1325 result.setBackgroundResource(android.R.drawable.menuitem_background);
1326 result.setOnClickListener(new TextView.OnClickListener() {
1328 public void onClick(View v) {
1329 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1336 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1337 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1338 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1339 final Context context = parent.getContext();
1341 final TableRow tableRow = new TableRow(result.getContext());
1342 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1343 : theme.tokenRowOtherBg);
1345 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1347 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1349 result.addView(tableRow);
1351 // Make it so we can long-click on these token rows, too:
1352 final TextView textView = new TextView(context);
1353 textView.setText(text, BufferType.SPANNABLE);
1354 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1355 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1357 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1358 result.setLongClickable(true);
1361 // textView.setTextColor(android.R.color.secondary_text_light);
1362 textView.setTypeface(typeface);
1363 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1365 textView.setTextAppearance(context, theme.tokenRowFg);
1366 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1368 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1372 textView.setLayoutParams(lp);
1373 tableRow.addView(textView);
1375 if (!htmlEntries.isEmpty()) {
1376 final ClickableSpan clickableSpan = new ClickableSpan() {
1378 public void onClick(View widget) {
1381 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1382 result.setClickable(true);
1383 textView.setClickable(true);
1384 textView.setMovementMethod(LinkMovementMethod.getInstance());
1385 textView.setOnClickListener(new OnClickListener() {
1387 public void onClick(View v) {
1388 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1389 //Log.d(LOG, "html=" + html);
1390 startActivityForResult(
1391 HtmlDisplayActivity.getHtmlIntent(String.format(
1392 "<html><head></head><body>%s</body></html>", html),
1393 htmlTextToHighlight, false),
1401 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1402 final IndexEntry indexEntry = row.getIndexEntry();
1403 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1404 indexEntry.htmlEntries, null, parent, result);
1407 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1408 final HtmlEntry htmlEntry = row.getEntry();
1409 final TokenRow tokenRow = row.getTokenRow(true);
1410 return getPossibleLinkToHtmlEntryView(false,
1411 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1412 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1418 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1420 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1421 final String text) {
1422 // Saw from the source code that LinkMovementMethod sets the selection!
1423 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1424 textView.setMovementMethod(LinkMovementMethod.getInstance());
1425 final Matcher matcher = CHAR_DASH.matcher(text);
1426 while (matcher.find()) {
1427 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
1428 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1432 String selectedSpannableText = null;
1434 int selectedSpannableIndex = -1;
1437 public boolean onTouchEvent(MotionEvent event) {
1438 selectedSpannableText = null;
1439 selectedSpannableIndex = -1;
1440 return super.onTouchEvent(event);
1443 private class TextViewLongClickListener implements OnLongClickListener {
1446 private TextViewLongClickListener(final int index) {
1451 public boolean onLongClick(final View v) {
1452 final TextView textView = (TextView) v;
1453 final int start = textView.getSelectionStart();
1454 final int end = textView.getSelectionEnd();
1455 if (start >= 0 && end >= 0) {
1456 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1457 selectedSpannableIndex = index;
1463 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1466 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1469 // --------------------------------------------------------------------------
1471 // --------------------------------------------------------------------------
1473 void onSearchTextChange(final String text) {
1474 if ("thadolina".equals(text)) {
1475 final Dialog dialog = new Dialog(getListView().getContext());
1476 dialog.setContentView(R.layout.thadolina_dialog);
1477 dialog.setTitle("Ti amo, amore mio!");
1478 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1479 imageView.setOnClickListener(new OnClickListener() {
1481 public void onClick(View v) {
1482 final Intent intent = new Intent(Intent.ACTION_VIEW);
1483 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1484 startActivity(intent);
1489 if (dictRaf == null) {
1490 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1493 if (!searchText.isFocused()) {
1494 Log.d(LOG, "searchText changed without focus, doing nothing.");
1497 Log.d(LOG, "onSearchTextChange: " + text);
1498 if (currentSearchOperation != null) {
1499 Log.d(LOG, "Interrupting currentSearchOperation.");
1500 currentSearchOperation.interrupted.set(true);
1502 currentSearchOperation = new SearchOperation(text, index);
1503 searchExecutor.execute(currentSearchOperation);
1506 private class SearchTextWatcher implements TextWatcher {
1507 public void afterTextChanged(final Editable searchTextEditable) {
1508 if (searchText.hasFocus()) {
1509 Log.d(LOG, "SearchTextWatcher: Search text changed with focus: " + searchText.getText());
1510 // If they were typing to cause the change, update the UI.
1511 onSearchTextChange(searchText.getText().toString());
1515 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1518 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1522 // --------------------------------------------------------------------------
1523 // Filtered results.
1524 // --------------------------------------------------------------------------
1526 boolean isFiltered() {
1527 return rowsToShow != null;
1530 void setFiltered(final SearchOperation searchOperation) {
1531 if (nextWordMenuItem != null) {
1532 nextWordMenuItem.setEnabled(false);
1533 previousWordMenuItem.setEnabled(false);
1535 rowsToShow = searchOperation.multiWordSearchResult;
1536 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1539 void clearFiltered() {
1540 if (nextWordMenuItem != null) {
1541 nextWordMenuItem.setEnabled(true);
1542 previousWordMenuItem.setEnabled(true);
1544 setListAdapter(new IndexAdapter(index));