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.graphics.drawable.ColorDrawable;
26 import android.net.Uri;
27 import android.os.Bundle;
28 import android.os.Handler;
29 import android.preference.PreferenceManager;
30 import android.speech.tts.TextToSpeech;
31 import android.speech.tts.TextToSpeech.OnInitListener;
32 import android.text.ClipboardManager;
33 import android.text.Spannable;
34 import android.text.method.LinkMovementMethod;
35 import android.text.style.ClickableSpan;
36 import android.text.style.StyleSpan;
37 import android.util.Log;
38 import android.util.TypedValue;
39 import android.view.ContextMenu;
40 import android.view.ContextMenu.ContextMenuInfo;
41 import android.view.Gravity;
42 import android.view.KeyEvent;
43 import android.view.MotionEvent;
44 import android.view.View;
45 import android.view.View.OnClickListener;
46 import android.view.View.OnLongClickListener;
47 import android.view.ViewGroup;
48 import android.view.ViewGroup.LayoutParams;
49 import android.view.WindowManager;
50 import android.view.inputmethod.EditorInfo;
51 import android.view.inputmethod.InputMethodManager;
52 import android.widget.AdapterView.AdapterContextMenuInfo;
53 import android.widget.BaseAdapter;
54 import android.widget.Button;
55 import android.widget.FrameLayout;
56 import android.widget.ImageView;
57 import android.widget.ImageView.ScaleType;
58 import android.widget.LinearLayout;
59 import android.widget.ListAdapter;
60 import android.widget.ListView;
61 import android.widget.TableLayout;
62 import android.widget.TableRow;
63 import android.widget.TextView;
64 import android.widget.TextView.BufferType;
65 import android.widget.Toast;
67 import com.actionbarsherlock.app.ActionBar;
68 import com.actionbarsherlock.app.SherlockListActivity;
69 import com.actionbarsherlock.view.Menu;
70 import com.actionbarsherlock.view.MenuItem;
71 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
72 import com.actionbarsherlock.widget.SearchView;
73 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
74 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
75 import com.hughes.android.dictionary.engine.Dictionary;
76 import com.hughes.android.dictionary.engine.EntrySource;
77 import com.hughes.android.dictionary.engine.HtmlEntry;
78 import com.hughes.android.dictionary.engine.Index;
79 import com.hughes.android.dictionary.engine.Index.IndexEntry;
80 import com.hughes.android.dictionary.engine.Language;
81 import com.hughes.android.dictionary.engine.Language.LanguageResources;
82 import com.hughes.android.dictionary.engine.PairEntry;
83 import com.hughes.android.dictionary.engine.PairEntry.Pair;
84 import com.hughes.android.dictionary.engine.RowBase;
85 import com.hughes.android.dictionary.engine.TokenRow;
86 import com.hughes.android.dictionary.engine.TransliteratorManager;
87 import com.hughes.android.util.IntentLauncher;
88 import com.hughes.android.util.NonLinkClickableSpan;
89 import com.hughes.util.StringUtil;
92 import java.io.FileWriter;
93 import java.io.IOException;
94 import java.io.PrintWriter;
95 import java.io.RandomAccessFile;
96 import java.text.SimpleDateFormat;
97 import java.util.Arrays;
98 import java.util.Collections;
99 import java.util.Date;
100 import java.util.HashMap;
101 import java.util.LinkedHashSet;
102 import java.util.List;
103 import java.util.Locale;
104 import java.util.Random;
105 import java.util.Set;
106 import java.util.concurrent.Executor;
107 import java.util.concurrent.Executors;
108 import java.util.concurrent.ThreadFactory;
109 import java.util.concurrent.atomic.AtomicBoolean;
110 import java.util.regex.Matcher;
111 import java.util.regex.Pattern;
113 public class DictionaryActivity extends SherlockListActivity {
115 static final String LOG = "QuickDic";
117 DictionaryApplication application;
119 File dictFile = null;
120 RandomAccessFile dictRaf = null;
122 Dictionary dictionary = null;
128 List<RowBase> rowsToShow = null; // if not null, just show these rows.
130 final Handler uiHandler = new Handler();
132 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
134 public Thread newThread(Runnable r) {
135 return new Thread(r, "searchExecutor");
139 private SearchOperation currentSearchOperation = null;
141 TextToSpeech textToSpeech;
142 volatile boolean ttsReady;
145 C.Theme theme = C.Theme.LIGHT;
146 int textColorFg = Color.BLACK;
149 SearchView searchView;
150 ImageView searchHintIcon;
151 SearchView.OnQueryTextListener onQueryTextListener;
153 MenuItem nextWordMenuItem, previousWordMenuItem;
156 private File wordList = null;
157 private boolean saveOnlyFirstSubentry = false;
158 private boolean clickOpensContextMenu = false;
160 // Visible for testing.
161 ListAdapter indexAdapter = null;
164 * For some languages, loading the transliterators used in this search takes
165 * a long time, so we fire it up on a different thread, and don't invoke it
166 * from the main thread until it's already finished once.
168 private volatile boolean indexPrepFinished = false;
170 public DictionaryActivity() {
173 public static Intent getLaunchIntent(final File dictFile, final String indexShortName,
174 final String searchToken) {
175 final Intent intent = new Intent();
176 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
177 DictionaryActivity.class.getName());
178 intent.putExtra(C.DICT_FILE, dictFile.getPath());
179 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
180 intent.putExtra(C.SEARCH_TOKEN, searchToken);
185 protected void onSaveInstanceState(final Bundle outState) {
186 super.onSaveInstanceState(outState);
187 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
188 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
189 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
193 protected void onRestoreInstanceState(final Bundle savedInstanceState) {
194 super.onRestoreInstanceState(savedInstanceState);
195 Log.d(LOG, "onRestoreInstanceState: " + savedInstanceState.getString(C.SEARCH_TOKEN));
196 onCreate(savedInstanceState);
200 public void onCreate(Bundle savedInstanceState) {
201 Log.d(LOG, "onCreate:" + this);
202 super.onCreate(savedInstanceState);
204 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
206 // Don't auto-launch if this fails.
207 prefs.edit().remove(C.DICT_FILE).commit();
209 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
211 application = (DictionaryApplication) getApplication();
212 theme = application.getSelectedTheme();
213 textColorFg = getResources().getColor(theme.tokenRowFgColor);
215 final Intent intent = getIntent();
216 String intentAction = intent.getAction();
218 * @author Dominik Köppl Querying the Intent
219 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
220 * Arguments: SearchManager.QUERY -> the phrase to search from
221 * -> language in which the phrase is written to -> to which
222 * language shall be translated
224 if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
226 String query = intent.getStringExtra(SearchManager.QUERY);
227 String from = intent.getStringExtra("from");
229 from = from.toLowerCase(Locale.US);
230 String to = intent.getStringExtra("to");
232 to = to.toLowerCase(Locale.US);
235 getIntent().putExtra(C.SEARCH_TOKEN, query);
237 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
239 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
240 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
241 for (DictionaryInfo info : dicts)
243 boolean hasFrom = from == null;
244 boolean hasTo = to == null;
245 for (IndexInfo index : info.indexInfos)
247 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
249 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
252 if (hasFrom && hasTo)
257 for (; which_index < info.indexInfos.size(); ++which_index)
259 if (info.indexInfos.get(which_index).shortName.toLowerCase(
260 Locale.US).equals(from))
263 intent.putExtra(C.INDEX_SHORT_NAME,
264 info.indexInfos.get(which_index).shortName);
267 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
276 * @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
277 * simple query Arguments follow from android standard (see
280 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
282 String query = intent.getStringExtra(SearchManager.QUERY);
284 getIntent().putExtra(C.SEARCH_TOKEN, query);
287 * @author Dominik Köppl If no dictionary is chosen, use the default
288 * dictionary specified in the preferences If this step does
289 * fail (no default directory specified), show a toast and
292 if (intent.getStringExtra(C.DICT_FILE) == null)
294 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
295 if (dictfile != null)
296 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
298 String dictFilename = intent.getStringExtra(C.DICT_FILE);
300 if (dictFilename == null)
302 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
303 startActivity(DictionaryManagerActivity.getLaunchIntent());
307 if (dictFilename != null)
308 dictFile = new File(dictFilename);
311 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
313 public void onInit(int status) {
320 final String name = application.getDictionaryName(dictFile.getName());
321 this.setTitle("QuickDic: " + name);
322 dictRaf = new RandomAccessFile(dictFile, "r");
323 dictionary = new Dictionary(dictRaf);
324 } catch (Exception e) {
325 Log.e(LOG, "Unable to load dictionary.", e);
326 if (dictRaf != null) {
329 } catch (IOException e1) {
330 Log.e(LOG, "Unable to close dictRaf.", e1);
334 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
335 Toast.LENGTH_LONG).show();
336 startActivity(DictionaryManagerActivity.getLaunchIntent());
340 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
341 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
342 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
345 for (int i = 0; i < dictionary.indices.size(); ++i) {
346 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
351 Log.d(LOG, "Loading index " + indexIndex);
352 index = dictionary.indices.get(indexIndex);
353 setListAdapter(new IndexAdapter(index));
355 // Pre-load the collators.
356 new Thread(new Runnable() {
358 final long startMillis = System.currentTimeMillis();
360 TransliteratorManager.init(new TransliteratorManager.Callback() {
362 public void onTransliteratorReady() {
363 uiHandler.post(new Runnable() {
366 onSearchTextChange(searchView.getQuery().toString());
372 for (final Index index : dictionary.indices) {
373 final String searchToken = index.sortedIndexEntries.get(0).token;
374 final IndexEntry entry = index.findExact(searchToken);
375 if (!searchToken.equals(entry.token)) {
376 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
379 indexPrepFinished = true;
380 } catch (Exception e) {
382 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
384 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
388 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
389 if ("SYSTEM".equals(fontName)) {
390 typeface = Typeface.DEFAULT;
393 typeface = Typeface.createFromAsset(getAssets(), fontName);
394 } catch (Exception e) {
395 Log.w(LOG, "Exception trying to use typeface, using default.", e);
396 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
397 Toast.LENGTH_LONG).show();
400 if (typeface == null) {
401 Log.w(LOG, "Unable to create typeface, using default.");
402 typeface = Typeface.DEFAULT;
404 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
406 fontSizeSp = Integer.parseInt(fontSize.trim());
407 } catch (NumberFormatException e) {
411 setContentView(R.layout.dictionary_activity);
414 registerForContextMenu(getListView());
417 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
418 new File(application.getDictDir(), "wordList.txt").getAbsolutePath()));
419 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
421 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
423 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
425 onCreateSetupActionBarAndSearchView();
427 // Set the search text from the intent, then the saved state.
428 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
429 if (savedInstanceState != null) {
430 text = savedInstanceState.getString(C.SEARCH_TOKEN);
435 setSearchText(text, true);
436 Log.d(LOG, "Trying to restore searchText=" + text);
438 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
441 searchView.requestFocus();
444 private void onCreateSetupActionBarAndSearchView() {
445 ActionBar actionBar = getSupportActionBar();
446 actionBar.setDisplayShowTitleEnabled(false);
447 actionBar.setDisplayShowHomeEnabled(false);
448 actionBar.setDisplayHomeAsUpEnabled(false);
450 searchView = new SearchView(getSupportActionBar().getThemedContext());
451 searchView.setIconifiedByDefault(false);
452 // searchView.setIconified(false); // puts the magnifying glass in the
454 searchView.setQueryHint(getString(R.string.searchText));
455 searchView.setSubmitButtonEnabled(false);
456 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
457 getResources().getDisplayMetrics());
458 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
459 FrameLayout.LayoutParams.WRAP_CONTENT);
460 searchView.setLayoutParams(lp);
461 searchView.setImeOptions(
462 EditorInfo.IME_ACTION_SEARCH |
463 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
464 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
465 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
467 EditorInfo.IME_MASK_ACTION |
468 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
469 onQueryTextListener = new OnQueryTextListener() {
471 public boolean onQueryTextSubmit(String query) {
472 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
477 public boolean onQueryTextChange(String newText) {
478 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
479 onSearchTextChange(searchView.getQuery().toString());
483 searchView.setOnQueryTextListener(onQueryTextListener);
484 searchView.setFocusable(true);
486 searchHintIcon = (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
487 // http://stackoverflow.com/questions/2521959/how-to-scale-an-image-in-imageview-to-keep-the-aspect-ratio
488 searchHintIcon.setLayoutParams(new LinearLayout.LayoutParams(
489 application.languageButtonPixels * 3 / 4, LayoutParams.WRAP_CONTENT));
490 searchHintIcon.setScaleType(ScaleType.FIT_CENTER);
491 searchHintIcon.setAdjustViewBounds(true);
492 searchHintIcon.setPadding(1, application.languageButtonPixels / 8, 1, 0);
493 searchHintIcon.setOnClickListener(new OnClickListener() {
495 public void onClick(View arg0) {
496 onLanguageButtonClick();
499 searchHintIcon.setOnLongClickListener(new OnLongClickListener() {
501 public boolean onLongClick(View v) {
502 onLanguageButtonLongClick(v.getContext());
506 actionBar.setCustomView(searchView);
507 actionBar.setDisplayShowCustomEnabled(true);
511 protected void onResume() {
512 Log.d(LOG, "onResume");
514 if (PreferenceActivity.prefsMightHaveChanged) {
515 PreferenceActivity.prefsMightHaveChanged = false;
517 startActivity(getIntent());
523 protected void onPause() {
529 * Invoked when MyWebView returns, since the user might have clicked some
530 * hypertext in the MyWebView.
532 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
533 super.onActivityResult(requestCode, resultCode, result);
534 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
535 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
536 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
540 private static void setDictionaryPrefs(final Context context, final File dictFile,
541 final String indexShortName, final String searchToken) {
542 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
544 prefs.putString(C.DICT_FILE, dictFile.getPath());
545 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
546 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
551 protected void onDestroy() {
553 if (dictRaf == null) {
557 final SearchOperation searchOperation = currentSearchOperation;
558 currentSearchOperation = null;
560 // Before we close the RAF, we have to wind the current search down.
561 if (searchOperation != null) {
562 Log.d(LOG, "Interrupting search to shut down.");
563 currentSearchOperation = null;
564 searchOperation.interrupted.set(true);
568 Log.d(LOG, "Closing RAF.");
570 } catch (IOException e) {
571 Log.e(LOG, "Failed to close dictionary", e);
576 // --------------------------------------------------------------------------
578 // --------------------------------------------------------------------------
580 private void showKeyboard() {
581 // For some reason, this doesn't always work the first time.
582 // One way to replicate the problem:
583 // Press the "task switch" button repeatedly to pause and resume
584 for (int delay = 1; delay <= 101; delay += 100) {
585 searchView.postDelayed(new Runnable() {
588 Log.d(LOG, "Trying to show soft keyboard.");
589 final boolean searchTextHadFocus = searchView.hasFocus();
590 searchView.requestFocusFromTouch();
591 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
592 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
593 if (!searchTextHadFocus) {
601 void updateLangButton() {
602 final LanguageResources languageResources =
603 Language.isoCodeToResources.get(index.shortName);
604 if (languageResources != null && languageResources.flagId != 0) {
605 searchHintIcon.setImageResource(languageResources.flagId);
607 if (indexIndex % 2 == 0) {
608 searchHintIcon.setImageResource(android.R.drawable.ic_media_next);
610 searchHintIcon.setImageResource(android.R.drawable.ic_media_previous);
616 private void updateTTSLanguage() {
617 if (!ttsReady || index == null || textToSpeech == null) {
618 Log.d(LOG, "Can't updateTTSLanguage.");
621 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
622 Log.d(LOG, "Setting TTS locale to: " + locale);
623 final int ttsResult = textToSpeech.setLanguage(locale);
624 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
625 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
626 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
630 void onLanguageButtonClick() {
631 if (dictionary.indices.size() == 1) {
632 // No need to work to switch indices.
635 if (currentSearchOperation != null) {
636 currentSearchOperation.interrupted.set(true);
637 currentSearchOperation = null;
639 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
640 searchView.getQuery().toString());
643 void onLanguageButtonLongClick(final Context context) {
644 final Dialog dialog = new Dialog(context);
645 dialog.setContentView(R.layout.select_dictionary_dialog);
646 dialog.setTitle(R.string.selectDictionary);
648 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
650 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
651 final Button button = new Button(listView.getContext());
652 final String name = getString(R.string.dictionaryManager);
653 button.setText(name);
654 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
655 DictionaryManagerActivity.getLaunchIntent()) {
657 protected void onGo() {
659 DictionaryActivity.this.finish();
662 button.setOnClickListener(intentLauncher);
663 listView.addHeaderView(button);
665 listView.setAdapter(new BaseAdapter() {
667 public View getView(int position, View convertView, ViewGroup parent) {
668 final DictionaryInfo dictionaryInfo = getItem(position);
670 final LinearLayout result = new LinearLayout(parent.getContext());
672 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
673 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
674 final View button = application.createButton(parent.getContext(),
675 dictionaryInfo, indexInfo);
676 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
678 application.getPath(dictionaryInfo.uncompressedFilename),
679 indexInfo.shortName, searchView.getQuery().toString())) {
681 protected void onGo() {
683 DictionaryActivity.this.finish();
686 button.setOnClickListener(intentLauncher);
687 result.addView(button);
690 final TextView nameView = new TextView(parent.getContext());
691 final String name = application
692 .getDictionaryName(dictionaryInfo.uncompressedFilename);
693 nameView.setText(name);
694 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
695 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
696 layoutParams.width = 0;
697 layoutParams.weight = 1.0f;
698 nameView.setLayoutParams(layoutParams);
699 nameView.setGravity(Gravity.CENTER_VERTICAL);
700 result.addView(nameView);
705 public long getItemId(int position) {
710 public DictionaryInfo getItem(int position) {
711 return installedDicts.get(position);
715 public int getCount() {
716 return installedDicts.size();
722 void onUpDownButton(final boolean up) {
726 final int firstVisibleRow = getListView().getFirstVisiblePosition();
727 final RowBase row = index.rows.get(firstVisibleRow);
728 final TokenRow tokenRow = row.getTokenRow(true);
729 final int destIndexEntry;
731 if (row != tokenRow) {
732 destIndexEntry = tokenRow.referenceIndex;
734 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
738 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
740 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
741 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
742 setSearchText(dest.token, false);
743 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
747 // --------------------------------------------------------------------------
749 // --------------------------------------------------------------------------
751 final Random random = new Random();
754 public boolean onCreateOptionsMenu(final Menu menu) {
756 if (PreferenceManager.getDefaultSharedPreferences(this)
757 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
759 nextWordMenuItem = menu.add(getString(R.string.nextWord))
760 .setIcon(R.drawable.arrow_down_float);
761 nextWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
762 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
764 public boolean onMenuItemClick(MenuItem item) {
765 onUpDownButton(false);
771 previousWordMenuItem = menu.add(getString(R.string.previousWord))
772 .setIcon(R.drawable.arrow_up_float);
773 previousWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
774 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
776 public boolean onMenuItemClick(MenuItem item) {
777 onUpDownButton(true);
783 application.onCreateGlobalOptionsMenu(this, menu);
786 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
787 dictionaryManager.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
788 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
789 public boolean onMenuItemClick(final MenuItem menuItem) {
790 startActivity(DictionaryManagerActivity.getLaunchIntent());
798 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
799 aboutDictionary.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
800 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
801 public boolean onMenuItemClick(final MenuItem menuItem) {
802 final Context context = getListView().getContext();
803 final Dialog dialog = new Dialog(context);
804 dialog.setContentView(R.layout.about_dictionary_dialog);
805 final TextView textView = (TextView) dialog.findViewById(R.id.text);
807 final String name = application.getDictionaryName(dictFile.getName());
808 dialog.setTitle(name);
810 final StringBuilder builder = new StringBuilder();
811 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
812 dictionaryInfo.uncompressedBytes = dictFile.length();
813 if (dictionaryInfo != null) {
814 builder.append(dictionaryInfo.dictInfo).append("\n\n");
815 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
818 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
821 getString(R.string.dictionaryCreationTime,
822 dictionaryInfo.creationMillis)).append("\n");
823 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
824 builder.append("\n");
825 builder.append(getString(R.string.indexName, indexInfo.shortName))
828 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
831 builder.append("\n");
832 builder.append(getString(R.string.sources)).append("\n");
833 for (final EntrySource source : dictionary.sources) {
835 getString(R.string.sourceInfo, source.getName(),
836 source.getNumEntries())).append("\n");
839 textView.setText(builder.toString());
842 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
843 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
844 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
845 dialog.getWindow().setAttributes(layoutParams);
854 // --------------------------------------------------------------------------
855 // Context Menu + clicks
856 // --------------------------------------------------------------------------
859 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
860 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
861 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
863 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
864 wordList.getName()));
866 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
867 public boolean onMenuItemClick(android.view.MenuItem item) {
868 onAppendToWordList(row);
873 final android.view.MenuItem share = menu.add("Share");
874 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
875 public boolean onMenuItemClick(android.view.MenuItem item) {
876 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
877 shareIntent.setType("text/plain");
878 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
880 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
881 row.getRawText(saveOnlyFirstSubentry));
882 startActivity(shareIntent);
887 final android.view.MenuItem copy = menu.add(android.R.string.copy);
888 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
889 public boolean onMenuItemClick(android.view.MenuItem item) {
895 if (selectedSpannableText != null) {
896 final String selectedText = selectedSpannableText;
897 final android.view.MenuItem searchForSelection = menu.add(getString(
898 R.string.searchForSelection,
899 selectedSpannableText));
901 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
902 public boolean onMenuItemClick(android.view.MenuItem item) {
903 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
909 if (row instanceof TokenRow && ttsReady) {
910 final android.view.MenuItem speak = menu.add(R.string.speak);
911 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
913 public boolean onMenuItemClick(android.view.MenuItem item) {
914 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
915 new HashMap<String, String>());
922 private void jumpToTextFromHyperLink(
923 final String selectedText, final int defaultIndexToUse) {
925 for (int i = 0; i < dictionary.indices.size(); ++i) {
926 final Index index = dictionary.indices.get(i);
927 if (indexPrepFinished) {
928 System.out.println("Doing index lookup: on " + selectedText);
929 final IndexEntry indexEntry = index.findExact(selectedText);
930 if (indexEntry != null) {
931 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
933 if (tokenRow != null && tokenRow.hasMainEntry) {
939 Log.w(LOG, "Skipping findExact on index " + index.shortName);
942 if (indexToUse == -1) {
943 indexToUse = defaultIndexToUse;
945 // Without this extra delay, the call to jumpToRow that this
946 // invokes doesn't always actually have any effect.
947 final int actualIndexToUse = indexToUse;
948 getListView().postDelayed(new Runnable() {
951 setIndexAndSearchText(actualIndexToUse, selectedText);
957 * Called when user clicks outside of search text, so that they can start
958 * typing again immediately.
960 void defocusSearchText() {
961 // Log.d(LOG, "defocusSearchText");
962 // Request focus so that if we start typing again, it clears the text
964 getListView().requestFocus();
966 // Visual indication that a new keystroke will clear the search text.
967 // Doesn't seem to work unless earchText has focus.
968 // searchView.selectAll();
972 protected void onListItemClick(ListView l, View v, int row, long id) {
974 if (clickOpensContextMenu && dictRaf != null) {
979 @SuppressLint("SimpleDateFormat")
980 void onAppendToWordList(final RowBase row) {
983 final StringBuilder rawText = new StringBuilder();
984 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
985 rawText.append(index.longName).append("\t");
986 rawText.append(row.getTokenRow(true).getToken()).append("\t");
987 rawText.append(row.getRawText(saveOnlyFirstSubentry));
988 Log.d(LOG, "Writing : " + rawText);
991 wordList.getParentFile().mkdirs();
992 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
993 out.println(rawText.toString());
995 } catch (IOException e) {
996 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
998 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
999 Toast.LENGTH_LONG).show();
1004 @SuppressWarnings("deprecation")
1005 void onCopy(final RowBase row) {
1006 defocusSearchText();
1008 Log.d(LOG, "Copy, row=" + row);
1009 final StringBuilder result = new StringBuilder();
1010 result.append(row.getRawText(false));
1011 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1012 clipboardManager.setText(result.toString());
1013 Log.d(LOG, "Copied: " + result);
1017 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1018 if (event.getUnicodeChar() != 0) {
1019 if (!searchView.hasFocus()) {
1020 setSearchText("" + (char) event.getUnicodeChar(), true);
1021 searchView.requestFocus();
1025 if (keyCode == KeyEvent.KEYCODE_BACK) {
1026 // Log.d(LOG, "Clearing dictionary prefs.");
1027 // Pretend that we just autolaunched so that we won't do it again.
1028 // DictionaryManagerActivity.lastAutoLaunchMillis =
1029 // System.currentTimeMillis();
1031 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1032 Log.d(LOG, "Trying to hide soft keyboard.");
1033 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1034 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
1035 InputMethodManager.HIDE_NOT_ALWAYS);
1038 return super.onKeyDown(keyCode, event);
1041 private void setIndexAndSearchText(int newIndex, String newSearchText) {
1042 Log.d(LOG, "Changing index to: " + newIndex);
1043 if (newIndex == -1) {
1044 Log.e(LOG, "Invalid index.");
1047 if (newIndex != indexIndex) {
1048 indexIndex = newIndex;
1049 index = dictionary.indices.get(indexIndex);
1050 indexAdapter = new IndexAdapter(index);
1051 setListAdapter(indexAdapter);
1052 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1053 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1056 setSearchText(newSearchText, true);
1059 private void setSearchText(final String text, final boolean triggerSearch) {
1060 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1061 // Disable the listener, because sometimes it doesn't work.
1062 searchView.setOnQueryTextListener(null);
1063 searchView.setQuery(text, false);
1064 moveCursorToRight();
1065 searchView.setOnQueryTextListener(onQueryTextListener);
1066 if (triggerSearch) {
1067 onQueryTextListener.onQueryTextChange(text);
1071 // private long cursorDelayMillis = 100;
1072 private void moveCursorToRight() {
1073 // if (searchText.getLayout() != null) {
1074 // cursorDelayMillis = 100;
1075 // // Surprising, but this can crash when you rotate...
1076 // Selection.moveToRightEdge(searchView.getQuery(),
1077 // searchText.getLayout());
1079 // uiHandler.postDelayed(new Runnable() {
1081 // public void run() {
1082 // moveCursorToRight();
1084 // }, cursorDelayMillis);
1085 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1089 // --------------------------------------------------------------------------
1091 // --------------------------------------------------------------------------
1093 private void searchFinished(final SearchOperation searchOperation) {
1094 if (searchOperation.interrupted.get()) {
1095 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1098 if (searchOperation != this.currentSearchOperation) {
1099 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1103 final Index.IndexEntry searchResult = searchOperation.searchResult;
1104 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1106 currentSearchOperation = null;
1107 uiHandler.postDelayed(new Runnable() {
1110 if (currentSearchOperation == null) {
1111 if (searchResult != null) {
1115 jumpToRow(searchResult.startRow);
1116 } else if (searchOperation.multiWordSearchResult != null) {
1117 // Multi-row search....
1118 setFiltered(searchOperation);
1120 throw new IllegalStateException("This should never happen.");
1123 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1129 private final void jumpToRow(final int row) {
1130 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1131 // getListView().requestFocusFromTouch();
1132 getListView().setSelectionFromTop(row, 0);
1133 getListView().setSelected(true);
1136 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1138 final class SearchOperation implements Runnable {
1140 final AtomicBoolean interrupted = new AtomicBoolean(false);
1142 final String searchText;
1144 List<String> searchTokens; // filled in for multiWord.
1148 long searchStartMillis;
1150 Index.IndexEntry searchResult;
1152 List<RowBase> multiWordSearchResult;
1154 boolean done = false;
1156 SearchOperation(final String searchText, final Index index) {
1157 this.searchText = StringUtil.normalizeWhitespace(searchText);
1161 public String toString() {
1162 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1168 searchStartMillis = System.currentTimeMillis();
1169 final String[] searchTokenArray = WHITESPACE.split(searchText);
1170 if (searchTokenArray.length == 1) {
1171 searchResult = index.findInsertionPoint(searchText, interrupted);
1173 searchTokens = Arrays.asList(searchTokenArray);
1174 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1178 "searchText=" + searchText + ", searchDuration="
1179 + (System.currentTimeMillis() - searchStartMillis)
1180 + ", interrupted=" + interrupted.get());
1181 if (!interrupted.get()) {
1182 uiHandler.post(new Runnable() {
1185 searchFinished(SearchOperation.this);
1189 Log.d(LOG, "interrupted, skipping searchFinished.");
1191 } catch (Exception e) {
1192 Log.e(LOG, "Failure during search (can happen during Activity close.");
1194 synchronized (this) {
1202 // --------------------------------------------------------------------------
1204 // --------------------------------------------------------------------------
1206 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1207 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1209 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1210 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1212 final class IndexAdapter extends BaseAdapter {
1214 private static final float PADDING_DEFAULT_DP = 8;
1216 private static final float PADDING_LARGE_DP = 16;
1220 final List<RowBase> rows;
1222 final Set<String> toHighlight;
1224 private int mPaddingDefault;
1226 private int mPaddingLarge;
1228 IndexAdapter(final Index index) {
1231 this.toHighlight = null;
1235 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1238 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1242 private void getMetrics() {
1243 // Get the screen's density scale
1244 final float scale = getResources().getDisplayMetrics().density;
1245 // Convert the dps to pixels, based on density scale
1246 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1247 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1251 public int getCount() {
1256 public RowBase getItem(int position) {
1257 return rows.get(position);
1261 public long getItemId(int position) {
1262 return getItem(position).index();
1266 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1267 final TableLayout result;
1268 if (convertView instanceof TableLayout) {
1269 result = (TableLayout) convertView;
1270 result.removeAllViews();
1272 result = new TableLayout(parent.getContext());
1274 final RowBase row = getItem(position);
1275 if (row instanceof PairEntry.Row) {
1276 return getView(position, (PairEntry.Row) row, parent, result);
1277 } else if (row instanceof TokenRow) {
1278 return getView((TokenRow) row, parent, result);
1279 } else if (row instanceof HtmlEntry.Row) {
1280 return getView((HtmlEntry.Row) row, parent, result);
1282 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1286 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1287 final TableLayout result) {
1288 final PairEntry entry = row.getEntry();
1289 final int rowCount = entry.pairs.size();
1291 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1292 layoutParams.weight = 0.5f;
1293 layoutParams.leftMargin = mPaddingLarge;
1295 for (int r = 0; r < rowCount; ++r) {
1296 final TableRow tableRow = new TableRow(result.getContext());
1298 final TextView col1 = new TextView(tableRow.getContext());
1299 final TextView col2 = new TextView(tableRow.getContext());
1301 // Set the columns in the table.
1303 final TextView bullet = new TextView(tableRow.getContext());
1304 bullet.setText(" • ");
1305 tableRow.addView(bullet);
1307 tableRow.addView(col1, layoutParams);
1308 final TextView margin = new TextView(tableRow.getContext());
1309 margin.setText(" ");
1310 tableRow.addView(margin);
1312 final TextView bullet = new TextView(tableRow.getContext());
1313 bullet.setText(" • ");
1314 tableRow.addView(bullet);
1316 tableRow.addView(col2, layoutParams);
1320 // Set what's in the columns.
1322 final Pair pair = entry.pairs.get(r);
1323 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1324 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1326 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1327 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1329 // Bold the token instances in col1.
1330 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1331 .singleton(row.getTokenRow(true).getToken());
1332 final Spannable col1Spannable = (Spannable) col1.getText();
1333 for (final String token : toBold) {
1335 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1336 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1337 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1338 startPos += token.length();
1342 createTokenLinkSpans(col1, col1Spannable, col1Text);
1343 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1345 col1.setTypeface(typeface);
1346 col2.setTypeface(typeface);
1347 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1348 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1349 // col2.setBackgroundResource(theme.otherLangBg);
1351 if (index.swapPairEntries) {
1352 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1353 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1355 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1356 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1359 result.addView(tableRow);
1362 // Because we have a Button inside a ListView row:
1363 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1364 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1365 result.setClickable(true);
1366 result.setFocusable(true);
1367 result.setLongClickable(true);
1368 result.setBackgroundResource(android.R.drawable.menuitem_background);
1369 result.setOnClickListener(new TextView.OnClickListener() {
1371 public void onClick(View v) {
1372 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1379 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1380 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1381 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1382 final Context context = parent.getContext();
1384 final TableRow tableRow = new TableRow(result.getContext());
1385 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1386 : theme.tokenRowOtherBg);
1388 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1390 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1392 result.addView(tableRow);
1394 // Make it so we can long-click on these token rows, too:
1395 final TextView textView = new TextView(context);
1396 textView.setText(text, BufferType.SPANNABLE);
1397 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1398 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1400 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1401 result.setLongClickable(true);
1404 // textView.setTextColor(android.R.color.secondary_text_light);
1405 textView.setTypeface(typeface);
1406 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1408 textView.setTextAppearance(context, theme.tokenRowFg);
1409 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1411 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1415 textView.setLayoutParams(lp);
1416 tableRow.addView(textView);
1418 if (!htmlEntries.isEmpty()) {
1419 final ClickableSpan clickableSpan = new ClickableSpan() {
1421 public void onClick(View widget) {
1424 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1425 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1426 result.setClickable(true);
1427 textView.setClickable(true);
1428 textView.setMovementMethod(LinkMovementMethod.getInstance());
1429 textView.setOnClickListener(new OnClickListener() {
1431 public void onClick(View v) {
1432 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1433 // Log.d(LOG, "html=" + html);
1434 startActivityForResult(
1435 HtmlDisplayActivity.getHtmlIntent(String.format(
1436 "<html><head></head><body>%s</body></html>", html),
1437 htmlTextToHighlight, false),
1445 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1446 final IndexEntry indexEntry = row.getIndexEntry();
1447 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1448 indexEntry.htmlEntries, null, parent, result);
1451 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1452 final HtmlEntry htmlEntry = row.getEntry();
1453 final TokenRow tokenRow = row.getTokenRow(true);
1454 return getPossibleLinkToHtmlEntryView(false,
1455 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1456 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1462 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1464 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1465 final String text) {
1466 // Saw from the source code that LinkMovementMethod sets the selection!
1467 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1468 textView.setMovementMethod(LinkMovementMethod.getInstance());
1469 final Matcher matcher = CHAR_DASH.matcher(text);
1470 while (matcher.find()) {
1471 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1473 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1477 String selectedSpannableText = null;
1479 int selectedSpannableIndex = -1;
1482 public boolean onTouchEvent(MotionEvent event) {
1483 selectedSpannableText = null;
1484 selectedSpannableIndex = -1;
1485 return super.onTouchEvent(event);
1488 private class TextViewLongClickListener implements OnLongClickListener {
1491 private TextViewLongClickListener(final int index) {
1496 public boolean onLongClick(final View v) {
1497 final TextView textView = (TextView) v;
1498 final int start = textView.getSelectionStart();
1499 final int end = textView.getSelectionEnd();
1500 if (start >= 0 && end >= 0) {
1501 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1502 selectedSpannableIndex = index;
1508 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1511 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1514 // --------------------------------------------------------------------------
1516 // --------------------------------------------------------------------------
1518 void onSearchTextChange(final String text) {
1519 if ("thadolina".equals(text)) {
1520 final Dialog dialog = new Dialog(getListView().getContext());
1521 dialog.setContentView(R.layout.thadolina_dialog);
1522 dialog.setTitle("Ti amo, amore mio!");
1523 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1524 imageView.setOnClickListener(new OnClickListener() {
1526 public void onClick(View v) {
1527 final Intent intent = new Intent(Intent.ACTION_VIEW);
1528 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1529 startActivity(intent);
1534 if (dictRaf == null) {
1535 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1538 // if (!searchView.hasFocus()) {
1539 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1542 Log.d(LOG, "onSearchTextChange: " + text);
1543 if (currentSearchOperation != null) {
1544 Log.d(LOG, "Interrupting currentSearchOperation.");
1545 currentSearchOperation.interrupted.set(true);
1547 currentSearchOperation = new SearchOperation(text, index);
1548 searchExecutor.execute(currentSearchOperation);
1551 // --------------------------------------------------------------------------
1552 // Filtered results.
1553 // --------------------------------------------------------------------------
1555 boolean isFiltered() {
1556 return rowsToShow != null;
1559 void setFiltered(final SearchOperation searchOperation) {
1560 if (nextWordMenuItem != null) {
1561 nextWordMenuItem.setEnabled(false);
1562 previousWordMenuItem.setEnabled(false);
1564 rowsToShow = searchOperation.multiWordSearchResult;
1565 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1568 void clearFiltered() {
1569 if (nextWordMenuItem != null) {
1570 nextWordMenuItem.setEnabled(true);
1571 previousWordMenuItem.setEnabled(true);
1573 setListAdapter(new IndexAdapter(index));