1 // Copyright 2011 Google Inc. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 package com.hughes.android.dictionary;
17 import android.annotation.SuppressLint;
18 import android.app.Dialog;
19 import android.content.Context;
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.graphics.Color;
23 import android.graphics.Typeface;
24 import android.net.Uri;
25 import android.os.Bundle;
26 import android.os.Handler;
27 import android.preference.PreferenceManager;
28 import android.speech.tts.TextToSpeech;
29 import android.speech.tts.TextToSpeech.OnInitListener;
30 import android.text.ClipboardManager;
31 import android.text.Editable;
32 import android.text.Selection;
33 import android.text.Spannable;
34 import android.text.TextWatcher;
35 import android.text.method.LinkMovementMethod;
36 import android.text.style.ClickableSpan;
37 import android.text.style.StyleSpan;
38 import android.util.Log;
39 import android.util.TypedValue;
40 import android.view.ContextMenu;
41 import android.view.ContextMenu.ContextMenuInfo;
42 import android.view.KeyEvent;
43 import android.view.LayoutInflater;
44 import android.view.MotionEvent;
45 import android.view.View;
46 import android.view.View.OnClickListener;
47 import android.view.View.OnFocusChangeListener;
48 import android.view.View.OnLongClickListener;
49 import android.view.ViewGroup;
50 import android.view.WindowManager;
51 import android.view.inputmethod.EditorInfo;
52 import android.view.inputmethod.InputMethodManager;
53 import android.widget.AdapterView.AdapterContextMenuInfo;
54 import android.widget.BaseAdapter;
55 import android.widget.Button;
56 import android.widget.EditText;
57 import android.widget.FrameLayout;
58 import android.widget.ImageButton;
59 import android.widget.ImageView;
60 import android.widget.LinearLayout;
61 import android.widget.ListAdapter;
62 import android.widget.ListView;
63 import android.widget.TableLayout;
64 import android.widget.TableRow;
65 import android.widget.TextView;
66 import android.widget.TextView.BufferType;
67 import android.widget.Toast;
69 import com.actionbarsherlock.app.ActionBar;
70 import com.actionbarsherlock.app.SherlockListActivity;
71 import com.actionbarsherlock.view.Menu;
72 import com.actionbarsherlock.view.MenuItem;
73 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
74 import com.actionbarsherlock.widget.SearchView;
75 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
76 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
77 import com.hughes.android.dictionary.engine.Dictionary;
78 import com.hughes.android.dictionary.engine.EntrySource;
79 import com.hughes.android.dictionary.engine.HtmlEntry;
80 import com.hughes.android.dictionary.engine.Index;
81 import com.hughes.android.dictionary.engine.Index.IndexEntry;
82 import com.hughes.android.dictionary.engine.Language;
83 import com.hughes.android.dictionary.engine.Language.LanguageResources;
84 import com.hughes.android.dictionary.engine.PairEntry;
85 import com.hughes.android.dictionary.engine.PairEntry.Pair;
86 import com.hughes.android.dictionary.engine.RowBase;
87 import com.hughes.android.dictionary.engine.TokenRow;
88 import com.hughes.android.dictionary.engine.TransliteratorManager;
89 import com.hughes.android.util.IntentLauncher;
90 import com.hughes.android.util.NonLinkClickableSpan;
91 import com.hughes.util.StringUtil;
94 import java.io.FileWriter;
95 import java.io.IOException;
96 import java.io.PrintWriter;
97 import java.io.RandomAccessFile;
98 import java.text.SimpleDateFormat;
99 import java.util.Arrays;
100 import java.util.Collections;
101 import java.util.Date;
102 import java.util.HashMap;
103 import java.util.LinkedHashSet;
104 import java.util.List;
105 import java.util.Locale;
106 import java.util.Random;
107 import java.util.Set;
108 import java.util.concurrent.Executor;
109 import java.util.concurrent.Executors;
110 import java.util.concurrent.ThreadFactory;
111 import java.util.concurrent.atomic.AtomicBoolean;
112 import java.util.regex.Matcher;
113 import java.util.regex.Pattern;
115 public class DictionaryActivity extends SherlockListActivity {
117 static final String LOG = "QuickDic";
119 DictionaryApplication application;
121 File dictFile = null;
123 RandomAccessFile dictRaf = null;
125 Dictionary dictionary = null;
131 List<RowBase> rowsToShow = null; // if not null, just show these rows.
134 final Handler uiHandler = new Handler();
136 TextToSpeech textToSpeech;
137 volatile boolean ttsReady;
139 int textColorFg = Color.BLACK;
142 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
144 public Thread newThread(Runnable r) {
145 return new Thread(r, "searchExecutor");
149 private SearchOperation currentSearchOperation = null;
151 C.Theme theme = C.Theme.LIGHT;
157 // EditText searchText;
158 SearchView searchView;
159 ImageView searchHintIcon;
161 MenuItem nextWordMenuItem, previousWordMenuItem;
164 private File wordList = null;
166 private boolean saveOnlyFirstSubentry = false;
168 private boolean clickOpensContextMenu = false;
170 // Visible for testing.
171 ListAdapter indexAdapter = null;
173 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
176 * For some languages, loading the transliterators used in this search takes
177 * a long time, so we fire it up on a different thread, and don't invoke it
178 * from the main thread until it's already finished once.
180 private volatile boolean indexPrepFinished = false;
182 public DictionaryActivity() {
185 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
186 final String searchToken) {
187 final Intent intent = new Intent();
188 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
189 DictionaryActivity.class.getName());
190 intent.putExtra(C.DICT_FILE, dictFile.getPath());
191 intent.putExtra(C.INDEX_INDEX, indexIndex);
192 intent.putExtra(C.SEARCH_TOKEN, searchToken);
197 protected void onSaveInstanceState(final Bundle outState) {
198 super.onSaveInstanceState(outState);
199 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
200 outState.putInt(C.INDEX_INDEX, indexIndex);
201 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
205 protected void onRestoreInstanceState(final Bundle outState) {
206 super.onRestoreInstanceState(outState);
207 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
212 public void onCreate(Bundle savedInstanceState) {
213 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
214 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
217 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
219 Log.d(LOG, "onCreate:" + this);
220 super.onCreate(savedInstanceState);
222 application = (DictionaryApplication) getApplication();
223 theme = application.getSelectedTheme();
224 textColorFg = getResources().getColor(theme.tokenRowFgColor);
226 final Intent intent = getIntent();
227 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
230 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
232 public void onInit(int status) {
239 final String name = application.getDictionaryName(dictFile.getName());
240 this.setTitle("QuickDic: " + name);
241 dictRaf = new RandomAccessFile(dictFile, "r");
242 dictionary = new Dictionary(dictRaf);
243 } catch (Exception e) {
244 Log.e(LOG, "Unable to load dictionary.", e);
245 if (dictRaf != null) {
248 } catch (IOException e1) {
249 Log.e(LOG, "Unable to close dictRaf.", e1);
253 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
254 Toast.LENGTH_LONG).show();
255 startActivity(DictionaryManagerActivity.getLaunchIntent());
259 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
260 if (savedInstanceState != null) {
261 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
263 indexIndex %= dictionary.indices.size();
264 Log.d(LOG, "Loading index " + indexIndex);
265 index = dictionary.indices.get(indexIndex);
266 setListAdapter(new IndexAdapter(index));
268 // Pre-load the collators.
269 new Thread(new Runnable() {
271 final long startMillis = System.currentTimeMillis();
273 TransliteratorManager.init(new TransliteratorManager.Callback() {
275 public void onTransliteratorReady() {
276 uiHandler.post(new Runnable() {
279 onSearchTextChange(searchView.getQuery().toString());
285 for (final Index index : dictionary.indices) {
286 final String searchToken = index.sortedIndexEntries.get(0).token;
287 final IndexEntry entry = index.findExact(searchToken);
288 if (!searchToken.equals(entry.token)) {
289 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
292 indexPrepFinished = true;
293 } catch (Exception e) {
295 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
297 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
301 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
302 if ("SYSTEM".equals(fontName)) {
303 typeface = Typeface.DEFAULT;
306 typeface = Typeface.createFromAsset(getAssets(), fontName);
307 } catch (Exception e) {
308 Log.w(LOG, "Exception trying to use typeface, using default.", e);
309 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
310 Toast.LENGTH_LONG).show();
313 // if (!"SYSTEM".equals(fontName)) {
314 // throw new RuntimeException("Test force using system font: " +
317 if (typeface == null) {
318 Log.w(LOG, "Unable to create typeface, using default.");
319 typeface = Typeface.DEFAULT;
321 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
323 fontSizeSp = Integer.parseInt(fontSize.trim());
324 } catch (NumberFormatException e) {
328 setContentView(R.layout.dictionary_activity);
329 // searchText = (EditText) findViewById(R.id.SearchText);
330 // searchText.requestFocus();
331 // searchText.addTextChangedListener(searchTextWatcher);
332 // searchText.setOnFocusChangeListener(new OnFocusChangeListener() {
334 // public void onFocusChange(View v, boolean hasFocus) {
335 // Log.d(LOG, "searchText onFocusChange hasFocus=" + hasFocus);
341 // final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
342 // clearSearchTextButton.setOnClickListener(new OnClickListener() {
343 // public void onClick(View v) {
344 // onClearSearchTextButton();
347 // clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
348 // .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
351 // getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
353 // public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
355 // if (!searchText.hasFocus()) {
356 // if (!isFiltered()) {
357 // final RowBase row = (RowBase) getListAdapter().getItem(position);
358 // Log.d(LOG, "onItemSelected: " + row.index());
359 // final TokenRow tokenRow = row.getTokenRow(true);
360 // searchText.setText(tokenRow.getToken());
366 // public void onNothingSelected(AdapterView<?> arg0) {
371 registerForContextMenu(getListView());
374 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
375 getString(R.string.wordListFileDefault)));
376 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
378 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
380 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
382 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
384 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
386 ActionBar actionBar = getSupportActionBar();
387 actionBar.setDisplayShowTitleEnabled(false);
389 //Inflate the custom view
390 // View customNav = LayoutInflater.from(this).inflate(R.layout.dictionary_search_view, null);
391 searchView = new SearchView(getSupportActionBar().getThemedContext());
392 searchView.setIconifiedByDefault(false);
393 // searchView.setIconified(false); // puts the magifying glass in the wrong place.
394 searchView.setQueryHint(getString(R.string.searchText));
395 searchView.setSubmitButtonEnabled(false);
396 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics());
397 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width, FrameLayout.LayoutParams.WRAP_CONTENT);
398 searchView.setLayoutParams(lp);
399 // searchView.setMaxWidth(200);
400 searchView.setImeOptions(
401 EditorInfo.IME_ACTION_SEARCH |
402 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
403 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
404 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API 11
405 EditorInfo.IME_MASK_ACTION |
406 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
407 searchView.setOnQueryTextListener(new OnQueryTextListener() {
409 public boolean onQueryTextSubmit(String query) {
410 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
415 public boolean onQueryTextChange(String newText) {
416 // if (searchView.hasFocus()) {
417 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
418 // If they were typing to cause the change, update the UI.
419 onSearchTextChange(searchView.getQuery().toString());
425 // Set the search text from the intent, then the saved state.
426 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
427 if (savedInstanceState != null) {
428 text = savedInstanceState.getString(C.SEARCH_TOKEN);
433 setSearchText(text, true);
434 Log.d(LOG, "Trying to restore searchText=" + text);
436 setDictionaryPrefs(this, dictFile, indexIndex, searchView.getQuery().toString());
438 searchHintIcon = (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
439 searchHintIcon.setOnClickListener(new OnClickListener() {
441 public void onClick(View arg0) {
445 searchHintIcon.setOnLongClickListener(new OnLongClickListener() {
447 public boolean onLongClick(View v) {
448 onLanguageButtonLongClick(v.getContext());
455 // ImageView searchHintIcon = (ImageView) searchView.findViewById(searchView.getContext().getResources().
456 // getIdentifier("android:id/search_mag_icon", null, null));
457 // searchHintIcon.setImageResource(android.R.color.transparent);
458 // searchView.setOnQueryTextListener(this);
459 // menu.add("Search")
460 //// .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.abs__ic_search)
461 // .setActionView(searchView)
462 // .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
463 actionBar.setCustomView(searchView);
464 actionBar.setDisplayShowCustomEnabled(true);
470 protected void onResume() {
471 Log.d(LOG, "onResume");
473 if (SettingsActivity.settingsMightHaveChanged) {
474 SettingsActivity.settingsMightHaveChanged = false;
476 startActivity(getIntent());
482 protected void onPause() {
487 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
488 super.onActivityResult(requestCode, resultCode, result);
489 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
490 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
491 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
495 private static void setDictionaryPrefs(final Context context, final File dictFile,
496 final int indexIndex, final String searchToken) {
497 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
499 prefs.putString(C.DICT_FILE, dictFile.getPath());
500 prefs.putInt(C.INDEX_INDEX, indexIndex);
501 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
506 protected void onDestroy() {
508 if (dictRaf == null) {
512 final SearchOperation searchOperation = currentSearchOperation;
513 currentSearchOperation = null;
515 // Before we close the RAF, we have to wind the current search down.
516 if (searchOperation != null) {
517 Log.d(LOG, "Interrupting search to shut down.");
518 currentSearchOperation = null;
519 searchOperation.interrupted.set(true);
523 Log.d(LOG, "Closing RAF.");
525 } catch (IOException e) {
526 Log.e(LOG, "Failed to close dictionary", e);
531 // --------------------------------------------------------------------------
533 // --------------------------------------------------------------------------
535 private void onClearSearchTextButton() {
536 setSearchText("", true);
540 private void showKeyboard() {
541 // searchText.postDelayed(new Runnable() {
543 // public void run() {
544 // Log.d(LOG, "Trying to show soft keyboard.");
545 // final boolean searchTextHadFocus = searchText.hasFocus();
546 // searchText.requestFocus();
547 // final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
548 // manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
549 // if (!searchTextHadFocus) {
550 // defocusSearchText();
555 void updateLangButton() {
556 final LanguageResources languageResources =
557 Language.isoCodeToResources.get(index.shortName);
558 if (languageResources != null && languageResources.flagId != 0) {
559 searchHintIcon.setImageResource(languageResources.flagId);
561 if (index == dictionary.indices.get(0)) {
562 searchHintIcon.setImageResource(android.R.drawable.ic_media_next);
564 searchHintIcon.setImageResource(android.R.drawable.ic_media_previous);
570 private void updateTTSLanuage() {
571 if (!ttsReady || index == null || textToSpeech == null) {
572 Log.d(LOG, "Can't updateTTSLanguage.");
575 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
576 Log.d(LOG, "Setting TTS locale to: " + locale);
577 final int ttsResult = textToSpeech.setLanguage(locale);
578 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
579 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
580 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
584 void onLanguageButton() {
585 if (currentSearchOperation != null) {
586 currentSearchOperation.interrupted.set(true);
587 currentSearchOperation = null;
589 changeIndexAndResearch((indexIndex + 1) % dictionary.indices.size());
592 void onLanguageButtonLongClick(final Context context) {
593 final Dialog dialog = new Dialog(context);
594 dialog.setContentView(R.layout.select_dictionary_dialog);
595 dialog.setTitle(R.string.selectDictionary);
597 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
600 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
602 // final LinearLayout.LayoutParams layoutParams = new
603 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
604 // ViewGroup.LayoutParams.WRAP_CONTENT);
605 // layoutParams.width = 0;
606 // layoutParams.weight = 1.0f;
608 final Button button = new Button(listView.getContext());
609 final String name = getString(R.string.dictionaryManager);
610 button.setText(name);
611 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
612 DictionaryManagerActivity.getLaunchIntent()) {
614 protected void onGo() {
616 DictionaryActivity.this.finish();
619 button.setOnClickListener(intentLauncher);
620 // button.setLayoutParams(layoutParams);
621 listView.addHeaderView(button);
622 // listView.setHeaderDividersEnabled(true);
624 listView.setAdapter(new BaseAdapter() {
626 public View getView(int position, View convertView, ViewGroup parent) {
627 final DictionaryInfo dictionaryInfo = getItem(position);
629 final LinearLayout result = new LinearLayout(parent.getContext());
631 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
633 final TextView dash = new TextView(parent.getContext());
635 result.addView(dash);
638 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
639 final Button button = new Button(parent.getContext());
640 button.setText(indexInfo.shortName);
641 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
643 application.getPath(dictionaryInfo.uncompressedFilename),
644 i, searchView.getQuery().toString())) {
646 protected void onGo() {
648 DictionaryActivity.this.finish();
651 button.setOnClickListener(intentLauncher);
652 result.addView(button);
656 final TextView nameView = new TextView(parent.getContext());
657 final String name = application
658 .getDictionaryName(dictionaryInfo.uncompressedFilename);
659 nameView.setText(name);
660 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
661 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
662 layoutParams.width = 0;
663 layoutParams.weight = 1.0f;
664 nameView.setLayoutParams(layoutParams);
665 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();
689 private void changeIndexAndResearch(int newIndex) {
690 Log.d(LOG, "Changing index to: " + newIndex);
691 if (newIndex == -1) {
692 Log.e(LOG, "Invalid index.");
695 indexIndex = newIndex;
696 index = dictionary.indices.get(indexIndex);
697 indexAdapter = new IndexAdapter(index);
698 Log.d(LOG, "changingIndex, newLang=" + index.longName);
699 setDictionaryPrefs(this, dictFile, indexIndex, searchView.getQuery().toString());
700 setListAdapter(indexAdapter);
702 setSearchText(searchView.getQuery().toString(), true);
705 void onUpDownButton(final boolean up) {
709 final int firstVisibleRow = getListView().getFirstVisiblePosition();
710 final RowBase row = index.rows.get(firstVisibleRow);
711 final TokenRow tokenRow = row.getTokenRow(true);
712 final int destIndexEntry;
714 if (row != tokenRow) {
715 destIndexEntry = tokenRow.referenceIndex;
717 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
721 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
723 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
724 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
725 setSearchText(dest.token, false);
726 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
730 // --------------------------------------------------------------------------
732 // --------------------------------------------------------------------------
734 final Random random = new Random();
737 public boolean onCreateOptionsMenu(final Menu menu) {
738 //Create the search view
739 // SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
740 // searchView.setIconifiedByDefault(false);
741 // searchView.setQueryHint(getString(R.string.searchText));
742 // searchView.setSubmitButtonEnabled(false);
743 // searchView.setMaxWidth(200);
744 // searchView.setImeOptions(
745 // EditorInfo.IME_ACTION_SEARCH |
746 // EditorInfo.IME_FLAG_NO_EXTRACT_UI |
747 // EditorInfo.IME_FLAG_NO_ENTER_ACTION |
748 //// EditorInfo.IME_FLAG_NO_FULLSCREEN |
749 // EditorInfo.IME_MASK_ACTION |
750 // EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
751 //// searchView.setOnQueryTextListener(this);
752 // menu.add("Search")
753 //// .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.abs__ic_search)
754 // .setActionView(searchView)
755 // .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
757 // final ImageView searchHintIcon =
758 // (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
759 // searchHintIcon.setImageResource(android.R.id.empty);
760 // searchHintIcon.setAdjustViewBounds(true);
761 // searchHintIcon.setMaxWidth(1);
762 // searchHintIcon.setMaxHeight(1);
763 // searchHintIcon.setVisibility(ImageView.GONE);
764 // searchView.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {
766 // public void onFocusChange(View arg0, boolean arg1) {
767 // searchHintIcon.setVisibility(ImageView.GONE);
768 // searchHintIcon.refreshDrawableState();
773 if (PreferenceManager.getDefaultSharedPreferences(this)
774 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
776 nextWordMenuItem = menu.add(getString(R.string.nextWord))
777 .setIcon(R.drawable.arrow_down_float);
778 nextWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
779 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
781 public boolean onMenuItemClick(MenuItem item) {
782 onUpDownButton(false);
788 previousWordMenuItem = menu.add(getString(R.string.previousWord))
789 .setIcon(R.drawable.arrow_up_float);
790 previousWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
791 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
793 public boolean onMenuItemClick(MenuItem item) {
794 onUpDownButton(true);
800 application.onCreateGlobalOptionsMenu(this, menu);
803 // final MenuItem randomWord = menu.add(getString(R.string.randomWord));
804 // randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
805 // public boolean onMenuItemClick(final MenuItem menuItem) {
806 // final String word = index.sortedIndexEntries.get(random
807 // .nextInt(index.sortedIndexEntries.size())).token;
808 // setSearchText(word, true);
815 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
816 dictionaryList.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
817 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
818 public boolean onMenuItemClick(final MenuItem menuItem) {
819 startActivity(DictionaryManagerActivity.getLaunchIntent());
827 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
828 aboutDictionary.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
829 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
830 public boolean onMenuItemClick(final MenuItem menuItem) {
831 final Context context = getListView().getContext();
832 final Dialog dialog = new Dialog(context);
833 dialog.setContentView(R.layout.about_dictionary_dialog);
834 final TextView textView = (TextView) dialog.findViewById(R.id.text);
836 final String name = application.getDictionaryName(dictFile.getName());
837 dialog.setTitle(name);
839 final StringBuilder builder = new StringBuilder();
840 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
841 dictionaryInfo.uncompressedBytes = dictFile.length();
842 if (dictionaryInfo != null) {
843 builder.append(dictionaryInfo.dictInfo).append("\n\n");
844 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
847 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
850 getString(R.string.dictionaryCreationTime,
851 dictionaryInfo.creationMillis)).append("\n");
852 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
853 builder.append("\n");
854 builder.append(getString(R.string.indexName, indexInfo.shortName))
857 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
860 builder.append("\n");
861 builder.append(getString(R.string.sources)).append("\n");
862 for (final EntrySource source : dictionary.sources) {
864 getString(R.string.sourceInfo, source.getName(),
865 source.getNumEntries())).append("\n");
869 // builder.append(getString(R.string.invalidDictionary));
871 textView.setText(builder.toString());
874 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
875 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
876 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
877 dialog.getWindow().setAttributes(layoutParams);
886 // --------------------------------------------------------------------------
887 // Context Menu + clicks
888 // --------------------------------------------------------------------------
891 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
892 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
893 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
895 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
896 wordList.getName()));
897 addToWordlist.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
898 public boolean onMenuItemClick(android.view.MenuItem item) {
899 onAppendToWordList(row);
904 final android.view.MenuItem share = menu.add("Share");
905 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
906 public boolean onMenuItemClick(android.view.MenuItem item) {
907 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
908 shareIntent.setType("text/plain");
909 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true).getToken());
910 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, row.getRawText(saveOnlyFirstSubentry));
911 startActivity(shareIntent);
916 final android.view.MenuItem copy = menu.add(android.R.string.copy);
917 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
918 public boolean onMenuItemClick(android.view.MenuItem item) {
924 if (selectedSpannableText != null) {
925 final String selectedText = selectedSpannableText;
926 final android.view.MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
927 selectedSpannableText));
928 searchForSelection.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
929 public boolean onMenuItemClick(android.view.MenuItem item) {
930 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
936 if (row instanceof TokenRow && ttsReady) {
937 final android.view.MenuItem speak = menu.add(R.string.speak);
938 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
940 public boolean onMenuItemClick(android.view.MenuItem item) {
941 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
942 new HashMap<String, String>());
949 private void jumpToTextFromHyperLink(final String selectedText, final int defaultIndexToUse) {
951 for (int i = 0; i < dictionary.indices.size(); ++i) {
952 final Index index = dictionary.indices.get(i);
953 if (indexPrepFinished) {
954 System.out.println("Doing index lookup: on " + selectedText);
955 final IndexEntry indexEntry = index.findExact(selectedText);
956 if (indexEntry != null) {
957 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
959 if (tokenRow != null && tokenRow.hasMainEntry) {
965 Log.w(LOG, "Skipping findExact on index " + index.shortName);
968 if (indexToUse == -1) {
969 indexToUse = defaultIndexToUse;
971 final boolean changeIndex = indexIndex != indexToUse;
973 setSearchText(selectedText, false);
974 changeIndexAndResearch(indexToUse);
976 setSearchText(selectedText, true);
981 protected void onListItemClick(ListView l, View v, int row, long id) {
983 if (clickOpensContextMenu && dictRaf != null) {
988 @SuppressLint("SimpleDateFormat")
989 void onAppendToWordList(final RowBase row) {
992 final StringBuilder rawText = new StringBuilder();
993 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
994 rawText.append(index.longName).append("\t");
995 rawText.append(row.getTokenRow(true).getToken()).append("\t");
996 rawText.append(row.getRawText(saveOnlyFirstSubentry));
997 Log.d(LOG, "Writing : " + rawText);
1000 wordList.getParentFile().mkdirs();
1001 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1002 out.println(rawText.toString());
1004 } catch (IOException e) {
1005 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1006 Toast.makeText(this,
1007 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1008 Toast.LENGTH_LONG).show();
1014 * Called when user clicks outside of search text, so that they can start
1015 * typing again immediately.
1017 void defocusSearchText() {
1018 // Log.d(LOG, "defocusSearchText");
1019 // Request focus so that if we start typing again, it clears the text
1021 getListView().requestFocus();
1023 // Visual indication that a new keystroke will clear the search text.
1024 // Doesn't seem to work unless earchText has focus.
1025 // searchText.selectAll();
1028 @SuppressWarnings("deprecation")
1029 void onCopy(final RowBase row) {
1030 defocusSearchText();
1032 Log.d(LOG, "Copy, row=" + row);
1033 final StringBuilder result = new StringBuilder();
1034 result.append(row.getRawText(false));
1035 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1036 clipboardManager.setText(result.toString());
1037 Log.d(LOG, "Copied: " + result);
1041 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1042 if (event.getUnicodeChar() != 0) {
1043 if (!searchView.hasFocus()) {
1044 setSearchText("" + (char) event.getUnicodeChar(), true);
1048 if (keyCode == KeyEvent.KEYCODE_BACK) {
1049 // Log.d(LOG, "Clearing dictionary prefs.");
1050 // Pretend that we just autolaunched so that we won't do it again.
1051 // DictionaryManagerActivity.lastAutoLaunchMillis =
1052 // System.currentTimeMillis();
1054 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1055 Log.d(LOG, "Trying to hide soft keyboard.");
1056 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1057 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
1058 InputMethodManager.HIDE_NOT_ALWAYS);
1061 return super.onKeyDown(keyCode, event);
1064 private void setSearchText(final String text, final boolean triggerSearch) {
1065 if (!triggerSearch) {
1066 getListView().requestFocus();
1068 searchView.setQuery(text, false);
1069 searchView.requestFocus();
1070 moveCursorToRight();
1071 if (triggerSearch) {
1072 onSearchTextChange(text);
1076 // private long cursorDelayMillis = 100;
1078 private void moveCursorToRight() {
1079 // if (searchText.getLayout() != null) {
1080 // cursorDelayMillis = 100;
1081 // // Surprising, but this can crash when you rotate...
1082 // Selection.moveToRightEdge(searchView.getQuery(), searchText.getLayout());
1084 // uiHandler.postDelayed(new Runnable() {
1086 // public void run() {
1087 // moveCursorToRight();
1089 // }, cursorDelayMillis);
1090 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1094 // --------------------------------------------------------------------------
1096 // --------------------------------------------------------------------------
1098 private void searchFinished(final SearchOperation searchOperation) {
1099 if (searchOperation.interrupted.get()) {
1100 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1103 if (searchOperation != this.currentSearchOperation) {
1104 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1108 final Index.IndexEntry searchResult = searchOperation.searchResult;
1109 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1111 currentSearchOperation = null;
1112 uiHandler.postDelayed(new Runnable() {
1115 if (currentSearchOperation == null) {
1116 if (searchResult != null) {
1120 jumpToRow(searchResult.startRow);
1121 } else if (searchOperation.multiWordSearchResult != null) {
1122 // Multi-row search....
1123 setFiltered(searchOperation);
1125 throw new IllegalStateException("This should never happen.");
1128 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1134 private final void jumpToRow(final int row) {
1135 final boolean refocusSearchText = searchView.hasFocus();
1136 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + refocusSearchText);
1137 getListView().requestFocusFromTouch();
1138 getListView().setSelectionFromTop(row, 0);
1139 getListView().setSelected(true);
1140 if (refocusSearchText) {
1141 searchView.requestFocus();
1143 //Log.d(LOG, "getSelectedItemPosition():" + getSelectedItemPosition());
1146 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1148 final class SearchOperation implements Runnable {
1150 final AtomicBoolean interrupted = new AtomicBoolean(false);
1152 final String searchText;
1154 List<String> searchTokens; // filled in for multiWord.
1158 long searchStartMillis;
1160 Index.IndexEntry searchResult;
1162 List<RowBase> multiWordSearchResult;
1164 boolean done = false;
1166 SearchOperation(final String searchText, final Index index) {
1167 this.searchText = StringUtil.normalizeWhitespace(searchText);
1171 public String toString() {
1172 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1178 searchStartMillis = System.currentTimeMillis();
1179 final String[] searchTokenArray = WHITESPACE.split(searchText);
1180 if (searchTokenArray.length == 1) {
1181 searchResult = index.findInsertionPoint(searchText, interrupted);
1183 searchTokens = Arrays.asList(searchTokenArray);
1184 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens, interrupted);
1187 "searchText=" + searchText + ", searchDuration="
1188 + (System.currentTimeMillis() - searchStartMillis)
1189 + ", interrupted=" + interrupted.get());
1190 if (!interrupted.get()) {
1191 uiHandler.post(new Runnable() {
1194 searchFinished(SearchOperation.this);
1198 Log.d(LOG, "interrupted, skipping searchFinished.");
1200 } catch (Exception e) {
1201 Log.e(LOG, "Failure during search (can happen during Activity close.");
1203 synchronized (this) {
1211 // --------------------------------------------------------------------------
1213 // --------------------------------------------------------------------------
1215 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1216 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1218 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1219 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1221 final class IndexAdapter extends BaseAdapter {
1223 private static final float PADDING_DEFAULT_DP = 8;
1225 private static final float PADDING_LARGE_DP = 16;
1229 final List<RowBase> rows;
1231 final Set<String> toHighlight;
1233 private int mPaddingDefault;
1235 private int mPaddingLarge;
1237 IndexAdapter(final Index index) {
1240 this.toHighlight = null;
1244 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1247 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1251 private void getMetrics() {
1252 // Get the screen's density scale
1253 final float scale = getResources().getDisplayMetrics().density;
1254 // Convert the dps to pixels, based on density scale
1255 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1256 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1260 public int getCount() {
1265 public RowBase getItem(int position) {
1266 return rows.get(position);
1270 public long getItemId(int position) {
1271 return getItem(position).index();
1275 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1276 final TableLayout result;
1277 if (convertView instanceof TableLayout) {
1278 result = (TableLayout) convertView;
1279 result.removeAllViews();
1281 result = new TableLayout(parent.getContext());
1283 final RowBase row = getItem(position);
1284 if (row instanceof PairEntry.Row) {
1285 return getView(position, (PairEntry.Row) row, parent, result);
1286 } else if (row instanceof TokenRow) {
1287 return getView((TokenRow) row, parent, result);
1288 } else if (row instanceof HtmlEntry.Row) {
1289 return getView((HtmlEntry.Row) row, parent, result);
1291 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1295 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1296 final TableLayout result) {
1297 final PairEntry entry = row.getEntry();
1298 final int rowCount = entry.pairs.size();
1300 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1301 layoutParams.weight = 0.5f;
1302 layoutParams.leftMargin = mPaddingLarge;
1304 for (int r = 0; r < rowCount; ++r) {
1305 final TableRow tableRow = new TableRow(result.getContext());
1307 final TextView col1 = new TextView(tableRow.getContext());
1308 final TextView col2 = new TextView(tableRow.getContext());
1310 // Set the columns in the table.
1312 final TextView bullet = new TextView(tableRow.getContext());
1313 bullet.setText(" • ");
1314 tableRow.addView(bullet);
1316 tableRow.addView(col1, layoutParams);
1317 final TextView margin = new TextView(tableRow.getContext());
1318 margin.setText(" ");
1319 tableRow.addView(margin);
1321 final TextView bullet = new TextView(tableRow.getContext());
1322 bullet.setText(" • ");
1323 tableRow.addView(bullet);
1325 tableRow.addView(col2, layoutParams);
1329 // Set what's in the columns.
1331 final Pair pair = entry.pairs.get(r);
1332 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1333 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1335 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1336 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1338 // Bold the token instances in col1.
1339 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1340 .singleton(row.getTokenRow(true).getToken());
1341 final Spannable col1Spannable = (Spannable) col1.getText();
1342 for (final String token : toBold) {
1344 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1345 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1346 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1347 startPos += token.length();
1351 createTokenLinkSpans(col1, col1Spannable, col1Text);
1352 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1354 col1.setTypeface(typeface);
1355 col2.setTypeface(typeface);
1356 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1357 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1358 // col2.setBackgroundResource(theme.otherLangBg);
1360 if (index.swapPairEntries) {
1361 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1362 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1364 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1365 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1368 result.addView(tableRow);
1371 // Because we have a Button inside a ListView row:
1372 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1373 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1374 result.setClickable(true);
1375 result.setFocusable(true);
1376 result.setLongClickable(true);
1377 result.setBackgroundResource(android.R.drawable.menuitem_background);
1378 result.setOnClickListener(new TextView.OnClickListener() {
1380 public void onClick(View v) {
1381 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1388 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1389 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1390 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1391 final Context context = parent.getContext();
1393 final TableRow tableRow = new TableRow(result.getContext());
1394 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1395 : theme.tokenRowOtherBg);
1397 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1399 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1401 result.addView(tableRow);
1403 // Make it so we can long-click on these token rows, too:
1404 final TextView textView = new TextView(context);
1405 textView.setText(text, BufferType.SPANNABLE);
1406 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1407 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1409 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1410 result.setLongClickable(true);
1413 // textView.setTextColor(android.R.color.secondary_text_light);
1414 textView.setTypeface(typeface);
1415 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1417 textView.setTextAppearance(context, theme.tokenRowFg);
1418 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1420 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1424 textView.setLayoutParams(lp);
1425 tableRow.addView(textView);
1427 if (!htmlEntries.isEmpty()) {
1428 final ClickableSpan clickableSpan = new ClickableSpan() {
1430 public void onClick(View widget) {
1433 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1434 result.setClickable(true);
1435 textView.setClickable(true);
1436 textView.setMovementMethod(LinkMovementMethod.getInstance());
1437 textView.setOnClickListener(new OnClickListener() {
1439 public void onClick(View v) {
1440 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1441 //Log.d(LOG, "html=" + html);
1442 startActivityForResult(
1443 HtmlDisplayActivity.getHtmlIntent(String.format(
1444 "<html><head></head><body>%s</body></html>", html),
1445 htmlTextToHighlight, false),
1453 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1454 final IndexEntry indexEntry = row.getIndexEntry();
1455 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1456 indexEntry.htmlEntries, null, parent, result);
1459 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1460 final HtmlEntry htmlEntry = row.getEntry();
1461 final TokenRow tokenRow = row.getTokenRow(true);
1462 return getPossibleLinkToHtmlEntryView(false,
1463 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1464 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1470 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1472 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1473 final String text) {
1474 // Saw from the source code that LinkMovementMethod sets the selection!
1475 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1476 textView.setMovementMethod(LinkMovementMethod.getInstance());
1477 final Matcher matcher = CHAR_DASH.matcher(text);
1478 while (matcher.find()) {
1479 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
1480 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1484 String selectedSpannableText = null;
1486 int selectedSpannableIndex = -1;
1489 public boolean onTouchEvent(MotionEvent event) {
1490 selectedSpannableText = null;
1491 selectedSpannableIndex = -1;
1492 return super.onTouchEvent(event);
1495 private class TextViewLongClickListener implements OnLongClickListener {
1498 private TextViewLongClickListener(final int index) {
1503 public boolean onLongClick(final View v) {
1504 final TextView textView = (TextView) v;
1505 final int start = textView.getSelectionStart();
1506 final int end = textView.getSelectionEnd();
1507 if (start >= 0 && end >= 0) {
1508 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1509 selectedSpannableIndex = index;
1515 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1518 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1521 // --------------------------------------------------------------------------
1523 // --------------------------------------------------------------------------
1525 void onSearchTextChange(final String text) {
1526 if ("thadolina".equals(text)) {
1527 final Dialog dialog = new Dialog(getListView().getContext());
1528 dialog.setContentView(R.layout.thadolina_dialog);
1529 dialog.setTitle("Ti amo, amore mio!");
1530 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1531 imageView.setOnClickListener(new OnClickListener() {
1533 public void onClick(View v) {
1534 final Intent intent = new Intent(Intent.ACTION_VIEW);
1535 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1536 startActivity(intent);
1541 if (dictRaf == null) {
1542 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1545 if (!searchView.hasFocus()) {
1546 Log.d(LOG, "searchText changed without focus, doing nothing.");
1549 Log.d(LOG, "onSearchTextChange: " + text);
1550 if (currentSearchOperation != null) {
1551 Log.d(LOG, "Interrupting currentSearchOperation.");
1552 currentSearchOperation.interrupted.set(true);
1554 currentSearchOperation = new SearchOperation(text, index);
1555 searchExecutor.execute(currentSearchOperation);
1558 private class SearchTextWatcher implements TextWatcher {
1559 public void afterTextChanged(final Editable searchTextEditable) {
1560 if (searchView.hasFocus()) {
1561 Log.d(LOG, "SearchTextWatcher: Search text changed with focus: " + searchView.getQuery());
1562 // If they were typing to cause the change, update the UI.
1563 onSearchTextChange(searchView.getQuery().toString());
1567 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1570 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1574 // --------------------------------------------------------------------------
1575 // Filtered results.
1576 // --------------------------------------------------------------------------
1578 boolean isFiltered() {
1579 return rowsToShow != null;
1582 void setFiltered(final SearchOperation searchOperation) {
1583 if (nextWordMenuItem != null) {
1584 nextWordMenuItem.setEnabled(false);
1585 previousWordMenuItem.setEnabled(false);
1587 rowsToShow = searchOperation.multiWordSearchResult;
1588 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1591 void clearFiltered() {
1592 if (nextWordMenuItem != null) {
1593 nextWordMenuItem.setEnabled(true);
1594 previousWordMenuItem.setEnabled(true);
1596 setListAdapter(new IndexAdapter(index));