1 // Copyright 2011 Google Inc. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 package com.hughes.android.dictionary;
17 import android.annotation.SuppressLint;
18 import android.app.Dialog;
19 import android.content.Context;
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.graphics.Color;
23 import android.graphics.Typeface;
24 import android.net.Uri;
25 import android.os.Bundle;
26 import android.os.Handler;
27 import android.preference.PreferenceManager;
28 import android.speech.tts.TextToSpeech;
29 import android.speech.tts.TextToSpeech.OnInitListener;
30 import android.text.ClipboardManager;
31 import android.text.Editable;
32 import android.text.Selection;
33 import android.text.Spannable;
34 import android.text.TextWatcher;
35 import android.text.method.LinkMovementMethod;
36 import android.text.style.ClickableSpan;
37 import android.text.style.StyleSpan;
38 import android.util.Log;
39 import android.util.TypedValue;
40 import android.view.ContextMenu;
41 import android.view.ContextMenu.ContextMenuInfo;
42 import android.view.KeyEvent;
43 import android.view.LayoutInflater;
44 import android.view.MotionEvent;
45 import android.view.View;
46 import android.view.View.OnClickListener;
47 import android.view.View.OnFocusChangeListener;
48 import android.view.View.OnLongClickListener;
49 import android.view.ViewGroup;
50 import android.view.WindowManager;
51 import android.view.inputmethod.EditorInfo;
52 import android.view.inputmethod.InputMethodManager;
53 import android.widget.AdapterView.AdapterContextMenuInfo;
54 import android.widget.BaseAdapter;
55 import android.widget.Button;
56 import android.widget.EditText;
57 import android.widget.ImageButton;
58 import android.widget.ImageView;
59 import android.widget.LinearLayout;
60 import android.widget.ListAdapter;
61 import android.widget.ListView;
62 import android.widget.TableLayout;
63 import android.widget.TableRow;
64 import android.widget.TextView;
65 import android.widget.TextView.BufferType;
66 import android.widget.Toast;
68 import com.actionbarsherlock.app.ActionBar;
69 import com.actionbarsherlock.app.SherlockListActivity;
70 import com.actionbarsherlock.view.Menu;
71 import com.actionbarsherlock.view.MenuItem;
72 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
73 import com.actionbarsherlock.widget.SearchView;
74 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
75 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
76 import com.hughes.android.dictionary.engine.Dictionary;
77 import com.hughes.android.dictionary.engine.EntrySource;
78 import com.hughes.android.dictionary.engine.HtmlEntry;
79 import com.hughes.android.dictionary.engine.Index;
80 import com.hughes.android.dictionary.engine.Index.IndexEntry;
81 import com.hughes.android.dictionary.engine.Language;
82 import com.hughes.android.dictionary.engine.Language.LanguageResources;
83 import com.hughes.android.dictionary.engine.PairEntry;
84 import com.hughes.android.dictionary.engine.PairEntry.Pair;
85 import com.hughes.android.dictionary.engine.RowBase;
86 import com.hughes.android.dictionary.engine.TokenRow;
87 import com.hughes.android.dictionary.engine.TransliteratorManager;
88 import com.hughes.android.util.IntentLauncher;
89 import com.hughes.android.util.NonLinkClickableSpan;
90 import com.hughes.util.StringUtil;
93 import java.io.FileWriter;
94 import java.io.IOException;
95 import java.io.PrintWriter;
96 import java.io.RandomAccessFile;
97 import java.text.SimpleDateFormat;
98 import java.util.Arrays;
99 import java.util.Collections;
100 import java.util.Date;
101 import java.util.HashMap;
102 import java.util.LinkedHashSet;
103 import java.util.List;
104 import java.util.Locale;
105 import java.util.Random;
106 import java.util.Set;
107 import java.util.concurrent.Executor;
108 import java.util.concurrent.Executors;
109 import java.util.concurrent.ThreadFactory;
110 import java.util.concurrent.atomic.AtomicBoolean;
111 import java.util.regex.Matcher;
112 import java.util.regex.Pattern;
114 public class DictionaryActivity extends SherlockListActivity {
116 static final String LOG = "QuickDic";
118 DictionaryApplication application;
120 File dictFile = null;
122 RandomAccessFile dictRaf = null;
124 Dictionary dictionary = null;
130 List<RowBase> rowsToShow = null; // if not null, just show these rows.
133 final Handler uiHandler = new Handler();
135 TextToSpeech textToSpeech;
136 volatile boolean ttsReady;
138 int textColorFg = Color.BLACK;
141 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
143 public Thread newThread(Runnable r) {
144 return new Thread(r, "searchExecutor");
148 private SearchOperation currentSearchOperation = null;
150 C.Theme theme = C.Theme.LIGHT;
156 // EditText searchText;
157 SearchView searchView;
158 ImageView searchHintIcon;
160 MenuItem nextWordMenuItem, previousWordMenuItem;
163 private File wordList = null;
165 private boolean saveOnlyFirstSubentry = false;
167 private boolean clickOpensContextMenu = false;
169 // Visible for testing.
170 ListAdapter indexAdapter = null;
172 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
175 * For some languages, loading the transliterators used in this search takes
176 * a long time, so we fire it up on a different thread, and don't invoke it
177 * from the main thread until it's already finished once.
179 private volatile boolean indexPrepFinished = false;
181 public DictionaryActivity() {
184 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
185 final String searchToken) {
186 final Intent intent = new Intent();
187 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
188 DictionaryActivity.class.getName());
189 intent.putExtra(C.DICT_FILE, dictFile.getPath());
190 intent.putExtra(C.INDEX_INDEX, indexIndex);
191 intent.putExtra(C.SEARCH_TOKEN, searchToken);
196 protected void onSaveInstanceState(final Bundle outState) {
197 super.onSaveInstanceState(outState);
198 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
199 outState.putInt(C.INDEX_INDEX, indexIndex);
200 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
204 protected void onRestoreInstanceState(final Bundle outState) {
205 super.onRestoreInstanceState(outState);
206 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
211 public void onCreate(Bundle savedInstanceState) {
212 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
213 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
216 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
218 Log.d(LOG, "onCreate:" + this);
219 super.onCreate(savedInstanceState);
221 application = (DictionaryApplication) getApplication();
222 theme = application.getSelectedTheme();
223 textColorFg = getResources().getColor(theme.tokenRowFgColor);
225 final Intent intent = getIntent();
226 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
229 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
231 public void onInit(int status) {
238 final String name = application.getDictionaryName(dictFile.getName());
239 this.setTitle("QuickDic: " + name);
240 dictRaf = new RandomAccessFile(dictFile, "r");
241 dictionary = new Dictionary(dictRaf);
242 } catch (Exception e) {
243 Log.e(LOG, "Unable to load dictionary.", e);
244 if (dictRaf != null) {
247 } catch (IOException e1) {
248 Log.e(LOG, "Unable to close dictRaf.", e1);
252 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
253 Toast.LENGTH_LONG).show();
254 startActivity(DictionaryManagerActivity.getLaunchIntent());
258 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
259 if (savedInstanceState != null) {
260 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
262 indexIndex %= dictionary.indices.size();
263 Log.d(LOG, "Loading index " + indexIndex);
264 index = dictionary.indices.get(indexIndex);
265 setListAdapter(new IndexAdapter(index));
267 // Pre-load the collators.
268 new Thread(new Runnable() {
270 final long startMillis = System.currentTimeMillis();
272 TransliteratorManager.init(new TransliteratorManager.Callback() {
274 public void onTransliteratorReady() {
275 uiHandler.post(new Runnable() {
278 onSearchTextChange(searchView.getQuery().toString());
284 for (final Index index : dictionary.indices) {
285 final String searchToken = index.sortedIndexEntries.get(0).token;
286 final IndexEntry entry = index.findExact(searchToken);
287 if (!searchToken.equals(entry.token)) {
288 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
291 indexPrepFinished = true;
292 } catch (Exception e) {
294 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
296 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
300 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
301 if ("SYSTEM".equals(fontName)) {
302 typeface = Typeface.DEFAULT;
305 typeface = Typeface.createFromAsset(getAssets(), fontName);
306 } catch (Exception e) {
307 Log.w(LOG, "Exception trying to use typeface, using default.", e);
308 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
309 Toast.LENGTH_LONG).show();
312 // if (!"SYSTEM".equals(fontName)) {
313 // throw new RuntimeException("Test force using system font: " +
316 if (typeface == null) {
317 Log.w(LOG, "Unable to create typeface, using default.");
318 typeface = Typeface.DEFAULT;
320 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
322 fontSizeSp = Integer.parseInt(fontSize.trim());
323 } catch (NumberFormatException e) {
327 setContentView(R.layout.dictionary_activity);
328 // searchText = (EditText) findViewById(R.id.SearchText);
329 // searchText.requestFocus();
330 // searchText.addTextChangedListener(searchTextWatcher);
331 // searchText.setOnFocusChangeListener(new OnFocusChangeListener() {
333 // public void onFocusChange(View v, boolean hasFocus) {
334 // Log.d(LOG, "searchText onFocusChange hasFocus=" + hasFocus);
340 // final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
341 // clearSearchTextButton.setOnClickListener(new OnClickListener() {
342 // public void onClick(View v) {
343 // onClearSearchTextButton();
346 // clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
347 // .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
350 // getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
352 // public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
354 // if (!searchText.isFocused()) {
355 // if (!isFiltered()) {
356 // final RowBase row = (RowBase) getListAdapter().getItem(position);
357 // Log.d(LOG, "onItemSelected: " + row.index());
358 // final TokenRow tokenRow = row.getTokenRow(true);
359 // searchText.setText(tokenRow.getToken());
365 // public void onNothingSelected(AdapterView<?> arg0) {
370 registerForContextMenu(getListView());
373 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
374 getString(R.string.wordListFileDefault)));
375 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
377 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
379 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
381 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
383 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
385 ActionBar actionBar = getSupportActionBar();
386 actionBar.setDisplayShowTitleEnabled(false);
388 //Inflate the custom view
389 // View customNav = LayoutInflater.from(this).inflate(R.layout.dictionary_search_view, null);
390 searchView = new SearchView(getSupportActionBar().getThemedContext());
391 searchView.setIconifiedByDefault(false);
392 searchView.setQueryHint(getString(R.string.searchText));
393 searchView.setSubmitButtonEnabled(false);
394 // searchView.setMaxWidth(200);
395 searchView.setImeOptions(
396 EditorInfo.IME_ACTION_SEARCH |
397 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
398 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
399 // EditorInfo.IME_FLAG_NO_FULLSCREEN |
400 EditorInfo.IME_MASK_ACTION |
401 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
402 searchView.setMinimumWidth((int)
403 TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics()));
404 searchView.setOnQueryTextListener(new OnQueryTextListener() {
406 public boolean onQueryTextSubmit(String query) {
407 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
412 public boolean onQueryTextChange(String newText) {
413 // if (searchView.hasFocus()) {
414 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
415 // If they were typing to cause the change, update the UI.
416 onSearchTextChange(searchView.getQuery().toString());
422 // Set the search text from the intent, then the saved state.
423 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
424 if (savedInstanceState != null) {
425 text = savedInstanceState.getString(C.SEARCH_TOKEN);
430 setSearchText(text, true);
431 Log.d(LOG, "Trying to restore searchText=" + text);
433 setDictionaryPrefs(this, dictFile, indexIndex, searchView.getQuery().toString());
435 searchHintIcon = (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
436 searchHintIcon.setOnClickListener(new OnClickListener() {
438 public void onClick(View arg0) {
442 searchHintIcon.setOnLongClickListener(new OnLongClickListener() {
444 public boolean onLongClick(View v) {
445 onLanguageButtonLongClick(v.getContext());
452 // ImageView searchHintIcon = (ImageView) searchView.findViewById(searchView.getContext().getResources().
453 // getIdentifier("android:id/search_mag_icon", null, null));
454 // searchHintIcon.setImageResource(android.R.color.transparent);
455 // searchView.setOnQueryTextListener(this);
456 // menu.add("Search")
457 //// .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.abs__ic_search)
458 // .setActionView(searchView)
459 // .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
460 actionBar.setCustomView(searchView);
461 actionBar.setDisplayShowCustomEnabled(true);
467 protected void onResume() {
468 Log.d(LOG, "onResume");
470 if (SettingsActivity.settingsMightHaveChanged) {
471 SettingsActivity.settingsMightHaveChanged = false;
473 startActivity(getIntent());
479 protected void onPause() {
484 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
485 super.onActivityResult(requestCode, resultCode, result);
486 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
487 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
488 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
492 private static void setDictionaryPrefs(final Context context, final File dictFile,
493 final int indexIndex, final String searchToken) {
494 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
496 prefs.putString(C.DICT_FILE, dictFile.getPath());
497 prefs.putInt(C.INDEX_INDEX, indexIndex);
498 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
503 protected void onDestroy() {
505 if (dictRaf == null) {
509 final SearchOperation searchOperation = currentSearchOperation;
510 currentSearchOperation = null;
512 // Before we close the RAF, we have to wind the current search down.
513 if (searchOperation != null) {
514 Log.d(LOG, "Interrupting search to shut down.");
515 currentSearchOperation = null;
516 searchOperation.interrupted.set(true);
520 Log.d(LOG, "Closing RAF.");
522 } catch (IOException e) {
523 Log.e(LOG, "Failed to close dictionary", e);
528 // --------------------------------------------------------------------------
530 // --------------------------------------------------------------------------
532 private void onClearSearchTextButton() {
533 setSearchText("", true);
537 private void showKeyboard() {
538 // searchText.postDelayed(new Runnable() {
540 // public void run() {
541 // Log.d(LOG, "Trying to show soft keyboard.");
542 // final boolean searchTextHadFocus = searchText.hasFocus();
543 // searchText.requestFocus();
544 // final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
545 // manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
546 // if (!searchTextHadFocus) {
547 // defocusSearchText();
552 void updateLangButton() {
553 final LanguageResources languageResources =
554 Language.isoCodeToResources.get(index.shortName);
555 if (languageResources != null && languageResources.flagId != 0) {
556 searchHintIcon.setImageResource(languageResources.flagId);
558 if (index == dictionary.indices.get(0)) {
559 searchHintIcon.setImageResource(android.R.drawable.ic_media_next);
561 searchHintIcon.setImageResource(android.R.drawable.ic_media_previous);
567 private void updateTTSLanuage() {
568 if (!ttsReady || index == null || textToSpeech == null) {
569 Log.d(LOG, "Can't updateTTSLanguage.");
572 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
573 Log.d(LOG, "Setting TTS locale to: " + locale);
574 final int ttsResult = textToSpeech.setLanguage(locale);
575 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
576 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
577 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
581 void onLanguageButton() {
582 if (currentSearchOperation != null) {
583 currentSearchOperation.interrupted.set(true);
584 currentSearchOperation = null;
586 changeIndexAndResearch((indexIndex + 1) % dictionary.indices.size());
589 void onLanguageButtonLongClick(final Context context) {
590 final Dialog dialog = new Dialog(context);
591 dialog.setContentView(R.layout.select_dictionary_dialog);
592 dialog.setTitle(R.string.selectDictionary);
594 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
597 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
599 // final LinearLayout.LayoutParams layoutParams = new
600 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
601 // ViewGroup.LayoutParams.WRAP_CONTENT);
602 // layoutParams.width = 0;
603 // layoutParams.weight = 1.0f;
605 final Button button = new Button(listView.getContext());
606 final String name = getString(R.string.dictionaryManager);
607 button.setText(name);
608 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
609 DictionaryManagerActivity.getLaunchIntent()) {
611 protected void onGo() {
613 DictionaryActivity.this.finish();
616 button.setOnClickListener(intentLauncher);
617 // button.setLayoutParams(layoutParams);
618 listView.addHeaderView(button);
619 // listView.setHeaderDividersEnabled(true);
621 listView.setAdapter(new BaseAdapter() {
623 public View getView(int position, View convertView, ViewGroup parent) {
624 final DictionaryInfo dictionaryInfo = getItem(position);
626 final LinearLayout result = new LinearLayout(parent.getContext());
628 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
630 final TextView dash = new TextView(parent.getContext());
632 result.addView(dash);
635 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
636 final Button button = new Button(parent.getContext());
637 button.setText(indexInfo.shortName);
638 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
640 application.getPath(dictionaryInfo.uncompressedFilename),
641 i, searchView.getQuery().toString())) {
643 protected void onGo() {
645 DictionaryActivity.this.finish();
648 button.setOnClickListener(intentLauncher);
649 result.addView(button);
653 final TextView nameView = new TextView(parent.getContext());
654 final String name = application
655 .getDictionaryName(dictionaryInfo.uncompressedFilename);
656 nameView.setText(name);
657 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
658 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
659 layoutParams.width = 0;
660 layoutParams.weight = 1.0f;
661 nameView.setLayoutParams(layoutParams);
662 result.addView(nameView);
668 public long getItemId(int position) {
673 public DictionaryInfo getItem(int position) {
674 return installedDicts.get(position);
678 public int getCount() {
679 return installedDicts.size();
686 private void changeIndexAndResearch(int newIndex) {
687 Log.d(LOG, "Changing index to: " + newIndex);
688 if (newIndex == -1) {
689 Log.e(LOG, "Invalid index.");
692 indexIndex = newIndex;
693 index = dictionary.indices.get(indexIndex);
694 indexAdapter = new IndexAdapter(index);
695 Log.d(LOG, "changingIndex, newLang=" + index.longName);
696 setDictionaryPrefs(this, dictFile, indexIndex, searchView.getQuery().toString());
697 setListAdapter(indexAdapter);
699 setSearchText(searchView.getQuery().toString(), true);
702 void onUpDownButton(final boolean up) {
706 final int firstVisibleRow = getListView().getFirstVisiblePosition();
707 final RowBase row = index.rows.get(firstVisibleRow);
708 final TokenRow tokenRow = row.getTokenRow(true);
709 final int destIndexEntry;
711 if (row != tokenRow) {
712 destIndexEntry = tokenRow.referenceIndex;
714 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
718 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
720 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
721 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
722 setSearchText(dest.token, false);
723 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
727 // --------------------------------------------------------------------------
729 // --------------------------------------------------------------------------
731 final Random random = new Random();
734 public boolean onCreateOptionsMenu(final Menu menu) {
735 //Create the search view
736 // SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
737 // searchView.setIconifiedByDefault(false);
738 // searchView.setQueryHint(getString(R.string.searchText));
739 // searchView.setSubmitButtonEnabled(false);
740 // searchView.setMaxWidth(200);
741 // searchView.setImeOptions(
742 // EditorInfo.IME_ACTION_SEARCH |
743 // EditorInfo.IME_FLAG_NO_EXTRACT_UI |
744 // EditorInfo.IME_FLAG_NO_ENTER_ACTION |
745 //// EditorInfo.IME_FLAG_NO_FULLSCREEN |
746 // EditorInfo.IME_MASK_ACTION |
747 // EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
748 //// searchView.setOnQueryTextListener(this);
749 // menu.add("Search")
750 //// .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.abs__ic_search)
751 // .setActionView(searchView)
752 // .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
754 // final ImageView searchHintIcon =
755 // (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
756 // searchHintIcon.setImageResource(android.R.id.empty);
757 // searchHintIcon.setAdjustViewBounds(true);
758 // searchHintIcon.setMaxWidth(1);
759 // searchHintIcon.setMaxHeight(1);
760 // searchHintIcon.setVisibility(ImageView.GONE);
761 // searchView.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {
763 // public void onFocusChange(View arg0, boolean arg1) {
764 // searchHintIcon.setVisibility(ImageView.GONE);
765 // searchHintIcon.refreshDrawableState();
770 if (PreferenceManager.getDefaultSharedPreferences(this)
771 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
773 nextWordMenuItem = menu.add(getString(R.string.nextWord))
774 .setIcon(R.drawable.arrow_down_float);
775 nextWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
776 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
778 public boolean onMenuItemClick(MenuItem item) {
779 onUpDownButton(false);
785 previousWordMenuItem = menu.add(getString(R.string.previousWord))
786 .setIcon(R.drawable.arrow_up_float);
787 previousWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
788 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
790 public boolean onMenuItemClick(MenuItem item) {
791 onUpDownButton(true);
797 application.onCreateGlobalOptionsMenu(this, menu);
800 // final MenuItem randomWord = menu.add(getString(R.string.randomWord));
801 // randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
802 // public boolean onMenuItemClick(final MenuItem menuItem) {
803 // final String word = index.sortedIndexEntries.get(random
804 // .nextInt(index.sortedIndexEntries.size())).token;
805 // setSearchText(word, true);
812 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
813 dictionaryList.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
814 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
815 public boolean onMenuItemClick(final MenuItem menuItem) {
816 startActivity(DictionaryManagerActivity.getLaunchIntent());
824 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
825 aboutDictionary.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
826 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
827 public boolean onMenuItemClick(final MenuItem menuItem) {
828 final Context context = getListView().getContext();
829 final Dialog dialog = new Dialog(context);
830 dialog.setContentView(R.layout.about_dictionary_dialog);
831 final TextView textView = (TextView) dialog.findViewById(R.id.text);
833 final String name = application.getDictionaryName(dictFile.getName());
834 dialog.setTitle(name);
836 final StringBuilder builder = new StringBuilder();
837 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
838 dictionaryInfo.uncompressedBytes = dictFile.length();
839 if (dictionaryInfo != null) {
840 builder.append(dictionaryInfo.dictInfo).append("\n\n");
841 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
844 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
847 getString(R.string.dictionaryCreationTime,
848 dictionaryInfo.creationMillis)).append("\n");
849 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
850 builder.append("\n");
851 builder.append(getString(R.string.indexName, indexInfo.shortName))
854 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
857 builder.append("\n");
858 builder.append(getString(R.string.sources)).append("\n");
859 for (final EntrySource source : dictionary.sources) {
861 getString(R.string.sourceInfo, source.getName(),
862 source.getNumEntries())).append("\n");
866 // builder.append(getString(R.string.invalidDictionary));
868 textView.setText(builder.toString());
871 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
872 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
873 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
874 dialog.getWindow().setAttributes(layoutParams);
883 // --------------------------------------------------------------------------
884 // Context Menu + clicks
885 // --------------------------------------------------------------------------
888 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
889 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
890 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
892 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
893 wordList.getName()));
894 addToWordlist.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
895 public boolean onMenuItemClick(android.view.MenuItem item) {
896 onAppendToWordList(row);
901 final android.view.MenuItem share = menu.add("Share");
902 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
903 public boolean onMenuItemClick(android.view.MenuItem item) {
904 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
905 shareIntent.setType("text/plain");
906 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true).getToken());
907 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, row.getRawText(saveOnlyFirstSubentry));
908 startActivity(shareIntent);
913 final android.view.MenuItem copy = menu.add(android.R.string.copy);
914 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
915 public boolean onMenuItemClick(android.view.MenuItem item) {
921 if (selectedSpannableText != null) {
922 final String selectedText = selectedSpannableText;
923 final android.view.MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
924 selectedSpannableText));
925 searchForSelection.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
926 public boolean onMenuItemClick(android.view.MenuItem item) {
927 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
933 if (row instanceof TokenRow && ttsReady) {
934 final android.view.MenuItem speak = menu.add(R.string.speak);
935 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
937 public boolean onMenuItemClick(android.view.MenuItem item) {
938 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
939 new HashMap<String, String>());
946 private void jumpToTextFromHyperLink(final String selectedText, final int defaultIndexToUse) {
948 for (int i = 0; i < dictionary.indices.size(); ++i) {
949 final Index index = dictionary.indices.get(i);
950 if (indexPrepFinished) {
951 System.out.println("Doing index lookup: on " + selectedText);
952 final IndexEntry indexEntry = index.findExact(selectedText);
953 if (indexEntry != null) {
954 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
956 if (tokenRow != null && tokenRow.hasMainEntry) {
962 Log.w(LOG, "Skipping findExact on index " + index.shortName);
965 if (indexToUse == -1) {
966 indexToUse = defaultIndexToUse;
968 final boolean changeIndex = indexIndex != indexToUse;
970 setSearchText(selectedText, false);
971 changeIndexAndResearch(indexToUse);
973 setSearchText(selectedText, true);
978 protected void onListItemClick(ListView l, View v, int row, long id) {
980 if (clickOpensContextMenu && dictRaf != null) {
985 @SuppressLint("SimpleDateFormat")
986 void onAppendToWordList(final RowBase row) {
989 final StringBuilder rawText = new StringBuilder();
990 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
991 rawText.append(index.longName).append("\t");
992 rawText.append(row.getTokenRow(true).getToken()).append("\t");
993 rawText.append(row.getRawText(saveOnlyFirstSubentry));
994 Log.d(LOG, "Writing : " + rawText);
997 wordList.getParentFile().mkdirs();
998 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
999 out.println(rawText.toString());
1001 } catch (IOException e) {
1002 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1003 Toast.makeText(this,
1004 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1005 Toast.LENGTH_LONG).show();
1011 * Called when user clicks outside of search text, so that they can start
1012 * typing again immediately.
1014 void defocusSearchText() {
1015 // Log.d(LOG, "defocusSearchText");
1016 // Request focus so that if we start typing again, it clears the text
1018 getListView().requestFocus();
1020 // Visual indication that a new keystroke will clear the search text.
1021 // Doesn't seem to work unless earchText has focus.
1022 // searchText.selectAll();
1025 @SuppressWarnings("deprecation")
1026 void onCopy(final RowBase row) {
1027 defocusSearchText();
1029 Log.d(LOG, "Copy, row=" + row);
1030 final StringBuilder result = new StringBuilder();
1031 result.append(row.getRawText(false));
1032 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1033 clipboardManager.setText(result.toString());
1034 Log.d(LOG, "Copied: " + result);
1038 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1039 if (event.getUnicodeChar() != 0) {
1040 if (!searchView.hasFocus()) {
1041 setSearchText("" + (char) event.getUnicodeChar(), true);
1045 if (keyCode == KeyEvent.KEYCODE_BACK) {
1046 // Log.d(LOG, "Clearing dictionary prefs.");
1047 // Pretend that we just autolaunched so that we won't do it again.
1048 // DictionaryManagerActivity.lastAutoLaunchMillis =
1049 // System.currentTimeMillis();
1051 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1052 Log.d(LOG, "Trying to hide soft keyboard.");
1053 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1054 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
1055 InputMethodManager.HIDE_NOT_ALWAYS);
1058 return super.onKeyDown(keyCode, event);
1061 private void setSearchText(final String text, final boolean triggerSearch) {
1062 if (!triggerSearch) {
1063 getListView().requestFocus();
1065 searchView.setQuery(text, false);
1066 searchView.requestFocus();
1067 moveCursorToRight();
1068 if (triggerSearch) {
1069 onSearchTextChange(text);
1073 // private long cursorDelayMillis = 100;
1075 private void moveCursorToRight() {
1076 // if (searchText.getLayout() != null) {
1077 // cursorDelayMillis = 100;
1078 // // Surprising, but this can crash when you rotate...
1079 // Selection.moveToRightEdge(searchView.getQuery(), searchText.getLayout());
1081 // uiHandler.postDelayed(new Runnable() {
1083 // public void run() {
1084 // moveCursorToRight();
1086 // }, cursorDelayMillis);
1087 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1091 // --------------------------------------------------------------------------
1093 // --------------------------------------------------------------------------
1095 private void searchFinished(final SearchOperation searchOperation) {
1096 if (searchOperation.interrupted.get()) {
1097 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1100 if (searchOperation != this.currentSearchOperation) {
1101 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1105 final Index.IndexEntry searchResult = searchOperation.searchResult;
1106 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1108 currentSearchOperation = null;
1109 uiHandler.postDelayed(new Runnable() {
1112 if (currentSearchOperation == null) {
1113 if (searchResult != null) {
1117 jumpToRow(searchResult.startRow);
1118 } else if (searchOperation.multiWordSearchResult != null) {
1119 // Multi-row search....
1120 setFiltered(searchOperation);
1122 throw new IllegalStateException("This should never happen.");
1125 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1131 private final void jumpToRow(final int row) {
1132 final boolean refocusSearchText = searchView.hasFocus();
1133 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + refocusSearchText);
1134 getListView().requestFocusFromTouch();
1135 getListView().setSelectionFromTop(row, 0);
1136 getListView().setSelected(true);
1137 if (refocusSearchText) {
1138 searchView.requestFocus();
1140 //Log.d(LOG, "getSelectedItemPosition():" + getSelectedItemPosition());
1143 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1145 final class SearchOperation implements Runnable {
1147 final AtomicBoolean interrupted = new AtomicBoolean(false);
1149 final String searchText;
1151 List<String> searchTokens; // filled in for multiWord.
1155 long searchStartMillis;
1157 Index.IndexEntry searchResult;
1159 List<RowBase> multiWordSearchResult;
1161 boolean done = false;
1163 SearchOperation(final String searchText, final Index index) {
1164 this.searchText = StringUtil.normalizeWhitespace(searchText);
1168 public String toString() {
1169 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1175 searchStartMillis = System.currentTimeMillis();
1176 final String[] searchTokenArray = WHITESPACE.split(searchText);
1177 if (searchTokenArray.length == 1) {
1178 searchResult = index.findInsertionPoint(searchText, interrupted);
1180 searchTokens = Arrays.asList(searchTokenArray);
1181 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens, interrupted);
1184 "searchText=" + searchText + ", searchDuration="
1185 + (System.currentTimeMillis() - searchStartMillis)
1186 + ", interrupted=" + interrupted.get());
1187 if (!interrupted.get()) {
1188 uiHandler.post(new Runnable() {
1191 searchFinished(SearchOperation.this);
1195 Log.d(LOG, "interrupted, skipping searchFinished.");
1197 } catch (Exception e) {
1198 Log.e(LOG, "Failure during search (can happen during Activity close.");
1200 synchronized (this) {
1208 // --------------------------------------------------------------------------
1210 // --------------------------------------------------------------------------
1212 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1213 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1215 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1216 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1218 final class IndexAdapter extends BaseAdapter {
1220 private static final float PADDING_DEFAULT_DP = 8;
1222 private static final float PADDING_LARGE_DP = 16;
1226 final List<RowBase> rows;
1228 final Set<String> toHighlight;
1230 private int mPaddingDefault;
1232 private int mPaddingLarge;
1234 IndexAdapter(final Index index) {
1237 this.toHighlight = null;
1241 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1244 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1248 private void getMetrics() {
1249 // Get the screen's density scale
1250 final float scale = getResources().getDisplayMetrics().density;
1251 // Convert the dps to pixels, based on density scale
1252 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1253 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1257 public int getCount() {
1262 public RowBase getItem(int position) {
1263 return rows.get(position);
1267 public long getItemId(int position) {
1268 return getItem(position).index();
1272 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1273 final TableLayout result;
1274 if (convertView instanceof TableLayout) {
1275 result = (TableLayout) convertView;
1276 result.removeAllViews();
1278 result = new TableLayout(parent.getContext());
1280 final RowBase row = getItem(position);
1281 if (row instanceof PairEntry.Row) {
1282 return getView(position, (PairEntry.Row) row, parent, result);
1283 } else if (row instanceof TokenRow) {
1284 return getView((TokenRow) row, parent, result);
1285 } else if (row instanceof HtmlEntry.Row) {
1286 return getView((HtmlEntry.Row) row, parent, result);
1288 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1292 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1293 final TableLayout result) {
1294 final PairEntry entry = row.getEntry();
1295 final int rowCount = entry.pairs.size();
1297 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1298 layoutParams.weight = 0.5f;
1299 layoutParams.leftMargin = mPaddingLarge;
1301 for (int r = 0; r < rowCount; ++r) {
1302 final TableRow tableRow = new TableRow(result.getContext());
1304 final TextView col1 = new TextView(tableRow.getContext());
1305 final TextView col2 = new TextView(tableRow.getContext());
1307 // Set the columns in the table.
1309 final TextView bullet = new TextView(tableRow.getContext());
1310 bullet.setText(" • ");
1311 tableRow.addView(bullet);
1313 tableRow.addView(col1, layoutParams);
1314 final TextView margin = new TextView(tableRow.getContext());
1315 margin.setText(" ");
1316 tableRow.addView(margin);
1318 final TextView bullet = new TextView(tableRow.getContext());
1319 bullet.setText(" • ");
1320 tableRow.addView(bullet);
1322 tableRow.addView(col2, layoutParams);
1326 // Set what's in the columns.
1328 final Pair pair = entry.pairs.get(r);
1329 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1330 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1332 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1333 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1335 // Bold the token instances in col1.
1336 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1337 .singleton(row.getTokenRow(true).getToken());
1338 final Spannable col1Spannable = (Spannable) col1.getText();
1339 for (final String token : toBold) {
1341 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1342 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1343 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1344 startPos += token.length();
1348 createTokenLinkSpans(col1, col1Spannable, col1Text);
1349 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1351 col1.setTypeface(typeface);
1352 col2.setTypeface(typeface);
1353 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1354 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1355 // col2.setBackgroundResource(theme.otherLangBg);
1357 if (index.swapPairEntries) {
1358 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1359 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1361 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1362 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1365 result.addView(tableRow);
1368 // Because we have a Button inside a ListView row:
1369 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1370 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1371 result.setClickable(true);
1372 result.setFocusable(true);
1373 result.setLongClickable(true);
1374 result.setBackgroundResource(android.R.drawable.menuitem_background);
1375 result.setOnClickListener(new TextView.OnClickListener() {
1377 public void onClick(View v) {
1378 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1385 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1386 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1387 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1388 final Context context = parent.getContext();
1390 final TableRow tableRow = new TableRow(result.getContext());
1391 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1392 : theme.tokenRowOtherBg);
1394 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1396 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1398 result.addView(tableRow);
1400 // Make it so we can long-click on these token rows, too:
1401 final TextView textView = new TextView(context);
1402 textView.setText(text, BufferType.SPANNABLE);
1403 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1404 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1406 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1407 result.setLongClickable(true);
1410 // textView.setTextColor(android.R.color.secondary_text_light);
1411 textView.setTypeface(typeface);
1412 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1414 textView.setTextAppearance(context, theme.tokenRowFg);
1415 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1417 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1421 textView.setLayoutParams(lp);
1422 tableRow.addView(textView);
1424 if (!htmlEntries.isEmpty()) {
1425 final ClickableSpan clickableSpan = new ClickableSpan() {
1427 public void onClick(View widget) {
1430 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1431 result.setClickable(true);
1432 textView.setClickable(true);
1433 textView.setMovementMethod(LinkMovementMethod.getInstance());
1434 textView.setOnClickListener(new OnClickListener() {
1436 public void onClick(View v) {
1437 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1438 //Log.d(LOG, "html=" + html);
1439 startActivityForResult(
1440 HtmlDisplayActivity.getHtmlIntent(String.format(
1441 "<html><head></head><body>%s</body></html>", html),
1442 htmlTextToHighlight, false),
1450 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1451 final IndexEntry indexEntry = row.getIndexEntry();
1452 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1453 indexEntry.htmlEntries, null, parent, result);
1456 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1457 final HtmlEntry htmlEntry = row.getEntry();
1458 final TokenRow tokenRow = row.getTokenRow(true);
1459 return getPossibleLinkToHtmlEntryView(false,
1460 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1461 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1467 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1469 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1470 final String text) {
1471 // Saw from the source code that LinkMovementMethod sets the selection!
1472 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1473 textView.setMovementMethod(LinkMovementMethod.getInstance());
1474 final Matcher matcher = CHAR_DASH.matcher(text);
1475 while (matcher.find()) {
1476 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
1477 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1481 String selectedSpannableText = null;
1483 int selectedSpannableIndex = -1;
1486 public boolean onTouchEvent(MotionEvent event) {
1487 selectedSpannableText = null;
1488 selectedSpannableIndex = -1;
1489 return super.onTouchEvent(event);
1492 private class TextViewLongClickListener implements OnLongClickListener {
1495 private TextViewLongClickListener(final int index) {
1500 public boolean onLongClick(final View v) {
1501 final TextView textView = (TextView) v;
1502 final int start = textView.getSelectionStart();
1503 final int end = textView.getSelectionEnd();
1504 if (start >= 0 && end >= 0) {
1505 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1506 selectedSpannableIndex = index;
1512 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1515 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1518 // --------------------------------------------------------------------------
1520 // --------------------------------------------------------------------------
1522 void onSearchTextChange(final String text) {
1523 if ("thadolina".equals(text)) {
1524 final Dialog dialog = new Dialog(getListView().getContext());
1525 dialog.setContentView(R.layout.thadolina_dialog);
1526 dialog.setTitle("Ti amo, amore mio!");
1527 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1528 imageView.setOnClickListener(new OnClickListener() {
1530 public void onClick(View v) {
1531 final Intent intent = new Intent(Intent.ACTION_VIEW);
1532 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1533 startActivity(intent);
1538 if (dictRaf == null) {
1539 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1542 if (!searchView.isFocused()) {
1543 Log.d(LOG, "searchText changed without focus, doing nothing.");
1546 Log.d(LOG, "onSearchTextChange: " + text);
1547 if (currentSearchOperation != null) {
1548 Log.d(LOG, "Interrupting currentSearchOperation.");
1549 currentSearchOperation.interrupted.set(true);
1551 currentSearchOperation = new SearchOperation(text, index);
1552 searchExecutor.execute(currentSearchOperation);
1555 private class SearchTextWatcher implements TextWatcher {
1556 public void afterTextChanged(final Editable searchTextEditable) {
1557 if (searchView.hasFocus()) {
1558 Log.d(LOG, "SearchTextWatcher: Search text changed with focus: " + searchView.getQuery());
1559 // If they were typing to cause the change, update the UI.
1560 onSearchTextChange(searchView.getQuery().toString());
1564 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1567 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1571 // --------------------------------------------------------------------------
1572 // Filtered results.
1573 // --------------------------------------------------------------------------
1575 boolean isFiltered() {
1576 return rowsToShow != null;
1579 void setFiltered(final SearchOperation searchOperation) {
1580 if (nextWordMenuItem != null) {
1581 nextWordMenuItem.setEnabled(false);
1582 previousWordMenuItem.setEnabled(false);
1584 rowsToShow = searchOperation.multiWordSearchResult;
1585 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1588 void clearFiltered() {
1589 if (nextWordMenuItem != null) {
1590 nextWordMenuItem.setEnabled(true);
1591 previousWordMenuItem.setEnabled(true);
1593 setListAdapter(new IndexAdapter(index));