1 // Copyright 2011 Google Inc. All Rights Reserved.
2 // Some Parts Copyright 2013 Dominik Köppl
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.app.SearchManager;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.SharedPreferences;
23 import android.graphics.Color;
24 import android.graphics.Typeface;
25 import android.net.Uri;
26 import android.os.Bundle;
27 import android.os.Handler;
28 import android.preference.PreferenceManager;
29 import android.speech.tts.TextToSpeech;
30 import android.speech.tts.TextToSpeech.OnInitListener;
31 import android.text.ClipboardManager;
32 import android.text.Spannable;
33 import android.text.method.LinkMovementMethod;
34 import android.text.style.ClickableSpan;
35 import android.text.style.StyleSpan;
36 import android.util.Log;
37 import android.util.TypedValue;
38 import android.view.ContextMenu;
39 import android.view.ContextMenu.ContextMenuInfo;
40 import android.view.KeyEvent;
41 import android.view.MotionEvent;
42 import android.view.View;
43 import android.view.View.OnClickListener;
44 import android.view.View.OnLongClickListener;
45 import android.view.ViewGroup;
46 import android.view.WindowManager;
47 import android.view.inputmethod.EditorInfo;
48 import android.view.inputmethod.InputMethodManager;
49 import android.widget.AdapterView.AdapterContextMenuInfo;
50 import android.widget.BaseAdapter;
51 import android.widget.Button;
52 import android.widget.FrameLayout;
53 import android.widget.ImageView;
54 import android.widget.LinearLayout;
55 import android.widget.ListAdapter;
56 import android.widget.ListView;
57 import android.widget.TableLayout;
58 import android.widget.TableRow;
59 import android.widget.TextView;
60 import android.widget.TextView.BufferType;
61 import android.widget.Toast;
63 import com.actionbarsherlock.app.ActionBar;
64 import com.actionbarsherlock.app.SherlockListActivity;
65 import com.actionbarsherlock.view.Menu;
66 import com.actionbarsherlock.view.MenuItem;
67 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
68 import com.actionbarsherlock.widget.SearchView;
69 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
70 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
71 import com.hughes.android.dictionary.engine.Dictionary;
72 import com.hughes.android.dictionary.engine.EntrySource;
73 import com.hughes.android.dictionary.engine.HtmlEntry;
74 import com.hughes.android.dictionary.engine.Index;
75 import com.hughes.android.dictionary.engine.Index.IndexEntry;
76 import com.hughes.android.dictionary.engine.Language;
77 import com.hughes.android.dictionary.engine.Language.LanguageResources;
78 import com.hughes.android.dictionary.engine.PairEntry;
79 import com.hughes.android.dictionary.engine.PairEntry.Pair;
80 import com.hughes.android.dictionary.engine.RowBase;
81 import com.hughes.android.dictionary.engine.TokenRow;
82 import com.hughes.android.dictionary.engine.TransliteratorManager;
83 import com.hughes.android.util.IntentLauncher;
84 import com.hughes.android.util.NonLinkClickableSpan;
85 import com.hughes.util.StringUtil;
88 import java.io.FileWriter;
89 import java.io.IOException;
90 import java.io.PrintWriter;
91 import java.io.RandomAccessFile;
92 import java.text.SimpleDateFormat;
93 import java.util.Arrays;
94 import java.util.Collections;
95 import java.util.Date;
96 import java.util.HashMap;
97 import java.util.LinkedHashSet;
98 import java.util.List;
99 import java.util.Locale;
100 import java.util.Random;
101 import java.util.Set;
102 import java.util.concurrent.Executor;
103 import java.util.concurrent.Executors;
104 import java.util.concurrent.ThreadFactory;
105 import java.util.concurrent.atomic.AtomicBoolean;
106 import java.util.regex.Matcher;
107 import java.util.regex.Pattern;
109 public class DictionaryActivity extends SherlockListActivity {
111 static final String LOG = "QuickDic";
113 DictionaryApplication application;
115 File dictFile = null;
116 RandomAccessFile dictRaf = null;
118 Dictionary dictionary = null;
124 List<RowBase> rowsToShow = null; // if not null, just show these rows.
126 final Handler uiHandler = new Handler();
128 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
130 public Thread newThread(Runnable r) {
131 return new Thread(r, "searchExecutor");
135 private SearchOperation currentSearchOperation = null;
138 TextToSpeech textToSpeech;
139 volatile boolean ttsReady;
142 C.Theme theme = C.Theme.LIGHT;
143 int textColorFg = Color.BLACK;
146 SearchView searchView;
147 ImageView searchHintIcon;
148 SearchView.OnQueryTextListener onQueryTextListener;
150 MenuItem nextWordMenuItem, previousWordMenuItem;
153 private File wordList = null;
154 private boolean saveOnlyFirstSubentry = false;
155 private boolean clickOpensContextMenu = false;
157 // Visible for testing.
158 ListAdapter indexAdapter = null;
161 * For some languages, loading the transliterators used in this search takes
162 * a long time, so we fire it up on a different thread, and don't invoke it
163 * from the main thread until it's already finished once.
165 private volatile boolean indexPrepFinished = false;
167 public DictionaryActivity() {
170 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
171 final String searchToken) {
172 final Intent intent = new Intent();
173 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
174 DictionaryActivity.class.getName());
175 intent.putExtra(C.DICT_FILE, dictFile.getPath());
176 intent.putExtra(C.INDEX_INDEX, indexIndex);
177 intent.putExtra(C.SEARCH_TOKEN, searchToken);
182 protected void onSaveInstanceState(final Bundle outState) {
183 super.onSaveInstanceState(outState);
184 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
185 outState.putInt(C.INDEX_INDEX, indexIndex);
186 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
190 protected void onRestoreInstanceState(final Bundle outState) {
191 super.onRestoreInstanceState(outState);
192 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
197 public void onCreate(Bundle savedInstanceState) {
198 Log.d(LOG, "onCreate:" + this);
199 super.onCreate(savedInstanceState);
201 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
203 // Don't auto-launch if this fails.
204 prefs.edit().remove(C.INDEX_INDEX).commit();
206 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
208 application = (DictionaryApplication) getApplication();
209 theme = application.getSelectedTheme();
210 textColorFg = getResources().getColor(theme.tokenRowFgColor);
214 final Intent intent = getIntent();
215 String intentAction = intent.getAction();
217 * @author Dominik Köppl
218 * Querying the Intent
219 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
221 * SearchManager.QUERY -> the phrase to search
222 * from -> language in which the phrase is written
223 * to -> to which language shall be translated
225 if(intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
227 String query = intent.getStringExtra(SearchManager.QUERY);
228 String from = intent.getStringExtra("from");
229 if(from != null) from = from.toLowerCase(Locale.US);
230 String to = intent.getStringExtra("to");
231 if(to != null) to = to.toLowerCase(Locale.US);
234 getIntent().putExtra(C.SEARCH_TOKEN, query);
236 if(intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
238 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
239 List<DictionaryInfo> dicts = application.getUsableDicts();
240 for(DictionaryInfo info : dicts)
242 boolean hasFrom = from == null;
243 boolean hasTo = to == null;
244 for(IndexInfo index : info.indexInfos)
246 if(!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from)) hasFrom = true;
247 if(!hasTo && index.shortName.toLowerCase(Locale.US).equals(to)) hasTo = true;
254 for(;which_index < info.indexInfos.size(); ++which_index)
256 if(info.indexInfos.get(which_index).shortName.toLowerCase(Locale.US).equals(from))
259 intent.putExtra(C.INDEX_INDEX, which_index);
262 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename).toString());
270 * @author Dominik Köppl
271 * Querying the Intent
272 * Intent.ACTION_SEARCH is a simple query
273 * Arguments follow from android standard (see documentation)
275 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
277 String query = intent.getStringExtra(SearchManager.QUERY);
278 if(query != null) getIntent().putExtra(C.SEARCH_TOKEN,query);
281 * @author Dominik Köppl
282 * If no dictionary is chosen, use the default dictionary specified in the preferences
283 * If this step does fail (no default directory specified), show a toast and abort.
285 if(intent.getStringExtra(C.DICT_FILE) == null)
287 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
288 if(dictfile != null) intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
290 String dictFilename = intent.getStringExtra(C.DICT_FILE);
292 if(dictFilename == null)
294 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
295 startActivity(DictionaryManagerActivity.getLaunchIntent());
299 if(dictFilename != null) dictFile = new File(dictFilename);
302 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
304 public void onInit(int status) {
311 final String name = application.getDictionaryName(dictFile.getName());
312 this.setTitle("QuickDic: " + name);
313 dictRaf = new RandomAccessFile(dictFile, "r");
314 dictionary = new Dictionary(dictRaf);
315 } catch (Exception e) {
316 Log.e(LOG, "Unable to load dictionary.", e);
317 if (dictRaf != null) {
320 } catch (IOException e1) {
321 Log.e(LOG, "Unable to close dictRaf.", e1);
325 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
326 Toast.LENGTH_LONG).show();
327 startActivity(DictionaryManagerActivity.getLaunchIntent());
331 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
332 if (savedInstanceState != null) {
333 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
335 indexIndex %= dictionary.indices.size();
336 Log.d(LOG, "Loading index " + indexIndex);
337 index = dictionary.indices.get(indexIndex);
338 setListAdapter(new IndexAdapter(index));
340 // Pre-load the collators.
341 new Thread(new Runnable() {
343 final long startMillis = System.currentTimeMillis();
345 TransliteratorManager.init(new TransliteratorManager.Callback() {
347 public void onTransliteratorReady() {
348 uiHandler.post(new Runnable() {
351 onSearchTextChange(searchView.getQuery().toString());
357 for (final Index index : dictionary.indices) {
358 final String searchToken = index.sortedIndexEntries.get(0).token;
359 final IndexEntry entry = index.findExact(searchToken);
360 if (!searchToken.equals(entry.token)) {
361 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
364 indexPrepFinished = true;
365 } catch (Exception e) {
367 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
369 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
373 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
374 if ("SYSTEM".equals(fontName)) {
375 typeface = Typeface.DEFAULT;
378 typeface = Typeface.createFromAsset(getAssets(), fontName);
379 } catch (Exception e) {
380 Log.w(LOG, "Exception trying to use typeface, using default.", e);
381 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
382 Toast.LENGTH_LONG).show();
385 if (typeface == null) {
386 Log.w(LOG, "Unable to create typeface, using default.");
387 typeface = Typeface.DEFAULT;
389 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
391 fontSizeSp = Integer.parseInt(fontSize.trim());
392 } catch (NumberFormatException e) {
396 setContentView(R.layout.dictionary_activity);
399 registerForContextMenu(getListView());
402 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
403 getString(R.string.wordListFileDefault)));
404 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
406 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
408 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
410 onCreateSetupActionBarAndSearchView();
412 // Set the search text from the intent, then the saved state.
413 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
414 if (savedInstanceState != null) {
415 text = savedInstanceState.getString(C.SEARCH_TOKEN);
420 setSearchText(text, true);
421 Log.d(LOG, "Trying to restore searchText=" + text);
423 setDictionaryPrefs(this, dictFile, indexIndex, searchView.getQuery().toString());
428 private void onCreateSetupActionBarAndSearchView() {
429 ActionBar actionBar = getSupportActionBar();
430 actionBar.setDisplayShowTitleEnabled(false);
432 searchView = new SearchView(getSupportActionBar().getThemedContext());
433 searchView.setIconifiedByDefault(false);
434 // searchView.setIconified(false); // puts the magifying glass in the
436 searchView.setQueryHint(getString(R.string.searchText));
437 searchView.setSubmitButtonEnabled(false);
438 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
439 getResources().getDisplayMetrics());
440 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
441 FrameLayout.LayoutParams.WRAP_CONTENT);
442 searchView.setLayoutParams(lp);
443 searchView.setImeOptions(
444 EditorInfo.IME_ACTION_SEARCH |
445 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
446 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
447 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
449 EditorInfo.IME_MASK_ACTION |
450 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
451 onQueryTextListener = new OnQueryTextListener() {
453 public boolean onQueryTextSubmit(String query) {
454 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
459 public boolean onQueryTextChange(String newText) {
460 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
461 onSearchTextChange(searchView.getQuery().toString());
465 searchView.setOnQueryTextListener(onQueryTextListener);
467 searchHintIcon = (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
468 searchHintIcon.setOnClickListener(new OnClickListener() {
470 public void onClick(View arg0) {
471 onLanguageButtonClick();
474 searchHintIcon.setOnLongClickListener(new OnLongClickListener() {
476 public boolean onLongClick(View v) {
477 onLanguageButtonLongClick(v.getContext());
481 actionBar.setCustomView(searchView);
482 actionBar.setDisplayShowCustomEnabled(true);
486 protected void onResume() {
487 Log.d(LOG, "onResume");
489 if (PreferenceActivity.prefsMightHaveChanged) {
490 PreferenceActivity.prefsMightHaveChanged = false;
492 startActivity(getIntent());
498 protected void onPause() {
504 * Invoked when MyWebView returns, since the user might have clicked some
505 * hypertext in the MyWebView.
507 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
508 super.onActivityResult(requestCode, resultCode, result);
509 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
510 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
511 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
515 private static void setDictionaryPrefs(final Context context, final File dictFile,
516 final int indexIndex, final String searchToken) {
517 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
519 prefs.putString(C.DICT_FILE, dictFile.getPath());
520 prefs.putInt(C.INDEX_INDEX, indexIndex);
521 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
526 protected void onDestroy() {
528 if (dictRaf == null) {
532 final SearchOperation searchOperation = currentSearchOperation;
533 currentSearchOperation = null;
535 // Before we close the RAF, we have to wind the current search down.
536 if (searchOperation != null) {
537 Log.d(LOG, "Interrupting search to shut down.");
538 currentSearchOperation = null;
539 searchOperation.interrupted.set(true);
543 Log.d(LOG, "Closing RAF.");
545 } catch (IOException e) {
546 Log.e(LOG, "Failed to close dictionary", e);
551 // --------------------------------------------------------------------------
553 // --------------------------------------------------------------------------
555 private void showKeyboard() {
556 // searchText.postDelayed(new Runnable() {
558 // public void run() {
559 // Log.d(LOG, "Trying to show soft keyboard.");
560 // final boolean searchTextHadFocus = searchText.hasFocus();
561 // searchText.requestFocus();
562 // final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
563 // manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
564 // if (!searchTextHadFocus) {
565 // defocusSearchText();
570 void updateLangButton() {
571 final LanguageResources languageResources =
572 Language.isoCodeToResources.get(index.shortName);
573 if (languageResources != null && languageResources.flagId != 0) {
574 searchHintIcon.setImageResource(languageResources.flagId);
576 if (indexIndex % 2 == 0) {
577 searchHintIcon.setImageResource(android.R.drawable.ic_media_next);
579 searchHintIcon.setImageResource(android.R.drawable.ic_media_previous);
585 private void updateTTSLanguage() {
586 if (!ttsReady || index == null || textToSpeech == null) {
587 Log.d(LOG, "Can't updateTTSLanguage.");
590 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
591 Log.d(LOG, "Setting TTS locale to: " + locale);
592 final int ttsResult = textToSpeech.setLanguage(locale);
593 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
594 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
595 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
599 void onLanguageButtonClick() {
600 if (currentSearchOperation != null) {
601 currentSearchOperation.interrupted.set(true);
602 currentSearchOperation = null;
604 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(), searchView.getQuery().toString());
607 void onLanguageButtonLongClick(final Context context) {
608 final Dialog dialog = new Dialog(context);
609 dialog.setContentView(R.layout.select_dictionary_dialog);
610 dialog.setTitle(R.string.selectDictionary);
612 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
615 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
617 final Button button = new Button(listView.getContext());
618 final String name = getString(R.string.dictionaryManager);
619 button.setText(name);
620 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
621 DictionaryManagerActivity.getLaunchIntent()) {
623 protected void onGo() {
625 DictionaryActivity.this.finish();
628 button.setOnClickListener(intentLauncher);
629 listView.addHeaderView(button);
631 listView.setAdapter(new BaseAdapter() {
633 public View getView(int position, View convertView, ViewGroup parent) {
634 final DictionaryInfo dictionaryInfo = getItem(position);
636 final LinearLayout result = new LinearLayout(parent.getContext());
638 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
640 final TextView dash = new TextView(parent.getContext());
642 result.addView(dash);
645 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
646 final Button button = new Button(parent.getContext());
647 button.setText(indexInfo.shortName);
648 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
650 application.getPath(dictionaryInfo.uncompressedFilename),
651 i, searchView.getQuery().toString())) {
653 protected void onGo() {
655 DictionaryActivity.this.finish();
658 button.setOnClickListener(intentLauncher);
659 result.addView(button);
663 final TextView nameView = new TextView(parent.getContext());
664 final String name = application
665 .getDictionaryName(dictionaryInfo.uncompressedFilename);
666 nameView.setText(name);
667 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
668 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
669 layoutParams.width = 0;
670 layoutParams.weight = 1.0f;
671 nameView.setLayoutParams(layoutParams);
672 result.addView(nameView);
678 public long getItemId(int position) {
683 public DictionaryInfo getItem(int position) {
684 return installedDicts.get(position);
688 public int getCount() {
689 return installedDicts.size();
696 void onUpDownButton(final boolean up) {
700 final int firstVisibleRow = getListView().getFirstVisiblePosition();
701 final RowBase row = index.rows.get(firstVisibleRow);
702 final TokenRow tokenRow = row.getTokenRow(true);
703 final int destIndexEntry;
705 if (row != tokenRow) {
706 destIndexEntry = tokenRow.referenceIndex;
708 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
712 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
714 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
715 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
716 setSearchText(dest.token, false);
717 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
721 // --------------------------------------------------------------------------
723 // --------------------------------------------------------------------------
725 final Random random = new Random();
728 public boolean onCreateOptionsMenu(final Menu menu) {
730 if (PreferenceManager.getDefaultSharedPreferences(this)
731 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
733 nextWordMenuItem = menu.add(getString(R.string.nextWord))
734 .setIcon(R.drawable.arrow_down_float);
735 nextWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
736 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
738 public boolean onMenuItemClick(MenuItem item) {
739 onUpDownButton(false);
745 previousWordMenuItem = menu.add(getString(R.string.previousWord))
746 .setIcon(R.drawable.arrow_up_float);
747 previousWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
748 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
750 public boolean onMenuItemClick(MenuItem item) {
751 onUpDownButton(true);
757 application.onCreateGlobalOptionsMenu(this, menu);
760 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
761 dictionaryList.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
762 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
763 public boolean onMenuItemClick(final MenuItem menuItem) {
764 startActivity(DictionaryManagerActivity.getLaunchIntent());
772 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
773 aboutDictionary.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
774 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
775 public boolean onMenuItemClick(final MenuItem menuItem) {
776 final Context context = getListView().getContext();
777 final Dialog dialog = new Dialog(context);
778 dialog.setContentView(R.layout.about_dictionary_dialog);
779 final TextView textView = (TextView) dialog.findViewById(R.id.text);
781 final String name = application.getDictionaryName(dictFile.getName());
782 dialog.setTitle(name);
784 final StringBuilder builder = new StringBuilder();
785 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
786 dictionaryInfo.uncompressedBytes = dictFile.length();
787 if (dictionaryInfo != null) {
788 builder.append(dictionaryInfo.dictInfo).append("\n\n");
789 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
792 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
795 getString(R.string.dictionaryCreationTime,
796 dictionaryInfo.creationMillis)).append("\n");
797 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
798 builder.append("\n");
799 builder.append(getString(R.string.indexName, indexInfo.shortName))
802 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
805 builder.append("\n");
806 builder.append(getString(R.string.sources)).append("\n");
807 for (final EntrySource source : dictionary.sources) {
809 getString(R.string.sourceInfo, source.getName(),
810 source.getNumEntries())).append("\n");
813 textView.setText(builder.toString());
816 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
817 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
818 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
819 dialog.getWindow().setAttributes(layoutParams);
828 // --------------------------------------------------------------------------
829 // Context Menu + clicks
830 // --------------------------------------------------------------------------
833 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
834 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
835 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
837 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
838 wordList.getName()));
839 addToWordlist.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
840 public boolean onMenuItemClick(android.view.MenuItem item) {
841 onAppendToWordList(row);
846 final android.view.MenuItem share = menu.add("Share");
847 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
848 public boolean onMenuItemClick(android.view.MenuItem item) {
849 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
850 shareIntent.setType("text/plain");
851 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true).getToken());
852 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, row.getRawText(saveOnlyFirstSubentry));
853 startActivity(shareIntent);
858 final android.view.MenuItem copy = menu.add(android.R.string.copy);
859 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
860 public boolean onMenuItemClick(android.view.MenuItem item) {
866 if (selectedSpannableText != null) {
867 final String selectedText = selectedSpannableText;
868 final android.view.MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
869 selectedSpannableText));
870 searchForSelection.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
871 public boolean onMenuItemClick(android.view.MenuItem item) {
872 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
878 if (row instanceof TokenRow && ttsReady) {
879 final android.view.MenuItem speak = menu.add(R.string.speak);
880 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
882 public boolean onMenuItemClick(android.view.MenuItem item) {
883 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
884 new HashMap<String, String>());
891 private void jumpToTextFromHyperLink(
892 final String selectedText, final int defaultIndexToUse) {
894 for (int i = 0; i < dictionary.indices.size(); ++i) {
895 final Index index = dictionary.indices.get(i);
896 if (indexPrepFinished) {
897 System.out.println("Doing index lookup: on " + selectedText);
898 final IndexEntry indexEntry = index.findExact(selectedText);
899 if (indexEntry != null) {
900 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
902 if (tokenRow != null && tokenRow.hasMainEntry) {
908 Log.w(LOG, "Skipping findExact on index " + index.shortName);
911 if (indexToUse == -1) {
912 indexToUse = defaultIndexToUse;
914 setIndexAndSearchText(indexToUse, selectedText);
918 * Called when user clicks outside of search text, so that they can start
919 * typing again immediately.
921 void defocusSearchText() {
922 // Log.d(LOG, "defocusSearchText");
923 // Request focus so that if we start typing again, it clears the text
925 getListView().requestFocus();
927 // Visual indication that a new keystroke will clear the search text.
928 // Doesn't seem to work unless earchText has focus.
929 // searchView.selectAll();
933 protected void onListItemClick(ListView l, View v, int row, long id) {
935 if (clickOpensContextMenu && dictRaf != null) {
940 @SuppressLint("SimpleDateFormat")
941 void onAppendToWordList(final RowBase row) {
944 final StringBuilder rawText = new StringBuilder();
945 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
946 rawText.append(index.longName).append("\t");
947 rawText.append(row.getTokenRow(true).getToken()).append("\t");
948 rawText.append(row.getRawText(saveOnlyFirstSubentry));
949 Log.d(LOG, "Writing : " + rawText);
952 wordList.getParentFile().mkdirs();
953 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
954 out.println(rawText.toString());
956 } catch (IOException e) {
957 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
959 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
960 Toast.LENGTH_LONG).show();
965 @SuppressWarnings("deprecation")
966 void onCopy(final RowBase row) {
969 Log.d(LOG, "Copy, row=" + row);
970 final StringBuilder result = new StringBuilder();
971 result.append(row.getRawText(false));
972 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
973 clipboardManager.setText(result.toString());
974 Log.d(LOG, "Copied: " + result);
978 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
979 if (event.getUnicodeChar() != 0) {
980 if (!searchView.hasFocus()) {
981 setSearchText("" + (char) event.getUnicodeChar(), true);
983 searchView.requestFocus();
986 if (keyCode == KeyEvent.KEYCODE_BACK) {
987 // Log.d(LOG, "Clearing dictionary prefs.");
988 // Pretend that we just autolaunched so that we won't do it again.
989 // DictionaryManagerActivity.lastAutoLaunchMillis =
990 // System.currentTimeMillis();
992 if (keyCode == KeyEvent.KEYCODE_ENTER) {
993 Log.d(LOG, "Trying to hide soft keyboard.");
994 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
995 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
996 InputMethodManager.HIDE_NOT_ALWAYS);
999 return super.onKeyDown(keyCode, event);
1002 private void setIndexAndSearchText(int newIndex, String newSearchText) {
1003 Log.d(LOG, "Changing index to: " + newIndex);
1004 if (newIndex == -1) {
1005 Log.e(LOG, "Invalid index.");
1008 if (newIndex != indexIndex) {
1009 indexIndex = newIndex;
1010 index = dictionary.indices.get(indexIndex);
1011 indexAdapter = new IndexAdapter(index);
1012 setListAdapter(indexAdapter);
1013 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1014 setDictionaryPrefs(this, dictFile, indexIndex, searchView.getQuery().toString());
1017 setSearchText(newSearchText, true);
1020 private void setSearchText(final String text, final boolean triggerSearch) {
1021 if (!triggerSearch) {
1022 searchView.setOnQueryTextListener(null);
1024 searchView.setQuery(text, false);
1025 moveCursorToRight();
1026 if (!triggerSearch) {
1027 searchView.setOnQueryTextListener(onQueryTextListener);
1029 onQueryTextListener.onQueryTextChange(text);
1033 // private long cursorDelayMillis = 100;
1034 private void moveCursorToRight() {
1035 // if (searchText.getLayout() != null) {
1036 // cursorDelayMillis = 100;
1037 // // Surprising, but this can crash when you rotate...
1038 // Selection.moveToRightEdge(searchView.getQuery(), searchText.getLayout());
1040 // uiHandler.postDelayed(new Runnable() {
1042 // public void run() {
1043 // moveCursorToRight();
1045 // }, cursorDelayMillis);
1046 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1050 // --------------------------------------------------------------------------
1052 // --------------------------------------------------------------------------
1054 private void searchFinished(final SearchOperation searchOperation) {
1055 if (searchOperation.interrupted.get()) {
1056 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1059 if (searchOperation != this.currentSearchOperation) {
1060 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1064 final Index.IndexEntry searchResult = searchOperation.searchResult;
1065 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1067 currentSearchOperation = null;
1068 uiHandler.postDelayed(new Runnable() {
1071 if (currentSearchOperation == null) {
1072 if (searchResult != null) {
1076 jumpToRow(searchResult.startRow);
1077 } else if (searchOperation.multiWordSearchResult != null) {
1078 // Multi-row search....
1079 setFiltered(searchOperation);
1081 throw new IllegalStateException("This should never happen.");
1084 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1090 private final void jumpToRow(final int row) {
1091 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1092 // getListView().requestFocusFromTouch();
1093 getListView().setSelectionFromTop(row, 0);
1094 getListView().setSelected(true);
1097 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1099 final class SearchOperation implements Runnable {
1101 final AtomicBoolean interrupted = new AtomicBoolean(false);
1103 final String searchText;
1105 List<String> searchTokens; // filled in for multiWord.
1109 long searchStartMillis;
1111 Index.IndexEntry searchResult;
1113 List<RowBase> multiWordSearchResult;
1115 boolean done = false;
1117 SearchOperation(final String searchText, final Index index) {
1118 this.searchText = StringUtil.normalizeWhitespace(searchText);
1122 public String toString() {
1123 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1129 searchStartMillis = System.currentTimeMillis();
1130 final String[] searchTokenArray = WHITESPACE.split(searchText);
1131 if (searchTokenArray.length == 1) {
1132 searchResult = index.findInsertionPoint(searchText, interrupted);
1134 searchTokens = Arrays.asList(searchTokenArray);
1135 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens, interrupted);
1138 "searchText=" + searchText + ", searchDuration="
1139 + (System.currentTimeMillis() - searchStartMillis)
1140 + ", interrupted=" + interrupted.get());
1141 if (!interrupted.get()) {
1142 uiHandler.post(new Runnable() {
1145 searchFinished(SearchOperation.this);
1149 Log.d(LOG, "interrupted, skipping searchFinished.");
1151 } catch (Exception e) {
1152 Log.e(LOG, "Failure during search (can happen during Activity close.");
1154 synchronized (this) {
1162 // --------------------------------------------------------------------------
1164 // --------------------------------------------------------------------------
1166 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1167 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1169 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1170 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1172 final class IndexAdapter extends BaseAdapter {
1174 private static final float PADDING_DEFAULT_DP = 8;
1176 private static final float PADDING_LARGE_DP = 16;
1180 final List<RowBase> rows;
1182 final Set<String> toHighlight;
1184 private int mPaddingDefault;
1186 private int mPaddingLarge;
1188 IndexAdapter(final Index index) {
1191 this.toHighlight = null;
1195 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1198 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1202 private void getMetrics() {
1203 // Get the screen's density scale
1204 final float scale = getResources().getDisplayMetrics().density;
1205 // Convert the dps to pixels, based on density scale
1206 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1207 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1211 public int getCount() {
1216 public RowBase getItem(int position) {
1217 return rows.get(position);
1221 public long getItemId(int position) {
1222 return getItem(position).index();
1226 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1227 final TableLayout result;
1228 if (convertView instanceof TableLayout) {
1229 result = (TableLayout) convertView;
1230 result.removeAllViews();
1232 result = new TableLayout(parent.getContext());
1234 final RowBase row = getItem(position);
1235 if (row instanceof PairEntry.Row) {
1236 return getView(position, (PairEntry.Row) row, parent, result);
1237 } else if (row instanceof TokenRow) {
1238 return getView((TokenRow) row, parent, result);
1239 } else if (row instanceof HtmlEntry.Row) {
1240 return getView((HtmlEntry.Row) row, parent, result);
1242 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1246 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1247 final TableLayout result) {
1248 final PairEntry entry = row.getEntry();
1249 final int rowCount = entry.pairs.size();
1251 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1252 layoutParams.weight = 0.5f;
1253 layoutParams.leftMargin = mPaddingLarge;
1255 for (int r = 0; r < rowCount; ++r) {
1256 final TableRow tableRow = new TableRow(result.getContext());
1258 final TextView col1 = new TextView(tableRow.getContext());
1259 final TextView col2 = new TextView(tableRow.getContext());
1261 // Set the columns in the table.
1263 final TextView bullet = new TextView(tableRow.getContext());
1264 bullet.setText(" • ");
1265 tableRow.addView(bullet);
1267 tableRow.addView(col1, layoutParams);
1268 final TextView margin = new TextView(tableRow.getContext());
1269 margin.setText(" ");
1270 tableRow.addView(margin);
1272 final TextView bullet = new TextView(tableRow.getContext());
1273 bullet.setText(" • ");
1274 tableRow.addView(bullet);
1276 tableRow.addView(col2, layoutParams);
1280 // Set what's in the columns.
1282 final Pair pair = entry.pairs.get(r);
1283 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1284 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1286 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1287 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1289 // Bold the token instances in col1.
1290 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1291 .singleton(row.getTokenRow(true).getToken());
1292 final Spannable col1Spannable = (Spannable) col1.getText();
1293 for (final String token : toBold) {
1295 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1296 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1297 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1298 startPos += token.length();
1302 createTokenLinkSpans(col1, col1Spannable, col1Text);
1303 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1305 col1.setTypeface(typeface);
1306 col2.setTypeface(typeface);
1307 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1308 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1309 // col2.setBackgroundResource(theme.otherLangBg);
1311 if (index.swapPairEntries) {
1312 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1313 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1315 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1316 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1319 result.addView(tableRow);
1322 // Because we have a Button inside a ListView row:
1323 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1324 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1325 result.setClickable(true);
1326 result.setFocusable(true);
1327 result.setLongClickable(true);
1328 result.setBackgroundResource(android.R.drawable.menuitem_background);
1329 result.setOnClickListener(new TextView.OnClickListener() {
1331 public void onClick(View v) {
1332 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1339 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1340 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1341 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1342 final Context context = parent.getContext();
1344 final TableRow tableRow = new TableRow(result.getContext());
1345 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1346 : theme.tokenRowOtherBg);
1348 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1350 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1352 result.addView(tableRow);
1354 // Make it so we can long-click on these token rows, too:
1355 final TextView textView = new TextView(context);
1356 textView.setText(text, BufferType.SPANNABLE);
1357 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1358 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1360 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1361 result.setLongClickable(true);
1364 // textView.setTextColor(android.R.color.secondary_text_light);
1365 textView.setTypeface(typeface);
1366 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1368 textView.setTextAppearance(context, theme.tokenRowFg);
1369 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1371 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1375 textView.setLayoutParams(lp);
1376 tableRow.addView(textView);
1378 if (!htmlEntries.isEmpty()) {
1379 final ClickableSpan clickableSpan = new ClickableSpan() {
1381 public void onClick(View widget) {
1384 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1385 result.setClickable(true);
1386 textView.setClickable(true);
1387 textView.setMovementMethod(LinkMovementMethod.getInstance());
1388 textView.setOnClickListener(new OnClickListener() {
1390 public void onClick(View v) {
1391 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1392 //Log.d(LOG, "html=" + html);
1393 startActivityForResult(
1394 HtmlDisplayActivity.getHtmlIntent(String.format(
1395 "<html><head></head><body>%s</body></html>", html),
1396 htmlTextToHighlight, false),
1404 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1405 final IndexEntry indexEntry = row.getIndexEntry();
1406 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1407 indexEntry.htmlEntries, null, parent, result);
1410 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1411 final HtmlEntry htmlEntry = row.getEntry();
1412 final TokenRow tokenRow = row.getTokenRow(true);
1413 return getPossibleLinkToHtmlEntryView(false,
1414 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1415 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1421 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1423 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1424 final String text) {
1425 // Saw from the source code that LinkMovementMethod sets the selection!
1426 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1427 textView.setMovementMethod(LinkMovementMethod.getInstance());
1428 final Matcher matcher = CHAR_DASH.matcher(text);
1429 while (matcher.find()) {
1430 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
1431 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1435 String selectedSpannableText = null;
1437 int selectedSpannableIndex = -1;
1440 public boolean onTouchEvent(MotionEvent event) {
1441 selectedSpannableText = null;
1442 selectedSpannableIndex = -1;
1443 return super.onTouchEvent(event);
1446 private class TextViewLongClickListener implements OnLongClickListener {
1449 private TextViewLongClickListener(final int index) {
1454 public boolean onLongClick(final View v) {
1455 final TextView textView = (TextView) v;
1456 final int start = textView.getSelectionStart();
1457 final int end = textView.getSelectionEnd();
1458 if (start >= 0 && end >= 0) {
1459 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1460 selectedSpannableIndex = index;
1466 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1469 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1472 // --------------------------------------------------------------------------
1474 // --------------------------------------------------------------------------
1476 void onSearchTextChange(final String text) {
1477 if ("thadolina".equals(text)) {
1478 final Dialog dialog = new Dialog(getListView().getContext());
1479 dialog.setContentView(R.layout.thadolina_dialog);
1480 dialog.setTitle("Ti amo, amore mio!");
1481 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1482 imageView.setOnClickListener(new OnClickListener() {
1484 public void onClick(View v) {
1485 final Intent intent = new Intent(Intent.ACTION_VIEW);
1486 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1487 startActivity(intent);
1492 if (dictRaf == null) {
1493 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1496 // if (!searchView.hasFocus()) {
1497 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1500 Log.d(LOG, "onSearchTextChange: " + text);
1501 if (currentSearchOperation != null) {
1502 Log.d(LOG, "Interrupting currentSearchOperation.");
1503 currentSearchOperation.interrupted.set(true);
1505 currentSearchOperation = new SearchOperation(text, index);
1506 searchExecutor.execute(currentSearchOperation);
1509 // --------------------------------------------------------------------------
1510 // Filtered results.
1511 // --------------------------------------------------------------------------
1513 boolean isFiltered() {
1514 return rowsToShow != null;
1517 void setFiltered(final SearchOperation searchOperation) {
1518 if (nextWordMenuItem != null) {
1519 nextWordMenuItem.setEnabled(false);
1520 previousWordMenuItem.setEnabled(false);
1522 rowsToShow = searchOperation.multiWordSearchResult;
1523 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1526 void clearFiltered() {
1527 if (nextWordMenuItem != null) {
1528 nextWordMenuItem.setEnabled(true);
1529 previousWordMenuItem.setEnabled(true);
1531 setListAdapter(new IndexAdapter(index));