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;
137 TextToSpeech textToSpeech;
138 volatile boolean ttsReady;
141 C.Theme theme = C.Theme.LIGHT;
142 int textColorFg = Color.BLACK;
145 SearchView searchView;
146 ImageView searchHintIcon;
147 SearchView.OnQueryTextListener onQueryTextListener;
149 MenuItem nextWordMenuItem, previousWordMenuItem;
152 private File wordList = null;
153 private boolean saveOnlyFirstSubentry = false;
154 private boolean clickOpensContextMenu = false;
156 // Visible for testing.
157 ListAdapter indexAdapter = null;
160 * For some languages, loading the transliterators used in this search takes
161 * a long time, so we fire it up on a different thread, and don't invoke it
162 * from the main thread until it's already finished once.
164 private volatile boolean indexPrepFinished = false;
166 public DictionaryActivity() {
169 public static Intent getLaunchIntent(final File dictFile, final String indexShortName,
170 final String searchToken) {
171 final Intent intent = new Intent();
172 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
173 DictionaryActivity.class.getName());
174 intent.putExtra(C.DICT_FILE, dictFile.getPath());
175 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
176 intent.putExtra(C.SEARCH_TOKEN, searchToken);
181 protected void onSaveInstanceState(final Bundle outState) {
182 super.onSaveInstanceState(outState);
183 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
184 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
185 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
189 protected void onRestoreInstanceState(final Bundle savedInstanceState) {
190 super.onRestoreInstanceState(savedInstanceState);
191 Log.d(LOG, "onRestoreInstanceState: " + savedInstanceState.getString(C.SEARCH_TOKEN));
192 onCreate(savedInstanceState);
196 public void onCreate(Bundle savedInstanceState) {
197 Log.d(LOG, "onCreate:" + this);
198 super.onCreate(savedInstanceState);
200 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
202 // Don't auto-launch if this fails.
203 prefs.edit().remove(C.INDEX_SHORT_NAME).commit();
205 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
207 application = (DictionaryApplication) getApplication();
208 theme = application.getSelectedTheme();
209 textColorFg = getResources().getColor(theme.tokenRowFgColor);
211 final Intent intent = getIntent();
212 String intentAction = intent.getAction();
214 * @author Dominik Köppl
215 * Querying the Intent
216 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
218 * SearchManager.QUERY -> the phrase to search
219 * from -> language in which the phrase is written
220 * to -> to which language shall be translated
222 if(intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
224 String query = intent.getStringExtra(SearchManager.QUERY);
225 String from = intent.getStringExtra("from");
226 if(from != null) from = from.toLowerCase(Locale.US);
227 String to = intent.getStringExtra("to");
228 if(to != null) to = to.toLowerCase(Locale.US);
231 getIntent().putExtra(C.SEARCH_TOKEN, query);
233 if(intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
235 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
236 List<DictionaryInfo> dicts = application.getDictionariesOnDevice();
237 for(DictionaryInfo info : dicts)
239 boolean hasFrom = from == null;
240 boolean hasTo = to == null;
241 for(IndexInfo index : info.indexInfos)
243 if(!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from)) hasFrom = true;
244 if(!hasTo && index.shortName.toLowerCase(Locale.US).equals(to)) hasTo = true;
251 for(;which_index < info.indexInfos.size(); ++which_index)
253 if(info.indexInfos.get(which_index).shortName.toLowerCase(Locale.US).equals(from))
256 intent.putExtra(C.INDEX_SHORT_NAME, info.indexInfos.get(which_index).shortName);
259 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename).toString());
267 * @author Dominik Köppl
268 * Querying the Intent
269 * Intent.ACTION_SEARCH is a simple query
270 * Arguments follow from android standard (see documentation)
272 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
274 String query = intent.getStringExtra(SearchManager.QUERY);
275 if(query != null) getIntent().putExtra(C.SEARCH_TOKEN,query);
278 * @author Dominik Köppl
279 * If no dictionary is chosen, use the default dictionary specified in the preferences
280 * If this step does fail (no default directory specified), show a toast and abort.
282 if(intent.getStringExtra(C.DICT_FILE) == null)
284 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
285 if(dictfile != null) intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
287 String dictFilename = intent.getStringExtra(C.DICT_FILE);
289 if(dictFilename == null)
291 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
292 startActivity(DictionaryManagerActivity.getLaunchIntent());
296 if(dictFilename != null) dictFile = new File(dictFilename);
299 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
301 public void onInit(int status) {
308 final String name = application.getDictionaryName(dictFile.getName());
309 this.setTitle("QuickDic: " + name);
310 dictRaf = new RandomAccessFile(dictFile, "r");
311 dictionary = new Dictionary(dictRaf);
312 } catch (Exception e) {
313 Log.e(LOG, "Unable to load dictionary.", e);
314 if (dictRaf != null) {
317 } catch (IOException e1) {
318 Log.e(LOG, "Unable to close dictRaf.", e1);
322 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
323 Toast.LENGTH_LONG).show();
324 startActivity(DictionaryManagerActivity.getLaunchIntent());
328 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
329 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
330 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
333 for (int i = 0; i < dictionary.indices.size(); ++i) {
334 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
339 indexIndex %= dictionary.indices.size();
340 Log.d(LOG, "Loading index " + indexIndex);
341 index = dictionary.indices.get(indexIndex);
342 setListAdapter(new IndexAdapter(index));
344 // Pre-load the collators.
345 new Thread(new Runnable() {
347 final long startMillis = System.currentTimeMillis();
349 TransliteratorManager.init(new TransliteratorManager.Callback() {
351 public void onTransliteratorReady() {
352 uiHandler.post(new Runnable() {
355 onSearchTextChange(searchView.getQuery().toString());
361 for (final Index index : dictionary.indices) {
362 final String searchToken = index.sortedIndexEntries.get(0).token;
363 final IndexEntry entry = index.findExact(searchToken);
364 if (!searchToken.equals(entry.token)) {
365 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
368 indexPrepFinished = true;
369 } catch (Exception e) {
371 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
373 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
377 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
378 if ("SYSTEM".equals(fontName)) {
379 typeface = Typeface.DEFAULT;
382 typeface = Typeface.createFromAsset(getAssets(), fontName);
383 } catch (Exception e) {
384 Log.w(LOG, "Exception trying to use typeface, using default.", e);
385 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
386 Toast.LENGTH_LONG).show();
389 if (typeface == null) {
390 Log.w(LOG, "Unable to create typeface, using default.");
391 typeface = Typeface.DEFAULT;
393 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
395 fontSizeSp = Integer.parseInt(fontSize.trim());
396 } catch (NumberFormatException e) {
400 setContentView(R.layout.dictionary_activity);
403 registerForContextMenu(getListView());
406 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
407 getString(R.string.wordListFileDefault)));
408 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
410 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
412 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
414 onCreateSetupActionBarAndSearchView();
416 // Set the search text from the intent, then the saved state.
417 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
418 if (savedInstanceState != null) {
419 text = savedInstanceState.getString(C.SEARCH_TOKEN);
424 setSearchText(text, true);
425 Log.d(LOG, "Trying to restore searchText=" + text);
427 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
432 private void onCreateSetupActionBarAndSearchView() {
433 ActionBar actionBar = getSupportActionBar();
434 actionBar.setDisplayShowTitleEnabled(false);
436 searchView = new SearchView(getSupportActionBar().getThemedContext());
437 searchView.setIconifiedByDefault(false);
438 // searchView.setIconified(false); // puts the magifying glass in the
440 searchView.setQueryHint(getString(R.string.searchText));
441 searchView.setSubmitButtonEnabled(false);
442 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
443 getResources().getDisplayMetrics());
444 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
445 FrameLayout.LayoutParams.WRAP_CONTENT);
446 searchView.setLayoutParams(lp);
447 searchView.setImeOptions(
448 EditorInfo.IME_ACTION_SEARCH |
449 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
450 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
451 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
453 EditorInfo.IME_MASK_ACTION |
454 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
455 onQueryTextListener = new OnQueryTextListener() {
457 public boolean onQueryTextSubmit(String query) {
458 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
463 public boolean onQueryTextChange(String newText) {
464 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
465 onSearchTextChange(searchView.getQuery().toString());
469 searchView.setOnQueryTextListener(onQueryTextListener);
471 searchHintIcon = (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
472 searchHintIcon.setOnClickListener(new OnClickListener() {
474 public void onClick(View arg0) {
475 onLanguageButtonClick();
478 searchHintIcon.setOnLongClickListener(new OnLongClickListener() {
480 public boolean onLongClick(View v) {
481 onLanguageButtonLongClick(v.getContext());
485 actionBar.setCustomView(searchView);
486 actionBar.setDisplayShowCustomEnabled(true);
490 protected void onResume() {
491 Log.d(LOG, "onResume");
493 if (PreferenceActivity.prefsMightHaveChanged) {
494 PreferenceActivity.prefsMightHaveChanged = false;
496 startActivity(getIntent());
502 protected void onPause() {
508 * Invoked when MyWebView returns, since the user might have clicked some
509 * hypertext in the MyWebView.
511 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
512 super.onActivityResult(requestCode, resultCode, result);
513 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
514 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
515 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
519 private static void setDictionaryPrefs(final Context context, final File dictFile,
520 final String indexShortName, final String searchToken) {
521 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
523 prefs.putString(C.DICT_FILE, dictFile.getPath());
524 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
525 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
530 protected void onDestroy() {
532 if (dictRaf == null) {
536 final SearchOperation searchOperation = currentSearchOperation;
537 currentSearchOperation = null;
539 // Before we close the RAF, we have to wind the current search down.
540 if (searchOperation != null) {
541 Log.d(LOG, "Interrupting search to shut down.");
542 currentSearchOperation = null;
543 searchOperation.interrupted.set(true);
547 Log.d(LOG, "Closing RAF.");
549 } catch (IOException e) {
550 Log.e(LOG, "Failed to close dictionary", e);
555 // --------------------------------------------------------------------------
557 // --------------------------------------------------------------------------
559 private void showKeyboard() {
560 // searchText.postDelayed(new Runnable() {
562 // public void run() {
563 // Log.d(LOG, "Trying to show soft keyboard.");
564 // final boolean searchTextHadFocus = searchText.hasFocus();
565 // searchText.requestFocus();
566 // final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
567 // manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
568 // if (!searchTextHadFocus) {
569 // defocusSearchText();
574 void updateLangButton() {
575 final LanguageResources languageResources =
576 Language.isoCodeToResources.get(index.shortName);
577 if (languageResources != null && languageResources.flagId != 0) {
578 searchHintIcon.setImageResource(languageResources.flagId);
580 if (indexIndex % 2 == 0) {
581 searchHintIcon.setImageResource(android.R.drawable.ic_media_next);
583 searchHintIcon.setImageResource(android.R.drawable.ic_media_previous);
589 private void updateTTSLanguage() {
590 if (!ttsReady || index == null || textToSpeech == null) {
591 Log.d(LOG, "Can't updateTTSLanguage.");
594 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
595 Log.d(LOG, "Setting TTS locale to: " + locale);
596 final int ttsResult = textToSpeech.setLanguage(locale);
597 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
598 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
599 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
603 void onLanguageButtonClick() {
604 if (currentSearchOperation != null) {
605 currentSearchOperation.interrupted.set(true);
606 currentSearchOperation = null;
608 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(), searchView.getQuery().toString());
611 void onLanguageButtonLongClick(final Context context) {
612 final Dialog dialog = new Dialog(context);
613 dialog.setContentView(R.layout.select_dictionary_dialog);
614 dialog.setTitle(R.string.selectDictionary);
616 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice();
618 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
619 final Button button = new Button(listView.getContext());
620 final String name = getString(R.string.dictionaryManager);
621 button.setText(name);
622 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
623 DictionaryManagerActivity.getLaunchIntent()) {
625 protected void onGo() {
627 DictionaryActivity.this.finish();
630 button.setOnClickListener(intentLauncher);
631 listView.addHeaderView(button);
633 listView.setAdapter(new BaseAdapter() {
635 public View getView(int position, View convertView, ViewGroup parent) {
636 final DictionaryInfo dictionaryInfo = getItem(position);
638 final LinearLayout result = new LinearLayout(parent.getContext());
640 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
641 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
642 final View button = application.createButton(parent.getContext(), dictionaryInfo, indexInfo);
643 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
645 application.getPath(dictionaryInfo.uncompressedFilename),
646 indexInfo.shortName, searchView.getQuery().toString())) {
648 protected void onGo() {
650 DictionaryActivity.this.finish();
653 button.setOnClickListener(intentLauncher);
654 result.addView(button);
657 final TextView nameView = new TextView(parent.getContext());
658 final String name = application
659 .getDictionaryName(dictionaryInfo.uncompressedFilename);
660 nameView.setText(name);
661 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
662 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
663 layoutParams.width = 0;
664 layoutParams.weight = 1.0f;
665 nameView.setLayoutParams(layoutParams);
666 result.addView(nameView);
671 public long getItemId(int position) {
676 public DictionaryInfo getItem(int position) {
677 return installedDicts.get(position);
681 public int getCount() {
682 return installedDicts.size();
688 void onUpDownButton(final boolean up) {
692 final int firstVisibleRow = getListView().getFirstVisiblePosition();
693 final RowBase row = index.rows.get(firstVisibleRow);
694 final TokenRow tokenRow = row.getTokenRow(true);
695 final int destIndexEntry;
697 if (row != tokenRow) {
698 destIndexEntry = tokenRow.referenceIndex;
700 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
704 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
706 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
707 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
708 setSearchText(dest.token, false);
709 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
713 // --------------------------------------------------------------------------
715 // --------------------------------------------------------------------------
717 final Random random = new Random();
720 public boolean onCreateOptionsMenu(final Menu menu) {
722 if (PreferenceManager.getDefaultSharedPreferences(this)
723 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
725 nextWordMenuItem = menu.add(getString(R.string.nextWord))
726 .setIcon(R.drawable.arrow_down_float);
727 nextWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
728 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
730 public boolean onMenuItemClick(MenuItem item) {
731 onUpDownButton(false);
737 previousWordMenuItem = menu.add(getString(R.string.previousWord))
738 .setIcon(R.drawable.arrow_up_float);
739 previousWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
740 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
742 public boolean onMenuItemClick(MenuItem item) {
743 onUpDownButton(true);
749 application.onCreateGlobalOptionsMenu(this, menu);
752 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
753 dictionaryList.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
754 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
755 public boolean onMenuItemClick(final MenuItem menuItem) {
756 startActivity(DictionaryManagerActivity.getLaunchIntent());
764 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
765 aboutDictionary.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
766 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
767 public boolean onMenuItemClick(final MenuItem menuItem) {
768 final Context context = getListView().getContext();
769 final Dialog dialog = new Dialog(context);
770 dialog.setContentView(R.layout.about_dictionary_dialog);
771 final TextView textView = (TextView) dialog.findViewById(R.id.text);
773 final String name = application.getDictionaryName(dictFile.getName());
774 dialog.setTitle(name);
776 final StringBuilder builder = new StringBuilder();
777 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
778 dictionaryInfo.uncompressedBytes = dictFile.length();
779 if (dictionaryInfo != null) {
780 builder.append(dictionaryInfo.dictInfo).append("\n\n");
781 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
784 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
787 getString(R.string.dictionaryCreationTime,
788 dictionaryInfo.creationMillis)).append("\n");
789 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
790 builder.append("\n");
791 builder.append(getString(R.string.indexName, indexInfo.shortName))
794 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
797 builder.append("\n");
798 builder.append(getString(R.string.sources)).append("\n");
799 for (final EntrySource source : dictionary.sources) {
801 getString(R.string.sourceInfo, source.getName(),
802 source.getNumEntries())).append("\n");
805 textView.setText(builder.toString());
808 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
809 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
810 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
811 dialog.getWindow().setAttributes(layoutParams);
820 // --------------------------------------------------------------------------
821 // Context Menu + clicks
822 // --------------------------------------------------------------------------
825 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
826 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
827 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
829 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
830 wordList.getName()));
831 addToWordlist.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
832 public boolean onMenuItemClick(android.view.MenuItem item) {
833 onAppendToWordList(row);
838 final android.view.MenuItem share = menu.add("Share");
839 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
840 public boolean onMenuItemClick(android.view.MenuItem item) {
841 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
842 shareIntent.setType("text/plain");
843 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true).getToken());
844 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, row.getRawText(saveOnlyFirstSubentry));
845 startActivity(shareIntent);
850 final android.view.MenuItem copy = menu.add(android.R.string.copy);
851 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
852 public boolean onMenuItemClick(android.view.MenuItem item) {
858 if (selectedSpannableText != null) {
859 final String selectedText = selectedSpannableText;
860 final android.view.MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
861 selectedSpannableText));
862 searchForSelection.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
863 public boolean onMenuItemClick(android.view.MenuItem item) {
864 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
870 if (row instanceof TokenRow && ttsReady) {
871 final android.view.MenuItem speak = menu.add(R.string.speak);
872 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
874 public boolean onMenuItemClick(android.view.MenuItem item) {
875 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
876 new HashMap<String, String>());
883 private void jumpToTextFromHyperLink(
884 final String selectedText, final int defaultIndexToUse) {
886 for (int i = 0; i < dictionary.indices.size(); ++i) {
887 final Index index = dictionary.indices.get(i);
888 if (indexPrepFinished) {
889 System.out.println("Doing index lookup: on " + selectedText);
890 final IndexEntry indexEntry = index.findExact(selectedText);
891 if (indexEntry != null) {
892 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
894 if (tokenRow != null && tokenRow.hasMainEntry) {
900 Log.w(LOG, "Skipping findExact on index " + index.shortName);
903 if (indexToUse == -1) {
904 indexToUse = defaultIndexToUse;
906 setIndexAndSearchText(indexToUse, selectedText);
910 * Called when user clicks outside of search text, so that they can start
911 * typing again immediately.
913 void defocusSearchText() {
914 // Log.d(LOG, "defocusSearchText");
915 // Request focus so that if we start typing again, it clears the text
917 getListView().requestFocus();
919 // Visual indication that a new keystroke will clear the search text.
920 // Doesn't seem to work unless earchText has focus.
921 // searchView.selectAll();
925 protected void onListItemClick(ListView l, View v, int row, long id) {
927 if (clickOpensContextMenu && dictRaf != null) {
932 @SuppressLint("SimpleDateFormat")
933 void onAppendToWordList(final RowBase row) {
936 final StringBuilder rawText = new StringBuilder();
937 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
938 rawText.append(index.longName).append("\t");
939 rawText.append(row.getTokenRow(true).getToken()).append("\t");
940 rawText.append(row.getRawText(saveOnlyFirstSubentry));
941 Log.d(LOG, "Writing : " + rawText);
944 wordList.getParentFile().mkdirs();
945 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
946 out.println(rawText.toString());
948 } catch (IOException e) {
949 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
951 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
952 Toast.LENGTH_LONG).show();
957 @SuppressWarnings("deprecation")
958 void onCopy(final RowBase row) {
961 Log.d(LOG, "Copy, row=" + row);
962 final StringBuilder result = new StringBuilder();
963 result.append(row.getRawText(false));
964 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
965 clipboardManager.setText(result.toString());
966 Log.d(LOG, "Copied: " + result);
970 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
971 if (event.getUnicodeChar() != 0) {
972 if (!searchView.hasFocus()) {
973 setSearchText("" + (char) event.getUnicodeChar(), true);
975 searchView.requestFocus();
978 if (keyCode == KeyEvent.KEYCODE_BACK) {
979 // Log.d(LOG, "Clearing dictionary prefs.");
980 // Pretend that we just autolaunched so that we won't do it again.
981 // DictionaryManagerActivity.lastAutoLaunchMillis =
982 // System.currentTimeMillis();
984 if (keyCode == KeyEvent.KEYCODE_ENTER) {
985 Log.d(LOG, "Trying to hide soft keyboard.");
986 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
987 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
988 InputMethodManager.HIDE_NOT_ALWAYS);
991 return super.onKeyDown(keyCode, event);
994 private void setIndexAndSearchText(int newIndex, String newSearchText) {
995 Log.d(LOG, "Changing index to: " + newIndex);
996 if (newIndex == -1) {
997 Log.e(LOG, "Invalid index.");
1000 if (newIndex != indexIndex) {
1001 indexIndex = newIndex;
1002 index = dictionary.indices.get(indexIndex);
1003 indexAdapter = new IndexAdapter(index);
1004 setListAdapter(indexAdapter);
1005 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1006 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1009 setSearchText(newSearchText, true);
1012 private void setSearchText(final String text, final boolean triggerSearch) {
1013 if (!triggerSearch) {
1014 searchView.setOnQueryTextListener(null);
1016 searchView.setQuery(text, false);
1017 moveCursorToRight();
1018 if (!triggerSearch) {
1019 searchView.setOnQueryTextListener(onQueryTextListener);
1021 onQueryTextListener.onQueryTextChange(text);
1025 // 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(searchView.getQuery(), searchText.getLayout());
1032 // uiHandler.postDelayed(new Runnable() {
1034 // public void run() {
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 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1084 // getListView().requestFocusFromTouch();
1085 getListView().setSelectionFromTop(row, 0);
1086 getListView().setSelected(true);
1089 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1091 final class SearchOperation implements Runnable {
1093 final AtomicBoolean interrupted = new AtomicBoolean(false);
1095 final String searchText;
1097 List<String> searchTokens; // filled in for multiWord.
1101 long searchStartMillis;
1103 Index.IndexEntry searchResult;
1105 List<RowBase> multiWordSearchResult;
1107 boolean done = false;
1109 SearchOperation(final String searchText, final Index index) {
1110 this.searchText = StringUtil.normalizeWhitespace(searchText);
1114 public String toString() {
1115 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1121 searchStartMillis = System.currentTimeMillis();
1122 final String[] searchTokenArray = WHITESPACE.split(searchText);
1123 if (searchTokenArray.length == 1) {
1124 searchResult = index.findInsertionPoint(searchText, interrupted);
1126 searchTokens = Arrays.asList(searchTokenArray);
1127 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens, interrupted);
1130 "searchText=" + searchText + ", searchDuration="
1131 + (System.currentTimeMillis() - searchStartMillis)
1132 + ", interrupted=" + interrupted.get());
1133 if (!interrupted.get()) {
1134 uiHandler.post(new Runnable() {
1137 searchFinished(SearchOperation.this);
1141 Log.d(LOG, "interrupted, skipping searchFinished.");
1143 } catch (Exception e) {
1144 Log.e(LOG, "Failure during search (can happen during Activity close.");
1146 synchronized (this) {
1154 // --------------------------------------------------------------------------
1156 // --------------------------------------------------------------------------
1158 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1159 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1161 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1162 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1164 final class IndexAdapter extends BaseAdapter {
1166 private static final float PADDING_DEFAULT_DP = 8;
1168 private static final float PADDING_LARGE_DP = 16;
1172 final List<RowBase> rows;
1174 final Set<String> toHighlight;
1176 private int mPaddingDefault;
1178 private int mPaddingLarge;
1180 IndexAdapter(final Index index) {
1183 this.toHighlight = null;
1187 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1190 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1194 private void getMetrics() {
1195 // Get the screen's density scale
1196 final float scale = getResources().getDisplayMetrics().density;
1197 // Convert the dps to pixels, based on density scale
1198 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1199 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1203 public int getCount() {
1208 public RowBase getItem(int position) {
1209 return rows.get(position);
1213 public long getItemId(int position) {
1214 return getItem(position).index();
1218 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1219 final TableLayout result;
1220 if (convertView instanceof TableLayout) {
1221 result = (TableLayout) convertView;
1222 result.removeAllViews();
1224 result = new TableLayout(parent.getContext());
1226 final RowBase row = getItem(position);
1227 if (row instanceof PairEntry.Row) {
1228 return getView(position, (PairEntry.Row) row, parent, result);
1229 } else if (row instanceof TokenRow) {
1230 return getView((TokenRow) row, parent, result);
1231 } else if (row instanceof HtmlEntry.Row) {
1232 return getView((HtmlEntry.Row) row, parent, result);
1234 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1238 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1239 final TableLayout result) {
1240 final PairEntry entry = row.getEntry();
1241 final int rowCount = entry.pairs.size();
1243 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1244 layoutParams.weight = 0.5f;
1245 layoutParams.leftMargin = mPaddingLarge;
1247 for (int r = 0; r < rowCount; ++r) {
1248 final TableRow tableRow = new TableRow(result.getContext());
1250 final TextView col1 = new TextView(tableRow.getContext());
1251 final TextView col2 = new TextView(tableRow.getContext());
1253 // Set the columns in the table.
1255 final TextView bullet = new TextView(tableRow.getContext());
1256 bullet.setText(" • ");
1257 tableRow.addView(bullet);
1259 tableRow.addView(col1, layoutParams);
1260 final TextView margin = new TextView(tableRow.getContext());
1261 margin.setText(" ");
1262 tableRow.addView(margin);
1264 final TextView bullet = new TextView(tableRow.getContext());
1265 bullet.setText(" • ");
1266 tableRow.addView(bullet);
1268 tableRow.addView(col2, layoutParams);
1272 // Set what's in the columns.
1274 final Pair pair = entry.pairs.get(r);
1275 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1276 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1278 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1279 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1281 // Bold the token instances in col1.
1282 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1283 .singleton(row.getTokenRow(true).getToken());
1284 final Spannable col1Spannable = (Spannable) col1.getText();
1285 for (final String token : toBold) {
1287 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1288 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1289 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1290 startPos += token.length();
1294 createTokenLinkSpans(col1, col1Spannable, col1Text);
1295 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1297 col1.setTypeface(typeface);
1298 col2.setTypeface(typeface);
1299 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1300 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1301 // col2.setBackgroundResource(theme.otherLangBg);
1303 if (index.swapPairEntries) {
1304 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1305 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1307 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1308 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1311 result.addView(tableRow);
1314 // Because we have a Button inside a ListView row:
1315 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1316 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1317 result.setClickable(true);
1318 result.setFocusable(true);
1319 result.setLongClickable(true);
1320 result.setBackgroundResource(android.R.drawable.menuitem_background);
1321 result.setOnClickListener(new TextView.OnClickListener() {
1323 public void onClick(View v) {
1324 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1331 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1332 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1333 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1334 final Context context = parent.getContext();
1336 final TableRow tableRow = new TableRow(result.getContext());
1337 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1338 : theme.tokenRowOtherBg);
1340 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1342 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1344 result.addView(tableRow);
1346 // Make it so we can long-click on these token rows, too:
1347 final TextView textView = new TextView(context);
1348 textView.setText(text, BufferType.SPANNABLE);
1349 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1350 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1352 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1353 result.setLongClickable(true);
1356 // textView.setTextColor(android.R.color.secondary_text_light);
1357 textView.setTypeface(typeface);
1358 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1360 textView.setTextAppearance(context, theme.tokenRowFg);
1361 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1363 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1367 textView.setLayoutParams(lp);
1368 tableRow.addView(textView);
1370 if (!htmlEntries.isEmpty()) {
1371 final ClickableSpan clickableSpan = new ClickableSpan() {
1373 public void onClick(View widget) {
1376 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1377 result.setClickable(true);
1378 textView.setClickable(true);
1379 textView.setMovementMethod(LinkMovementMethod.getInstance());
1380 textView.setOnClickListener(new OnClickListener() {
1382 public void onClick(View v) {
1383 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1384 //Log.d(LOG, "html=" + html);
1385 startActivityForResult(
1386 HtmlDisplayActivity.getHtmlIntent(String.format(
1387 "<html><head></head><body>%s</body></html>", html),
1388 htmlTextToHighlight, false),
1396 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1397 final IndexEntry indexEntry = row.getIndexEntry();
1398 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1399 indexEntry.htmlEntries, null, parent, result);
1402 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1403 final HtmlEntry htmlEntry = row.getEntry();
1404 final TokenRow tokenRow = row.getTokenRow(true);
1405 return getPossibleLinkToHtmlEntryView(false,
1406 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1407 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1413 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1415 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1416 final String text) {
1417 // Saw from the source code that LinkMovementMethod sets the selection!
1418 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1419 textView.setMovementMethod(LinkMovementMethod.getInstance());
1420 final Matcher matcher = CHAR_DASH.matcher(text);
1421 while (matcher.find()) {
1422 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
1423 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1427 String selectedSpannableText = null;
1429 int selectedSpannableIndex = -1;
1432 public boolean onTouchEvent(MotionEvent event) {
1433 selectedSpannableText = null;
1434 selectedSpannableIndex = -1;
1435 return super.onTouchEvent(event);
1438 private class TextViewLongClickListener implements OnLongClickListener {
1441 private TextViewLongClickListener(final int index) {
1446 public boolean onLongClick(final View v) {
1447 final TextView textView = (TextView) v;
1448 final int start = textView.getSelectionStart();
1449 final int end = textView.getSelectionEnd();
1450 if (start >= 0 && end >= 0) {
1451 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1452 selectedSpannableIndex = index;
1458 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1461 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1464 // --------------------------------------------------------------------------
1466 // --------------------------------------------------------------------------
1468 void onSearchTextChange(final String text) {
1469 if ("thadolina".equals(text)) {
1470 final Dialog dialog = new Dialog(getListView().getContext());
1471 dialog.setContentView(R.layout.thadolina_dialog);
1472 dialog.setTitle("Ti amo, amore mio!");
1473 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1474 imageView.setOnClickListener(new OnClickListener() {
1476 public void onClick(View v) {
1477 final Intent intent = new Intent(Intent.ACTION_VIEW);
1478 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1479 startActivity(intent);
1484 if (dictRaf == null) {
1485 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1488 // if (!searchView.hasFocus()) {
1489 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1492 Log.d(LOG, "onSearchTextChange: " + text);
1493 if (currentSearchOperation != null) {
1494 Log.d(LOG, "Interrupting currentSearchOperation.");
1495 currentSearchOperation.interrupted.set(true);
1497 currentSearchOperation = new SearchOperation(text, index);
1498 searchExecutor.execute(currentSearchOperation);
1501 // --------------------------------------------------------------------------
1502 // Filtered results.
1503 // --------------------------------------------------------------------------
1505 boolean isFiltered() {
1506 return rowsToShow != null;
1509 void setFiltered(final SearchOperation searchOperation) {
1510 if (nextWordMenuItem != null) {
1511 nextWordMenuItem.setEnabled(false);
1512 previousWordMenuItem.setEnabled(false);
1514 rowsToShow = searchOperation.multiWordSearchResult;
1515 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1518 void clearFiltered() {
1519 if (nextWordMenuItem != null) {
1520 nextWordMenuItem.setEnabled(true);
1521 previousWordMenuItem.setEnabled(true);
1523 setListAdapter(new IndexAdapter(index));