1 // Copyright 2011 Google Inc. All Rights Reserved.
2 // Some Parts Copyright 2013 Dominik Köppl
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 package com.hughes.android.dictionary;
17 import android.annotation.SuppressLint;
18 import android.app.Dialog;
19 import android.app.SearchManager;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.SharedPreferences;
23 import android.graphics.Color;
24 import android.graphics.Typeface;
25 import android.net.Uri;
26 import android.os.Bundle;
27 import android.os.Handler;
28 import android.preference.PreferenceManager;
29 import android.speech.tts.TextToSpeech;
30 import android.speech.tts.TextToSpeech.OnInitListener;
31 import android.text.ClipboardManager;
32 import android.text.Spannable;
33 import android.text.method.LinkMovementMethod;
34 import android.text.style.ClickableSpan;
35 import android.text.style.StyleSpan;
36 import android.util.Log;
37 import android.util.TypedValue;
38 import android.view.ContextMenu;
39 import android.view.ContextMenu.ContextMenuInfo;
40 import android.view.Gravity;
41 import android.view.KeyEvent;
42 import android.view.MotionEvent;
43 import android.view.View;
44 import android.view.View.OnClickListener;
45 import android.view.View.OnLongClickListener;
46 import android.view.ViewGroup;
47 import android.view.WindowManager;
48 import android.view.inputmethod.EditorInfo;
49 import android.view.inputmethod.InputMethodManager;
50 import android.widget.AdapterView.AdapterContextMenuInfo;
51 import android.widget.BaseAdapter;
52 import android.widget.Button;
53 import android.widget.FrameLayout;
54 import android.widget.ImageButton;
55 import android.widget.ImageView;
56 import android.widget.ImageView.ScaleType;
57 import android.widget.LinearLayout;
58 import android.widget.ListAdapter;
59 import android.widget.ListView;
60 import android.widget.TableLayout;
61 import android.widget.TableRow;
62 import android.widget.TextView;
63 import android.widget.TextView.BufferType;
64 import android.widget.Toast;
66 import com.actionbarsherlock.app.ActionBar;
67 import com.actionbarsherlock.app.SherlockListActivity;
68 import com.actionbarsherlock.view.Menu;
69 import com.actionbarsherlock.view.MenuItem;
70 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
71 import com.actionbarsherlock.widget.SearchView;
72 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
73 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
74 import com.hughes.android.dictionary.engine.Dictionary;
75 import com.hughes.android.dictionary.engine.EntrySource;
76 import com.hughes.android.dictionary.engine.HtmlEntry;
77 import com.hughes.android.dictionary.engine.Index;
78 import com.hughes.android.dictionary.engine.Index.IndexEntry;
79 import com.hughes.android.dictionary.engine.Language;
80 import com.hughes.android.dictionary.engine.Language.LanguageResources;
81 import com.hughes.android.dictionary.engine.PairEntry;
82 import com.hughes.android.dictionary.engine.PairEntry.Pair;
83 import com.hughes.android.dictionary.engine.RowBase;
84 import com.hughes.android.dictionary.engine.TokenRow;
85 import com.hughes.android.dictionary.engine.TransliteratorManager;
86 import com.hughes.android.util.IntentLauncher;
87 import com.hughes.android.util.NonLinkClickableSpan;
88 import com.hughes.util.StringUtil;
91 import java.io.FileWriter;
92 import java.io.IOException;
93 import java.io.PrintWriter;
94 import java.io.RandomAccessFile;
95 import java.text.SimpleDateFormat;
96 import java.util.Arrays;
97 import java.util.Collections;
98 import java.util.Date;
99 import java.util.HashMap;
100 import java.util.LinkedHashSet;
101 import java.util.List;
102 import java.util.Locale;
103 import java.util.Random;
104 import java.util.Set;
105 import java.util.concurrent.Executor;
106 import java.util.concurrent.Executors;
107 import java.util.concurrent.ThreadFactory;
108 import java.util.concurrent.atomic.AtomicBoolean;
109 import java.util.regex.Matcher;
110 import java.util.regex.Pattern;
112 public class DictionaryActivity extends SherlockListActivity {
114 static final String LOG = "QuickDic";
116 DictionaryApplication application;
118 File dictFile = null;
119 RandomAccessFile dictRaf = null;
121 Dictionary dictionary = null;
127 List<RowBase> rowsToShow = null; // if not null, just show these rows.
129 final Handler uiHandler = new Handler();
131 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
133 public Thread newThread(Runnable r) {
134 return new Thread(r, "searchExecutor");
138 private SearchOperation currentSearchOperation = null;
140 TextToSpeech textToSpeech;
141 volatile boolean ttsReady;
144 C.Theme theme = C.Theme.LIGHT;
145 int textColorFg = Color.BLACK;
148 SearchView searchView;
149 ImageButton languageButton;
150 SearchView.OnQueryTextListener onQueryTextListener;
152 MenuItem nextWordMenuItem, previousWordMenuItem;
155 private File wordList = null;
156 private boolean saveOnlyFirstSubentry = false;
157 private boolean clickOpensContextMenu = false;
159 // Visible for testing.
160 ListAdapter indexAdapter = null;
163 * For some languages, loading the transliterators used in this search takes
164 * a long time, so we fire it up on a different thread, and don't invoke it
165 * from the main thread until it's already finished once.
167 private volatile boolean indexPrepFinished = false;
169 public DictionaryActivity() {
172 public static Intent getLaunchIntent(final File dictFile, final String indexShortName,
173 final String searchToken) {
174 final Intent intent = new Intent();
175 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
176 DictionaryActivity.class.getName());
177 intent.putExtra(C.DICT_FILE, dictFile.getPath());
178 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
179 intent.putExtra(C.SEARCH_TOKEN, searchToken);
184 protected void onSaveInstanceState(final Bundle outState) {
185 super.onSaveInstanceState(outState);
186 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
187 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
188 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
192 protected void onRestoreInstanceState(final Bundle savedInstanceState) {
193 super.onRestoreInstanceState(savedInstanceState);
194 Log.d(LOG, "onRestoreInstanceState: " + savedInstanceState.getString(C.SEARCH_TOKEN));
195 onCreate(savedInstanceState);
199 public void onCreate(Bundle savedInstanceState) {
200 Log.d(LOG, "onCreate:" + this);
201 super.onCreate(savedInstanceState);
203 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
205 // Don't auto-launch if this fails.
206 prefs.edit().remove(C.DICT_FILE).commit();
208 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
210 application = (DictionaryApplication) getApplication();
211 theme = application.getSelectedTheme();
212 textColorFg = getResources().getColor(theme.tokenRowFgColor);
214 final Intent intent = getIntent();
215 String intentAction = intent.getAction();
217 * @author Dominik Köppl Querying the Intent
218 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
219 * Arguments: SearchManager.QUERY -> the phrase to search from
220 * -> language in which the phrase is written to -> to which
221 * language shall be translated
223 if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
225 String query = intent.getStringExtra(SearchManager.QUERY);
226 String from = intent.getStringExtra("from");
228 from = from.toLowerCase(Locale.US);
229 String to = intent.getStringExtra("to");
231 to = to.toLowerCase(Locale.US);
234 getIntent().putExtra(C.SEARCH_TOKEN, query);
236 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
238 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
239 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
240 for (DictionaryInfo info : dicts)
242 boolean hasFrom = from == null;
243 boolean hasTo = to == null;
244 for (IndexInfo index : info.indexInfos)
246 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
248 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
251 if (hasFrom && hasTo)
256 for (; which_index < info.indexInfos.size(); ++which_index)
258 if (info.indexInfos.get(which_index).shortName.toLowerCase(
259 Locale.US).equals(from))
262 intent.putExtra(C.INDEX_SHORT_NAME,
263 info.indexInfos.get(which_index).shortName);
266 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
275 * @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
276 * simple query Arguments follow from android standard (see
279 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
281 String query = intent.getStringExtra(SearchManager.QUERY);
283 getIntent().putExtra(C.SEARCH_TOKEN, query);
286 * @author Dominik Köppl If no dictionary is chosen, use the default
287 * dictionary specified in the preferences If this step does
288 * fail (no default directory specified), show a toast and
291 if (intent.getStringExtra(C.DICT_FILE) == null)
293 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
294 if (dictfile != null)
295 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
297 String dictFilename = intent.getStringExtra(C.DICT_FILE);
299 if (dictFilename == null)
301 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
302 startActivity(DictionaryManagerActivity.getLaunchIntent());
306 if (dictFilename != null)
307 dictFile = new File(dictFilename);
310 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
312 public void onInit(int status) {
319 final String name = application.getDictionaryName(dictFile.getName());
320 this.setTitle("QuickDic: " + name);
321 dictRaf = new RandomAccessFile(dictFile, "r");
322 dictionary = new Dictionary(dictRaf);
323 } catch (Exception e) {
324 Log.e(LOG, "Unable to load dictionary.", e);
325 if (dictRaf != null) {
328 } catch (IOException e1) {
329 Log.e(LOG, "Unable to close dictRaf.", e1);
333 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
334 Toast.LENGTH_LONG).show();
335 startActivity(DictionaryManagerActivity.getLaunchIntent());
339 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
340 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
341 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
344 for (int i = 0; i < dictionary.indices.size(); ++i) {
345 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
350 Log.d(LOG, "Loading index " + indexIndex);
351 index = dictionary.indices.get(indexIndex);
352 setListAdapter(new IndexAdapter(index));
354 // Pre-load the collators.
355 new Thread(new Runnable() {
357 final long startMillis = System.currentTimeMillis();
359 TransliteratorManager.init(new TransliteratorManager.Callback() {
361 public void onTransliteratorReady() {
362 uiHandler.post(new Runnable() {
365 onSearchTextChange(searchView.getQuery().toString());
371 for (final Index index : dictionary.indices) {
372 final String searchToken = index.sortedIndexEntries.get(0).token;
373 final IndexEntry entry = index.findExact(searchToken);
374 if (!searchToken.equals(entry.token)) {
375 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
378 indexPrepFinished = true;
379 } catch (Exception e) {
381 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
383 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
387 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
388 if ("SYSTEM".equals(fontName)) {
389 typeface = Typeface.DEFAULT;
392 typeface = Typeface.createFromAsset(getAssets(), fontName);
393 } catch (Exception e) {
394 Log.w(LOG, "Exception trying to use typeface, using default.", e);
395 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
396 Toast.LENGTH_LONG).show();
399 if (typeface == null) {
400 Log.w(LOG, "Unable to create typeface, using default.");
401 typeface = Typeface.DEFAULT;
403 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
405 fontSizeSp = Integer.parseInt(fontSize.trim());
406 } catch (NumberFormatException e) {
410 setContentView(R.layout.dictionary_activity);
413 registerForContextMenu(getListView());
416 wordList = application.getWordListFile();
417 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
419 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
421 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
423 onCreateSetupActionBarAndSearchView();
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, index.shortName, searchView.getQuery().toString());
439 searchView.requestFocus();
441 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
442 getListView().setCacheColorHint(0);
445 private void onCreateSetupActionBarAndSearchView() {
446 ActionBar actionBar = getSupportActionBar();
447 actionBar.setDisplayShowTitleEnabled(false);
448 actionBar.setDisplayShowHomeEnabled(false);
449 actionBar.setDisplayHomeAsUpEnabled(false);
451 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
453 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
454 getResources().getDisplayMetrics());
455 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
456 width, ViewGroup.LayoutParams.WRAP_CONTENT);
457 customSearchView.setLayoutParams(layoutParams);
459 languageButton = new ImageButton(customSearchView.getContext());
460 languageButton.setMinimumWidth(application.languageButtonPixels);
461 languageButton.setMinimumHeight(application.languageButtonPixels * 2 / 3);
462 languageButton.setScaleType(ScaleType.FIT_CENTER);
463 languageButton.setOnClickListener(new OnClickListener() {
465 public void onClick(View arg0) {
466 onLanguageButtonClick();
469 languageButton.setOnLongClickListener(new OnLongClickListener() {
471 public boolean onLongClick(View v) {
472 onLanguageButtonLongClick(v.getContext());
476 customSearchView.addView(languageButton);
478 searchView = new SearchView(customSearchView.getContext());
479 searchView.setIconifiedByDefault(false);
480 // searchView.setIconified(false); // puts the magnifying glass in the
482 searchView.setQueryHint(getString(R.string.searchText));
483 searchView.setSubmitButtonEnabled(false);
484 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
485 FrameLayout.LayoutParams.WRAP_CONTENT);
487 searchView.setLayoutParams(lp);
488 searchView.setImeOptions(
489 EditorInfo.IME_ACTION_SEARCH |
490 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
491 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
492 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
494 EditorInfo.IME_MASK_ACTION |
495 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
496 onQueryTextListener = new OnQueryTextListener() {
498 public boolean onQueryTextSubmit(String query) {
499 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
504 public boolean onQueryTextChange(String newText) {
505 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
506 onSearchTextChange(searchView.getQuery().toString());
510 searchView.setOnQueryTextListener(onQueryTextListener);
511 searchView.setFocusable(true);
512 customSearchView.addView(searchView);
514 // Clear the searchHint icon so that it takes as little space as possible.
515 ImageView searchHintIcon = (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
516 searchHintIcon.setBackgroundResource(android.R.color.transparent);
517 searchHintIcon.setLayoutParams(new LinearLayout.LayoutParams(1, 1));
518 searchHintIcon.setAdjustViewBounds(true);
519 searchHintIcon.setPadding(0, 0, 0, 0);
521 actionBar.setCustomView(customSearchView);
522 actionBar.setDisplayShowCustomEnabled(true);
526 protected void onResume() {
527 Log.d(LOG, "onResume");
529 if (PreferenceActivity.prefsMightHaveChanged) {
530 PreferenceActivity.prefsMightHaveChanged = false;
532 startActivity(getIntent());
538 protected void onPause() {
544 * Invoked when MyWebView returns, since the user might have clicked some
545 * hypertext in the MyWebView.
547 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
548 super.onActivityResult(requestCode, resultCode, result);
549 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
550 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
551 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
555 private static void setDictionaryPrefs(final Context context, final File dictFile,
556 final String indexShortName, final String searchToken) {
557 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
559 prefs.putString(C.DICT_FILE, dictFile.getPath());
560 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
561 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
566 protected void onDestroy() {
568 if (dictRaf == null) {
572 final SearchOperation searchOperation = currentSearchOperation;
573 currentSearchOperation = null;
575 // Before we close the RAF, we have to wind the current search down.
576 if (searchOperation != null) {
577 Log.d(LOG, "Interrupting search to shut down.");
578 currentSearchOperation = null;
579 searchOperation.interrupted.set(true);
583 Log.d(LOG, "Closing RAF.");
585 } catch (IOException e) {
586 Log.e(LOG, "Failed to close dictionary", e);
591 // --------------------------------------------------------------------------
593 // --------------------------------------------------------------------------
595 private void showKeyboard() {
596 // For some reason, this doesn't always work the first time.
597 // One way to replicate the problem:
598 // Press the "task switch" button repeatedly to pause and resume
599 for (int delay = 1; delay <= 101; delay += 100) {
600 searchView.postDelayed(new Runnable() {
603 Log.d(LOG, "Trying to show soft keyboard.");
604 final boolean searchTextHadFocus = searchView.hasFocus();
605 searchView.requestFocusFromTouch();
606 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
607 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
608 if (!searchTextHadFocus) {
616 void updateLangButton() {
617 final LanguageResources languageResources =
618 Language.isoCodeToResources.get(index.shortName);
619 if (languageResources != null && languageResources.flagId != 0) {
620 languageButton.setImageResource(languageResources.flagId);
622 if (indexIndex % 2 == 0) {
623 languageButton.setImageResource(android.R.drawable.ic_media_next);
625 languageButton.setImageResource(android.R.drawable.ic_media_previous);
631 private void updateTTSLanguage() {
632 if (!ttsReady || index == null || textToSpeech == null) {
633 Log.d(LOG, "Can't updateTTSLanguage.");
636 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
637 Log.d(LOG, "Setting TTS locale to: " + locale);
638 final int ttsResult = textToSpeech.setLanguage(locale);
639 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
640 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
641 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
645 void onLanguageButtonClick() {
646 if (dictionary.indices.size() == 1) {
647 // No need to work to switch indices.
650 if (currentSearchOperation != null) {
651 currentSearchOperation.interrupted.set(true);
652 currentSearchOperation = null;
654 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
655 searchView.getQuery().toString());
658 void onLanguageButtonLongClick(final Context context) {
659 final Dialog dialog = new Dialog(context);
660 dialog.setContentView(R.layout.select_dictionary_dialog);
661 dialog.setTitle(R.string.selectDictionary);
663 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
665 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
666 final Button button = new Button(listView.getContext());
667 final String name = getString(R.string.dictionaryManager);
668 button.setText(name);
669 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
670 DictionaryManagerActivity.getLaunchIntent()) {
672 protected void onGo() {
674 DictionaryActivity.this.finish();
677 button.setOnClickListener(intentLauncher);
678 listView.addHeaderView(button);
680 listView.setAdapter(new BaseAdapter() {
682 public View getView(int position, View convertView, ViewGroup parent) {
683 final DictionaryInfo dictionaryInfo = getItem(position);
685 final LinearLayout result = new LinearLayout(parent.getContext());
687 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
688 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
689 final View button = application.createButton(parent.getContext(),
690 dictionaryInfo, indexInfo);
691 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
693 application.getPath(dictionaryInfo.uncompressedFilename),
694 indexInfo.shortName, searchView.getQuery().toString())) {
696 protected void onGo() {
698 DictionaryActivity.this.finish();
701 button.setOnClickListener(intentLauncher);
702 result.addView(button);
705 final TextView nameView = new TextView(parent.getContext());
706 final String name = application
707 .getDictionaryName(dictionaryInfo.uncompressedFilename);
708 nameView.setText(name);
709 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
710 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
711 layoutParams.width = 0;
712 layoutParams.weight = 1.0f;
713 nameView.setLayoutParams(layoutParams);
714 nameView.setGravity(Gravity.CENTER_VERTICAL);
715 result.addView(nameView);
720 public long getItemId(int position) {
725 public DictionaryInfo getItem(int position) {
726 return installedDicts.get(position);
730 public int getCount() {
731 return installedDicts.size();
737 void onUpDownButton(final boolean up) {
741 final int firstVisibleRow = getListView().getFirstVisiblePosition();
742 final RowBase row = index.rows.get(firstVisibleRow);
743 final TokenRow tokenRow = row.getTokenRow(true);
744 final int destIndexEntry;
746 if (row != tokenRow) {
747 destIndexEntry = tokenRow.referenceIndex;
749 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
753 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
755 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
756 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
757 setSearchText(dest.token, false);
758 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
762 // --------------------------------------------------------------------------
764 // --------------------------------------------------------------------------
766 final Random random = new Random();
769 public boolean onCreateOptionsMenu(final Menu menu) {
771 if (PreferenceManager.getDefaultSharedPreferences(this)
772 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
774 nextWordMenuItem = menu.add(getString(R.string.nextWord))
775 .setIcon(R.drawable.arrow_down_float);
776 nextWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
777 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
779 public boolean onMenuItemClick(MenuItem item) {
780 onUpDownButton(false);
786 previousWordMenuItem = menu.add(getString(R.string.previousWord))
787 .setIcon(R.drawable.arrow_up_float);
788 previousWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
789 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
791 public boolean onMenuItemClick(MenuItem item) {
792 onUpDownButton(true);
798 application.onCreateGlobalOptionsMenu(this, menu);
801 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
802 dictionaryManager.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
803 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
804 public boolean onMenuItemClick(final MenuItem menuItem) {
805 startActivity(DictionaryManagerActivity.getLaunchIntent());
813 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
814 aboutDictionary.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
815 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
816 public boolean onMenuItemClick(final MenuItem menuItem) {
817 final Context context = getListView().getContext();
818 final Dialog dialog = new Dialog(context);
819 dialog.setContentView(R.layout.about_dictionary_dialog);
820 final TextView textView = (TextView) dialog.findViewById(R.id.text);
822 final String name = application.getDictionaryName(dictFile.getName());
823 dialog.setTitle(name);
825 final StringBuilder builder = new StringBuilder();
826 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
827 dictionaryInfo.uncompressedBytes = dictFile.length();
828 if (dictionaryInfo != null) {
829 builder.append(dictionaryInfo.dictInfo).append("\n\n");
830 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
833 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
836 getString(R.string.dictionaryCreationTime,
837 dictionaryInfo.creationMillis)).append("\n");
838 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
839 builder.append("\n");
840 builder.append(getString(R.string.indexName, indexInfo.shortName))
843 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
846 builder.append("\n");
847 builder.append(getString(R.string.sources)).append("\n");
848 for (final EntrySource source : dictionary.sources) {
850 getString(R.string.sourceInfo, source.getName(),
851 source.getNumEntries())).append("\n");
854 textView.setText(builder.toString());
857 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
858 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
859 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
860 dialog.getWindow().setAttributes(layoutParams);
869 // --------------------------------------------------------------------------
870 // Context Menu + clicks
871 // --------------------------------------------------------------------------
874 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
875 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
876 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
878 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
879 wordList.getName()));
881 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
882 public boolean onMenuItemClick(android.view.MenuItem item) {
883 onAppendToWordList(row);
888 final android.view.MenuItem share = menu.add("Share");
889 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
890 public boolean onMenuItemClick(android.view.MenuItem item) {
891 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
892 shareIntent.setType("text/plain");
893 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
895 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
896 row.getRawText(saveOnlyFirstSubentry));
897 startActivity(shareIntent);
902 final android.view.MenuItem copy = menu.add(android.R.string.copy);
903 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
904 public boolean onMenuItemClick(android.view.MenuItem item) {
910 if (selectedSpannableText != null) {
911 final String selectedText = selectedSpannableText;
912 final android.view.MenuItem searchForSelection = menu.add(getString(
913 R.string.searchForSelection,
914 selectedSpannableText));
916 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
917 public boolean onMenuItemClick(android.view.MenuItem item) {
918 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
922 // Rats, this won't be shown:
923 searchForSelection.setIcon(R.drawable.abs__ic_search);
926 if (row instanceof TokenRow && ttsReady) {
927 final android.view.MenuItem speak = menu.add(R.string.speak);
928 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
930 public boolean onMenuItemClick(android.view.MenuItem item) {
931 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
932 new HashMap<String, String>());
939 private void jumpToTextFromHyperLink(
940 final String selectedText, final int defaultIndexToUse) {
942 for (int i = 0; i < dictionary.indices.size(); ++i) {
943 final Index index = dictionary.indices.get(i);
944 if (indexPrepFinished) {
945 System.out.println("Doing index lookup: on " + selectedText);
946 final IndexEntry indexEntry = index.findExact(selectedText);
947 if (indexEntry != null) {
948 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
950 if (tokenRow != null && tokenRow.hasMainEntry) {
956 Log.w(LOG, "Skipping findExact on index " + index.shortName);
959 if (indexToUse == -1) {
960 indexToUse = defaultIndexToUse;
962 // Without this extra delay, the call to jumpToRow that this
963 // invokes doesn't always actually have any effect.
964 final int actualIndexToUse = indexToUse;
965 getListView().postDelayed(new Runnable() {
968 setIndexAndSearchText(actualIndexToUse, selectedText);
974 * Called when user clicks outside of search text, so that they can start
975 * typing again immediately.
977 void defocusSearchText() {
978 // Log.d(LOG, "defocusSearchText");
979 // Request focus so that if we start typing again, it clears the text
981 getListView().requestFocus();
983 // Visual indication that a new keystroke will clear the search text.
984 // Doesn't seem to work unless earchText has focus.
985 // searchView.selectAll();
989 protected void onListItemClick(ListView l, View v, int row, long id) {
991 if (clickOpensContextMenu && dictRaf != null) {
996 @SuppressLint("SimpleDateFormat")
997 void onAppendToWordList(final RowBase row) {
1000 final StringBuilder rawText = new StringBuilder();
1001 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1002 rawText.append(index.longName).append("\t");
1003 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1004 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1005 Log.d(LOG, "Writing : " + rawText);
1008 wordList.getParentFile().mkdirs();
1009 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1010 out.println(rawText.toString());
1012 } catch (Exception e) {
1013 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1014 Toast.makeText(this,
1015 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1016 Toast.LENGTH_LONG).show();
1021 @SuppressWarnings("deprecation")
1022 void onCopy(final RowBase row) {
1023 defocusSearchText();
1025 Log.d(LOG, "Copy, row=" + row);
1026 final StringBuilder result = new StringBuilder();
1027 result.append(row.getRawText(false));
1028 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1029 clipboardManager.setText(result.toString());
1030 Log.d(LOG, "Copied: " + result);
1034 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1035 if (event.getUnicodeChar() != 0) {
1036 if (!searchView.hasFocus()) {
1037 setSearchText("" + (char) event.getUnicodeChar(), true);
1038 searchView.requestFocus();
1042 if (keyCode == KeyEvent.KEYCODE_BACK) {
1043 // Log.d(LOG, "Clearing dictionary prefs.");
1044 // Pretend that we just autolaunched so that we won't do it again.
1045 // DictionaryManagerActivity.lastAutoLaunchMillis =
1046 // System.currentTimeMillis();
1048 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1049 Log.d(LOG, "Trying to hide soft keyboard.");
1050 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1051 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
1052 InputMethodManager.HIDE_NOT_ALWAYS);
1055 return super.onKeyDown(keyCode, event);
1058 private void setIndexAndSearchText(int newIndex, String newSearchText) {
1059 Log.d(LOG, "Changing index to: " + newIndex);
1060 if (newIndex == -1) {
1061 Log.e(LOG, "Invalid index.");
1064 if (newIndex != indexIndex) {
1065 indexIndex = newIndex;
1066 index = dictionary.indices.get(indexIndex);
1067 indexAdapter = new IndexAdapter(index);
1068 setListAdapter(indexAdapter);
1069 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1070 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1073 setSearchText(newSearchText, true);
1076 private void setSearchText(final String text, final boolean triggerSearch) {
1077 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1078 // Disable the listener, because sometimes it doesn't work.
1079 searchView.setOnQueryTextListener(null);
1080 searchView.setQuery(text, false);
1081 moveCursorToRight();
1082 searchView.setOnQueryTextListener(onQueryTextListener);
1083 if (triggerSearch) {
1084 onQueryTextListener.onQueryTextChange(text);
1088 // private long cursorDelayMillis = 100;
1089 private void moveCursorToRight() {
1090 // if (searchText.getLayout() != null) {
1091 // cursorDelayMillis = 100;
1092 // // Surprising, but this can crash when you rotate...
1093 // Selection.moveToRightEdge(searchView.getQuery(),
1094 // searchText.getLayout());
1096 // uiHandler.postDelayed(new Runnable() {
1098 // public void run() {
1099 // moveCursorToRight();
1101 // }, cursorDelayMillis);
1102 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1106 // --------------------------------------------------------------------------
1108 // --------------------------------------------------------------------------
1110 private void searchFinished(final SearchOperation searchOperation) {
1111 if (searchOperation.interrupted.get()) {
1112 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1115 if (searchOperation != this.currentSearchOperation) {
1116 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1120 final Index.IndexEntry searchResult = searchOperation.searchResult;
1121 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1123 currentSearchOperation = null;
1124 uiHandler.postDelayed(new Runnable() {
1127 if (currentSearchOperation == null) {
1128 if (searchResult != null) {
1132 jumpToRow(searchResult.startRow);
1133 } else if (searchOperation.multiWordSearchResult != null) {
1134 // Multi-row search....
1135 setFiltered(searchOperation);
1137 throw new IllegalStateException("This should never happen.");
1140 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1146 private final void jumpToRow(final int row) {
1147 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1148 // getListView().requestFocusFromTouch();
1149 getListView().setSelectionFromTop(row, 0);
1150 getListView().setSelected(true);
1153 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1155 final class SearchOperation implements Runnable {
1157 final AtomicBoolean interrupted = new AtomicBoolean(false);
1159 final String searchText;
1161 List<String> searchTokens; // filled in for multiWord.
1165 long searchStartMillis;
1167 Index.IndexEntry searchResult;
1169 List<RowBase> multiWordSearchResult;
1171 boolean done = false;
1173 SearchOperation(final String searchText, final Index index) {
1174 this.searchText = StringUtil.normalizeWhitespace(searchText);
1178 public String toString() {
1179 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1185 searchStartMillis = System.currentTimeMillis();
1186 final String[] searchTokenArray = WHITESPACE.split(searchText);
1187 if (searchTokenArray.length == 1) {
1188 searchResult = index.findInsertionPoint(searchText, interrupted);
1190 searchTokens = Arrays.asList(searchTokenArray);
1191 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1195 "searchText=" + searchText + ", searchDuration="
1196 + (System.currentTimeMillis() - searchStartMillis)
1197 + ", interrupted=" + interrupted.get());
1198 if (!interrupted.get()) {
1199 uiHandler.post(new Runnable() {
1202 searchFinished(SearchOperation.this);
1206 Log.d(LOG, "interrupted, skipping searchFinished.");
1208 } catch (Exception e) {
1209 Log.e(LOG, "Failure during search (can happen during Activity close.");
1211 synchronized (this) {
1219 // --------------------------------------------------------------------------
1221 // --------------------------------------------------------------------------
1223 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1224 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1226 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1227 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1229 final class IndexAdapter extends BaseAdapter {
1231 private static final float PADDING_DEFAULT_DP = 8;
1233 private static final float PADDING_LARGE_DP = 16;
1237 final List<RowBase> rows;
1239 final Set<String> toHighlight;
1241 private int mPaddingDefault;
1243 private int mPaddingLarge;
1245 IndexAdapter(final Index index) {
1248 this.toHighlight = null;
1252 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1255 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1259 private void getMetrics() {
1260 // Get the screen's density scale
1261 final float scale = getResources().getDisplayMetrics().density;
1262 // Convert the dps to pixels, based on density scale
1263 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1264 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1268 public int getCount() {
1273 public RowBase getItem(int position) {
1274 return rows.get(position);
1278 public long getItemId(int position) {
1279 return getItem(position).index();
1283 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1284 final TableLayout result;
1285 if (convertView instanceof TableLayout) {
1286 result = (TableLayout) convertView;
1287 result.removeAllViews();
1289 result = new TableLayout(parent.getContext());
1291 final RowBase row = getItem(position);
1292 if (row instanceof PairEntry.Row) {
1293 return getView(position, (PairEntry.Row) row, parent, result);
1294 } else if (row instanceof TokenRow) {
1295 return getView((TokenRow) row, parent, result);
1296 } else if (row instanceof HtmlEntry.Row) {
1297 return getView((HtmlEntry.Row) row, parent, result);
1299 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1303 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1304 final TableLayout result) {
1305 final PairEntry entry = row.getEntry();
1306 final int rowCount = entry.pairs.size();
1308 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1309 layoutParams.weight = 0.5f;
1310 layoutParams.leftMargin = mPaddingLarge;
1312 for (int r = 0; r < rowCount; ++r) {
1313 final TableRow tableRow = new TableRow(result.getContext());
1315 final TextView col1 = new TextView(tableRow.getContext());
1316 final TextView col2 = new TextView(tableRow.getContext());
1318 // Set the columns in the table.
1320 final TextView bullet = new TextView(tableRow.getContext());
1321 bullet.setText(" • ");
1322 tableRow.addView(bullet);
1324 tableRow.addView(col1, layoutParams);
1325 final TextView margin = new TextView(tableRow.getContext());
1326 margin.setText(" ");
1327 tableRow.addView(margin);
1329 final TextView bullet = new TextView(tableRow.getContext());
1330 bullet.setText(" • ");
1331 tableRow.addView(bullet);
1333 tableRow.addView(col2, layoutParams);
1337 // Set what's in the columns.
1339 final Pair pair = entry.pairs.get(r);
1340 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1341 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1343 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1344 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1346 // Bold the token instances in col1.
1347 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1348 .singleton(row.getTokenRow(true).getToken());
1349 final Spannable col1Spannable = (Spannable) col1.getText();
1350 for (final String token : toBold) {
1352 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1353 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1354 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1355 startPos += token.length();
1359 createTokenLinkSpans(col1, col1Spannable, col1Text);
1360 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1362 col1.setTypeface(typeface);
1363 col2.setTypeface(typeface);
1364 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1365 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1366 // col2.setBackgroundResource(theme.otherLangBg);
1368 if (index.swapPairEntries) {
1369 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1370 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1372 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1373 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1376 result.addView(tableRow);
1379 // Because we have a Button inside a ListView row:
1380 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1381 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1382 result.setClickable(true);
1383 result.setFocusable(true);
1384 result.setLongClickable(true);
1385 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1387 result.setBackgroundResource(theme.normalRowBg);
1389 result.setOnClickListener(new TextView.OnClickListener() {
1391 public void onClick(View v) {
1392 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1399 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1400 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1401 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1402 final Context context = parent.getContext();
1404 final TableRow tableRow = new TableRow(result.getContext());
1405 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1406 : theme.tokenRowOtherBg);
1408 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1410 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1412 result.addView(tableRow);
1414 // Make it so we can long-click on these token rows, too:
1415 final TextView textView = new TextView(context);
1416 textView.setText(text, BufferType.SPANNABLE);
1417 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1418 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1420 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1421 result.setLongClickable(true);
1424 // textView.setTextColor(android.R.color.secondary_text_light);
1425 textView.setTypeface(typeface);
1426 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1428 textView.setTextAppearance(context, theme.tokenRowFg);
1429 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1431 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1435 textView.setLayoutParams(lp);
1436 tableRow.addView(textView);
1438 if (!htmlEntries.isEmpty()) {
1439 final ClickableSpan clickableSpan = new ClickableSpan() {
1441 public void onClick(View widget) {
1444 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1445 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1446 result.setClickable(true);
1447 textView.setClickable(true);
1448 textView.setMovementMethod(LinkMovementMethod.getInstance());
1449 textView.setOnClickListener(new OnClickListener() {
1451 public void onClick(View v) {
1452 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1453 // Log.d(LOG, "html=" + html);
1454 startActivityForResult(
1455 HtmlDisplayActivity.getHtmlIntent(String.format(
1456 "<html><head></head><body>%s</body></html>", html),
1457 htmlTextToHighlight, false),
1465 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1466 final IndexEntry indexEntry = row.getIndexEntry();
1467 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1468 indexEntry.htmlEntries, null, parent, result);
1471 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1472 final HtmlEntry htmlEntry = row.getEntry();
1473 final TokenRow tokenRow = row.getTokenRow(true);
1474 return getPossibleLinkToHtmlEntryView(false,
1475 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1476 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1482 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1484 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1485 final String text) {
1486 // Saw from the source code that LinkMovementMethod sets the selection!
1487 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1488 textView.setMovementMethod(LinkMovementMethod.getInstance());
1489 final Matcher matcher = CHAR_DASH.matcher(text);
1490 while (matcher.find()) {
1491 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1493 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1497 String selectedSpannableText = null;
1499 int selectedSpannableIndex = -1;
1502 public boolean onTouchEvent(MotionEvent event) {
1503 selectedSpannableText = null;
1504 selectedSpannableIndex = -1;
1505 return super.onTouchEvent(event);
1508 private class TextViewLongClickListener implements OnLongClickListener {
1511 private TextViewLongClickListener(final int index) {
1516 public boolean onLongClick(final View v) {
1517 final TextView textView = (TextView) v;
1518 final int start = textView.getSelectionStart();
1519 final int end = textView.getSelectionEnd();
1520 if (start >= 0 && end >= 0) {
1521 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1522 selectedSpannableIndex = index;
1528 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1531 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1534 // --------------------------------------------------------------------------
1536 // --------------------------------------------------------------------------
1538 void onSearchTextChange(final String text) {
1539 if ("thadolina".equals(text)) {
1540 final Dialog dialog = new Dialog(getListView().getContext());
1541 dialog.setContentView(R.layout.thadolina_dialog);
1542 dialog.setTitle("Ti amo, amore mio!");
1543 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1544 imageView.setOnClickListener(new OnClickListener() {
1546 public void onClick(View v) {
1547 final Intent intent = new Intent(Intent.ACTION_VIEW);
1548 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1549 startActivity(intent);
1554 if (dictRaf == null) {
1555 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1558 // if (!searchView.hasFocus()) {
1559 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1562 Log.d(LOG, "onSearchTextChange: " + text);
1563 if (currentSearchOperation != null) {
1564 Log.d(LOG, "Interrupting currentSearchOperation.");
1565 currentSearchOperation.interrupted.set(true);
1567 currentSearchOperation = new SearchOperation(text, index);
1568 searchExecutor.execute(currentSearchOperation);
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));