]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryActivity.java
WebView links starting to work (still timing problem).
[Dictionary.git] / src / com / hughes / android / dictionary / DictionaryActivity.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
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
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 package com.hughes.android.dictionary;
16
17 import android.app.Dialog;
18 import android.app.ListActivity;
19 import android.content.Context;
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.graphics.Typeface;
23 import android.net.Uri;
24 import android.os.Bundle;
25 import android.os.Handler;
26 import android.preference.PreferenceManager;
27 import android.speech.tts.TextToSpeech;
28 import android.speech.tts.TextToSpeech.OnInitListener;
29 import android.text.ClipboardManager;
30 import android.text.Editable;
31 import android.text.Selection;
32 import android.text.Spannable;
33 import android.text.TextWatcher;
34 import android.text.method.LinkMovementMethod;
35 import android.text.style.StyleSpan;
36 import android.util.Log;
37 import android.util.TypedValue;
38 import android.view.ContextMenu;
39 import android.view.ContextMenu.ContextMenuInfo;
40 import android.view.KeyEvent;
41 import android.view.Menu;
42 import android.view.MenuItem;
43 import android.view.MenuItem.OnMenuItemClickListener;
44 import android.view.MotionEvent;
45 import android.view.View;
46 import android.view.View.OnClickListener;
47 import android.view.View.OnLongClickListener;
48 import android.view.ViewGroup;
49 import android.view.WindowManager;
50 import android.view.inputmethod.InputMethodManager;
51 import android.widget.AdapterView;
52 import android.widget.AdapterView.AdapterContextMenuInfo;
53 import android.widget.BaseAdapter;
54 import android.widget.Button;
55 import android.widget.EditText;
56 import android.widget.ImageButton;
57 import android.widget.ImageView;
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.Toast;
65
66 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
67 import com.hughes.android.dictionary.engine.Dictionary;
68 import com.hughes.android.dictionary.engine.EntrySource;
69 import com.hughes.android.dictionary.engine.HtmlEntry;
70 import com.hughes.android.dictionary.engine.Index;
71 import com.hughes.android.dictionary.engine.Index.IndexEntry;
72 import com.hughes.android.dictionary.engine.PairEntry;
73 import com.hughes.android.dictionary.engine.PairEntry.Pair;
74 import com.hughes.android.dictionary.engine.RowBase;
75 import com.hughes.android.dictionary.engine.TokenRow;
76 import com.hughes.android.dictionary.engine.TransliteratorManager;
77 import com.hughes.android.util.IntentLauncher;
78 import com.hughes.android.util.NonLinkClickableSpan;
79
80 import java.io.File;
81 import java.io.FileWriter;
82 import java.io.IOException;
83 import java.io.PrintWriter;
84 import java.io.RandomAccessFile;
85 import java.text.SimpleDateFormat;
86 import java.util.Arrays;
87 import java.util.Collections;
88 import java.util.Date;
89 import java.util.HashMap;
90 import java.util.LinkedHashSet;
91 import java.util.List;
92 import java.util.Locale;
93 import java.util.Random;
94 import java.util.Set;
95 import java.util.concurrent.Executor;
96 import java.util.concurrent.Executors;
97 import java.util.concurrent.ThreadFactory;
98 import java.util.concurrent.atomic.AtomicBoolean;
99 import java.util.regex.Matcher;
100 import java.util.regex.Pattern;
101
102 public class DictionaryActivity extends ListActivity {
103
104     static final String LOG = "QuickDic";
105
106     DictionaryApplication application;
107
108     File dictFile = null;
109
110     RandomAccessFile dictRaf = null;
111
112     Dictionary dictionary = null;
113
114     int indexIndex = 0;
115
116     Index index = null;
117
118     List<RowBase> rowsToShow = null; // if not null, just show these rows.
119
120     // package for test.
121     final Handler uiHandler = new Handler();
122     
123     TextToSpeech textToSpeech;
124     volatile boolean ttsReady;
125
126     private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
127         @Override
128         public Thread newThread(Runnable r) {
129             return new Thread(r, "searchExecutor");
130         }
131     });
132
133     private SearchOperation currentSearchOperation = null;
134
135     C.Theme theme = C.Theme.LIGHT;
136
137     Typeface typeface;
138
139     int fontSizeSp;
140
141     EditText searchText;
142
143     Button langButton;
144
145     // Never null.
146     private File wordList = null;
147
148     private boolean saveOnlyFirstSubentry = false;
149
150     private boolean clickOpensContextMenu = false;
151
152     // Visible for testing.
153     ListAdapter indexAdapter = null;
154
155     final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
156
157     /**
158      * For some languages, loading the transliterators used in this search takes
159      * a long time, so we fire it up on a different thread, and don't invoke it
160      * from the main thread until it's already finished once.
161      */
162     private volatile boolean indexPrepFinished = false;
163
164     public DictionaryActivity() {
165     }
166
167     public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
168             final String searchToken) {
169         final Intent intent = new Intent();
170         intent.setClassName(DictionaryActivity.class.getPackage().getName(),
171                 DictionaryActivity.class.getName());
172         intent.putExtra(C.DICT_FILE, dictFile.getPath());
173         intent.putExtra(C.INDEX_INDEX, indexIndex);
174         intent.putExtra(C.SEARCH_TOKEN, searchToken);
175         return intent;
176     }
177
178     @Override
179     protected void onSaveInstanceState(final Bundle outState) {
180         super.onSaveInstanceState(outState);
181         Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
182         outState.putInt(C.INDEX_INDEX, indexIndex);
183         outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
184     }
185
186     @Override
187     protected void onRestoreInstanceState(final Bundle outState) {
188         super.onRestoreInstanceState(outState);
189         Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
190         onCreate(outState);
191     }
192
193     @Override
194     public void onCreate(Bundle savedInstanceState) {
195         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
196         prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
197                                                      // this fails.
198
199         setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
200
201         Log.d(LOG, "onCreate:" + this);
202         super.onCreate(savedInstanceState);
203
204         application = (DictionaryApplication) getApplication();
205         theme = application.getSelectedTheme();
206
207         final Intent intent = getIntent();
208         dictFile = new File(intent.getStringExtra(C.DICT_FILE));
209         
210         ttsReady = false;
211         textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
212             @Override
213             public void onInit(int status) {
214                 ttsReady = true;
215                 updateTTSLanuage();
216             }
217         });
218
219         try {
220             final String name = application.getDictionaryName(dictFile.getName());
221             this.setTitle("QuickDic: " + name);
222             dictRaf = new RandomAccessFile(dictFile, "r");
223             dictionary = new Dictionary(dictRaf);
224         } catch (Exception e) {
225             Log.e(LOG, "Unable to load dictionary.", e);
226             if (dictRaf != null) {
227                 try {
228                     dictRaf.close();
229                 } catch (IOException e1) {
230                     Log.e(LOG, "Unable to close dictRaf.", e1);
231                 }
232                 dictRaf = null;
233             }
234             Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
235                     Toast.LENGTH_LONG).show();
236             startActivity(DictionaryManagerActivity.getLaunchIntent());
237             finish();
238             return;
239         }
240         indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
241         if (savedInstanceState != null) {
242             indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
243         }
244         indexIndex %= dictionary.indices.size();
245         Log.d(LOG, "Loading index " + indexIndex);
246         index = dictionary.indices.get(indexIndex);
247         setListAdapter(new IndexAdapter(index));
248
249         // Pre-load the collators.
250         new Thread(new Runnable() {
251             public void run() {
252                 final long startMillis = System.currentTimeMillis();
253                 try {
254                     TransliteratorManager.init(new TransliteratorManager.Callback() {
255                         @Override
256                         public void onTransliteratorReady() {
257                             uiHandler.post(new Runnable() {
258                                 @Override
259                                 public void run() {
260                                     onSearchTextChange(searchText.getText().toString());
261                                 }
262                             });
263                         }
264                     });
265
266                     for (final Index index : dictionary.indices) {
267                         final String searchToken = index.sortedIndexEntries.get(0).token;
268                         final IndexEntry entry = index.findExact(searchToken);
269                         if (!searchToken.equals(entry.token)) {
270                             Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
271                         }
272                     }
273                     indexPrepFinished = true;
274                 } catch (Exception e) {
275                     Log.w(LOG,
276                             "Exception while prepping.  This can happen if dictionary is closed while search is happening.");
277                 }
278                 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
279             }
280         }).start();
281
282         String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
283         if ("SYSTEM".equals(fontName)) {
284             typeface = Typeface.DEFAULT;
285         } else {
286             try {
287                 typeface = Typeface.createFromAsset(getAssets(), fontName);
288             } catch (Exception e) {
289                 Log.w(LOG, "Exception trying to use typeface, using default.", e);
290                 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
291                         Toast.LENGTH_LONG).show();
292             }
293         }
294         // if (!"SYSTEM".equals(fontName)) {
295         // throw new RuntimeException("Test force using system font: " +
296         // fontName);
297         // }
298         if (typeface == null) {
299             Log.w(LOG, "Unable to create typeface, using default.");
300             typeface = Typeface.DEFAULT;
301         }
302         final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
303         try {
304             fontSizeSp = Integer.parseInt(fontSize.trim());
305         } catch (NumberFormatException e) {
306             fontSizeSp = 14;
307         }
308
309         setContentView(R.layout.dictionary_activity);
310         searchText = (EditText) findViewById(R.id.SearchText);
311         searchText.requestFocus();
312         searchText.addTextChangedListener(searchTextWatcher);
313
314         // Set the search text from the intent, then the saved state.
315         String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
316         if (savedInstanceState != null) {
317             text = savedInstanceState.getString(C.SEARCH_TOKEN);
318         }
319         if (text == null) {
320             text = "";
321         }
322         setSearchText(text, true);
323         Log.d(LOG, "Trying to restore searchText=" + text);
324
325         final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
326         clearSearchTextButton.setOnClickListener(new OnClickListener() {
327             public void onClick(View v) {
328                 onClearSearchTextButton();
329             }
330         });
331         clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
332                 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
333                 : View.GONE);
334
335         langButton = (Button) findViewById(R.id.LangButton);
336         langButton.setOnClickListener(new OnClickListener() {
337             public void onClick(View v) {
338                 onLanguageButton();
339             }
340         });
341         langButton.setOnLongClickListener(new OnLongClickListener() {
342             @Override
343             public boolean onLongClick(View v) {
344                 onLanguageButtonLongClick(v.getContext());
345                 return true;
346             }
347         });
348         updateLangButton();
349
350         final View upButton = findViewById(R.id.UpButton);
351         upButton.setOnClickListener(new OnClickListener() {
352             public void onClick(View v) {
353                 onUpDownButton(true);
354             }
355         });
356         final View downButton = findViewById(R.id.DownButton);
357         downButton.setOnClickListener(new OnClickListener() {
358             public void onClick(View v) {
359                 onUpDownButton(false);
360             }
361         });
362
363         getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
364             @Override
365             public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
366                     long id) {
367                 if (!searchText.isFocused()) {
368                     if (!isFiltered()) {
369                         final RowBase row = (RowBase) getListAdapter().getItem(position);
370                         Log.d(LOG, "onItemSelected: " + row.index());
371                         final TokenRow tokenRow = row.getTokenRow(true);
372                         searchText.setText(tokenRow.getToken());
373                     }
374                 }
375             }
376
377             @Override
378             public void onNothingSelected(AdapterView<?> arg0) {
379             }
380         });
381
382         // ContextMenu.
383         registerForContextMenu(getListView());
384
385         // Prefs.
386         wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
387                 getString(R.string.wordListFileDefault)));
388         saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
389                 false);
390         clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
391                 false);
392         // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
393         // true)) {
394         // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
395         // }
396         Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
397
398         setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
399     }
400
401     @Override
402     protected void onResume() {
403         Log.d(LOG, "onResume");
404         super.onResume();
405         if (PreferenceActivity.prefsMightHaveChanged) {
406             PreferenceActivity.prefsMightHaveChanged = false;
407             finish();
408             startActivity(getIntent());
409         }
410         showKeyboard();
411     }
412
413     @Override
414     protected void onPause() {
415         super.onPause();
416     }
417     
418     @Override
419     protected void onActivityResult(int requestCode, int resultCode, Intent result) {
420         super.onActivityResult(requestCode, resultCode, result);
421         if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
422             Log.d(LOG, "onActivityResult: " + result.toString());
423             jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
424         }
425     }
426
427     private static void setDictionaryPrefs(final Context context, final File dictFile,
428             final int indexIndex, final String searchToken) {
429         final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
430                 context).edit();
431         prefs.putString(C.DICT_FILE, dictFile.getPath());
432         prefs.putInt(C.INDEX_INDEX, indexIndex);
433         prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
434         prefs.commit();
435     }
436
437     @Override
438     protected void onDestroy() {
439         super.onDestroy();
440         if (dictRaf == null) {
441             return;
442         }
443
444         final SearchOperation searchOperation = currentSearchOperation;
445         currentSearchOperation = null;
446
447         // Before we close the RAF, we have to wind the current search down.
448         if (searchOperation != null) {
449             Log.d(LOG, "Interrupting search to shut down.");
450             currentSearchOperation = null;
451             searchOperation.interrupted.set(true);
452         }
453
454         try {
455             Log.d(LOG, "Closing RAF.");
456             dictRaf.close();
457         } catch (IOException e) {
458             Log.e(LOG, "Failed to close dictionary", e);
459         }
460         dictRaf = null;
461     }
462
463     // --------------------------------------------------------------------------
464     // Buttons
465     // --------------------------------------------------------------------------
466
467     private void onClearSearchTextButton() {
468         setSearchText("", true);
469         showKeyboard();
470     }
471
472     private void showKeyboard() {
473         Log.d(LOG, "Trying to show soft keyboard.");
474         final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
475         manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
476     }
477
478     void updateLangButton() {
479         // final LanguageResources languageResources =
480         // Language.isoCodeToResources.get(index.shortName);
481         // if (languageResources != null && languageResources.flagId != 0) {
482         // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
483         // languageResources.flagId, 0);
484         // } else {
485         // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
486         langButton.setText(index.shortName);
487         // }
488         updateTTSLanuage();
489     }
490     
491     private void updateTTSLanuage() {
492         if (!ttsReady) {
493             return;
494         }
495         final Locale locale = new Locale(index.sortLanguage.getIsoCode());
496         Log.d(LOG, "Setting TTS locale to: " + locale);
497         final int ttsResult = textToSpeech.setLanguage(locale);
498         if (ttsResult != TextToSpeech.SUCCESS) {
499             Log.e(LOG, "TTS not available in this language.");
500         }
501     }
502
503     void onLanguageButton() {
504         if (currentSearchOperation != null) {
505             currentSearchOperation.interrupted.set(true);
506             currentSearchOperation = null;
507         }
508         changeIndexGetFocusAndResearch((indexIndex + 1) % dictionary.indices.size());
509     }
510
511     void onLanguageButtonLongClick(final Context context) {
512         final Dialog dialog = new Dialog(context);
513         dialog.setContentView(R.layout.select_dictionary_dialog);
514         dialog.setTitle(R.string.selectDictionary);
515
516         final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
517                 .getUsableDicts();
518
519         ListView listView = (ListView) dialog.findViewById(android.R.id.list);
520
521         // final LinearLayout.LayoutParams layoutParams = new
522         // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
523         // ViewGroup.LayoutParams.WRAP_CONTENT);
524         // layoutParams.width = 0;
525         // layoutParams.weight = 1.0f;
526
527         final Button button = new Button(listView.getContext());
528         final String name = getString(R.string.dictionaryManager);
529         button.setText(name);
530         final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
531                 DictionaryManagerActivity.getLaunchIntent()) {
532             @Override
533             protected void onGo() {
534                 dialog.dismiss();
535                 DictionaryActivity.this.finish();
536             };
537         };
538         button.setOnClickListener(intentLauncher);
539         // button.setLayoutParams(layoutParams);
540         listView.addHeaderView(button);
541         // listView.setHeaderDividersEnabled(true);
542
543         listView.setAdapter(new BaseAdapter() {
544             @Override
545             public View getView(int position, View convertView, ViewGroup parent) {
546                 final DictionaryInfo dictionaryInfo = getItem(position);
547
548                 final LinearLayout result = new LinearLayout(parent.getContext());
549                 
550                 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
551                     if (i > 0) {
552                         final TextView dash = new TextView(parent.getContext());
553                         dash.setText("-");
554                         result.addView(dash);
555                     }
556                     
557                     final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
558                     final Button button = new Button(parent.getContext());
559                     button.setText(indexInfo.shortName);
560                     final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
561                             getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
562                                     i, searchText.getText().toString())) {
563                         @Override
564                         protected void onGo() {
565                             dialog.dismiss();
566                             DictionaryActivity.this.finish();
567                         };
568                     };
569                     button.setOnClickListener(intentLauncher);
570                     result.addView(button);
571                     
572                 }
573                 
574                 final TextView nameView = new TextView(parent.getContext());
575                 final String name = application
576                         .getDictionaryName(dictionaryInfo.uncompressedFilename);
577                 nameView.setText(name);
578                 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
579                         ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
580                 layoutParams.width = 0;
581                 layoutParams.weight = 1.0f;
582                 nameView.setLayoutParams(layoutParams);
583                 result.addView(nameView);
584
585                 return result;
586             }
587
588             @Override
589             public long getItemId(int position) {
590                 return position;
591             }
592
593             @Override
594             public DictionaryInfo getItem(int position) {
595                 return installedDicts.get(position);
596             }
597
598             @Override
599             public int getCount() {
600                 return installedDicts.size();
601             }
602         });
603
604         dialog.show();
605     }
606
607     private void changeIndexGetFocusAndResearch(int newIndex) {
608         Log.d(LOG, "Changing index to: " + newIndex);
609         if (newIndex == -1) {
610             Log.e(LOG, "Invalid index.");
611             newIndex = 0;
612         }
613         indexIndex = newIndex;
614         index = dictionary.indices.get(indexIndex);
615         indexAdapter = new IndexAdapter(index);
616         Log.d(LOG, "changingIndex, newLang=" + index.longName);
617         setListAdapter(indexAdapter);
618         updateLangButton();
619         searchText.requestFocus(); // Otherwise, nothing may happen.
620         onSearchTextChange(searchText.getText().toString());
621         setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
622     }
623
624     void onUpDownButton(final boolean up) {
625         if (isFiltered()) {
626             return;
627         }
628         final int firstVisibleRow = getListView().getFirstVisiblePosition();
629         final RowBase row = index.rows.get(firstVisibleRow);
630         final TokenRow tokenRow = row.getTokenRow(true);
631         final int destIndexEntry;
632         if (up) {
633             if (row != tokenRow) {
634                 destIndexEntry = tokenRow.referenceIndex;
635             } else {
636                 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
637             }
638         } else {
639             // Down
640             destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
641         }
642         final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
643         Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
644         searchText.removeTextChangedListener(searchTextWatcher);
645         searchText.setText(dest.token);
646         if (searchText.getLayout() != null) {
647             // Surprising, but this can otherwise crash sometimes...
648             Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
649         }
650         jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
651         searchText.addTextChangedListener(searchTextWatcher);
652     }
653
654     // --------------------------------------------------------------------------
655     // Options Menu
656     // --------------------------------------------------------------------------
657
658     final Random random = new Random();
659
660     @Override
661     public boolean onCreateOptionsMenu(final Menu menu) {
662         application.onCreateGlobalOptionsMenu(this, menu);
663
664         {
665             final MenuItem randomWord = menu.add(getString(R.string.randomWord));
666             randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
667                 public boolean onMenuItemClick(final MenuItem menuItem) {
668                     final String word = index.sortedIndexEntries.get(random
669                             .nextInt(index.sortedIndexEntries.size())).token;
670                     setSearchText(word, true);
671                     return false;
672                 }
673             });
674         }
675
676         {
677             final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
678             dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
679                 public boolean onMenuItemClick(final MenuItem menuItem) {
680                     startActivity(DictionaryManagerActivity.getLaunchIntent());
681                     finish();
682                     return false;
683                 }
684             });
685         }
686
687         {
688             final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
689             aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
690                 public boolean onMenuItemClick(final MenuItem menuItem) {
691                     final Context context = getListView().getContext();
692                     final Dialog dialog = new Dialog(context);
693                     dialog.setContentView(R.layout.about_dictionary_dialog);
694                     final TextView textView = (TextView) dialog.findViewById(R.id.text);
695
696                     final String name = application.getDictionaryName(dictFile.getName());
697                     dialog.setTitle(name);
698
699                     final StringBuilder builder = new StringBuilder();
700                     final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
701                     dictionaryInfo.uncompressedBytes = dictFile.length();
702                     if (dictionaryInfo != null) {
703                         builder.append(dictionaryInfo.dictInfo).append("\n\n");
704                         builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
705                                 .append("\n");
706                         builder.append(
707                                 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
708                                 .append("\n");
709                         builder.append(
710                                 getString(R.string.dictionaryCreationTime,
711                                         dictionaryInfo.creationMillis)).append("\n");
712                         for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
713                             builder.append("\n");
714                             builder.append(getString(R.string.indexName, indexInfo.shortName))
715                                     .append("\n");
716                             builder.append(
717                                     getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
718                                     .append("\n");
719                         }
720                         builder.append("\n");
721                         builder.append(getString(R.string.sources)).append("\n");
722                         for (final EntrySource source : dictionary.sources) {
723                             builder.append(
724                                     getString(R.string.sourceInfo, source.getName(),
725                                             source.getNumEntries())).append("\n");
726                         }
727                     }
728                     // } else {
729                     // builder.append(getString(R.string.invalidDictionary));
730                     // }
731                     textView.setText(builder.toString());
732
733                     dialog.show();
734                     final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
735                     layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
736                     layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
737                     dialog.getWindow().setAttributes(layoutParams);
738                     return false;
739                 }
740             });
741         }
742
743         return true;
744     }
745
746     // --------------------------------------------------------------------------
747     // Context Menu + clicks
748     // --------------------------------------------------------------------------
749
750     @Override
751     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
752         AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
753         final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
754
755         final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
756                 wordList.getName()));
757         addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
758             public boolean onMenuItemClick(MenuItem item) {
759                 onAppendToWordList(row);
760                 return false;
761             }
762         });
763
764         final MenuItem copy = menu.add(android.R.string.copy);
765         copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
766             public boolean onMenuItemClick(MenuItem item) {
767                 onCopy(row);
768                 return false;
769             }
770         });
771
772         if (selectedSpannableText != null) {
773             final String selectedText = selectedSpannableText;
774             final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
775                     selectedSpannableText));
776             searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
777                 public boolean onMenuItemClick(MenuItem item) {
778                     jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
779                     return false;
780                 }
781             });
782         }
783         
784         if (row instanceof TokenRow) {
785             final MenuItem speak = menu.add(R.string.speak);
786             speak.setOnMenuItemClickListener(new OnMenuItemClickListener() {
787                 @Override
788                 public boolean onMenuItemClick(MenuItem item) {
789                     textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH, new HashMap<String, String>());
790                     return false;
791                 }
792             });
793         }
794     }
795     
796     private void jumpToTextFromHyperLink(final String selectedText, final int defaultIndexToUse) {
797         int indexToUse = -1;
798         for (int i = 0; i < dictionary.indices.size(); ++i) {
799             final Index index = dictionary.indices.get(i);
800             if (indexPrepFinished) {
801                 System.out.println("Doing index lookup: on " + selectedText);
802                 final IndexEntry indexEntry = index.findExact(selectedText);
803                 if (indexEntry != null) {
804                     final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
805                             .getTokenRow(false);
806                     if (tokenRow != null && tokenRow.hasMainEntry) {
807                         indexToUse = i;
808                         break;
809                     }
810                 }
811             } else {
812                 Log.w(LOG, "Skipping findExact on index " + index.shortName);
813             }
814         }
815         if (indexToUse == -1) {
816             indexToUse = defaultIndexToUse;
817         }
818         final boolean changeIndex = indexIndex != indexToUse;
819         // If we're not changing index, we have to trigger search:
820         setSearchText(selectedText, !changeIndex); 
821         if (changeIndex) {
822             changeIndexGetFocusAndResearch(indexToUse);
823         }
824         // Give focus back to list view because typing is done.
825         getListView().requestFocus();
826     }
827
828     @Override
829     protected void onListItemClick(ListView l, View v, int row, long id) {
830         defocusSearchText();
831         if (clickOpensContextMenu && dictRaf != null) {
832             openContextMenu(v);
833         }
834     }
835
836     void onAppendToWordList(final RowBase row) {
837         defocusSearchText();
838
839         final StringBuilder rawText = new StringBuilder();
840         rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
841         rawText.append(index.longName).append("\t");
842         rawText.append(row.getTokenRow(true).getToken()).append("\t");
843         rawText.append(row.getRawText(saveOnlyFirstSubentry));
844         Log.d(LOG, "Writing : " + rawText);
845
846         try {
847             wordList.getParentFile().mkdirs();
848             final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
849             out.println(rawText.toString());
850             out.close();
851         } catch (IOException e) {
852             Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
853             Toast.makeText(this,
854                     getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
855                     Toast.LENGTH_LONG).show();
856         }
857         return;
858     }
859
860     /**
861      * Called when user clicks outside of search text, so that they can start
862      * typing again immediately.
863      */
864     void defocusSearchText() {
865         // Log.d(LOG, "defocusSearchText");
866         // Request focus so that if we start typing again, it clears the text
867         // input.
868         getListView().requestFocus();
869
870         // Visual indication that a new keystroke will clear the search text.
871         searchText.selectAll();
872     }
873
874     @SuppressWarnings("deprecation")
875     void onCopy(final RowBase row) {
876         defocusSearchText();
877
878         Log.d(LOG, "Copy, row=" + row);
879         final StringBuilder result = new StringBuilder();
880         result.append(row.getRawText(false));
881         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
882         clipboardManager.setText(result.toString());
883         Log.d(LOG, "Copied: " + result);
884     }
885
886     @Override
887     public boolean onKeyDown(final int keyCode, final KeyEvent event) {
888         if (event.getUnicodeChar() != 0) {
889             if (!searchText.hasFocus()) {
890                 setSearchText("" + (char) event.getUnicodeChar(), true);
891             }
892             return true;
893         }
894         if (keyCode == KeyEvent.KEYCODE_BACK) {
895             // Log.d(LOG, "Clearing dictionary prefs.");
896             // Pretend that we just autolaunched so that we won't do it again.
897             // DictionaryManagerActivity.lastAutoLaunchMillis =
898             // System.currentTimeMillis();
899         }
900         if (keyCode == KeyEvent.KEYCODE_ENTER) {
901             Log.d(LOG, "Trying to hide soft keyboard.");
902             final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
903             inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
904                     InputMethodManager.HIDE_NOT_ALWAYS);
905             return true;
906         }
907         return super.onKeyDown(keyCode, event);
908     }
909
910     private void setSearchText(final String text, final boolean triggerSearch) {
911         if (!triggerSearch) {
912             getListView().requestFocus();
913         }
914         searchText.setText(text);
915         searchText.requestFocus();
916         moveCursorToRight();
917         if (triggerSearch) {
918             onSearchTextChange(text);
919         }
920     }
921
922     private long cursorDelayMillis = 100;
923
924     private void moveCursorToRight() {
925         if (searchText.getLayout() != null) {
926             cursorDelayMillis = 100;
927             // Surprising, but this can crash when you rotate...
928             Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
929         } else {
930             uiHandler.postDelayed(new Runnable() {
931                 @Override
932                 public void run() {
933                     moveCursorToRight();
934                 }
935             }, cursorDelayMillis);
936             cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
937         }
938     }
939
940     // --------------------------------------------------------------------------
941     // SearchOperation
942     // --------------------------------------------------------------------------
943
944     private void searchFinished(final SearchOperation searchOperation) {
945         if (searchOperation.interrupted.get()) {
946             Log.d(LOG, "Search operation was interrupted: " + searchOperation);
947             return;
948         }
949         if (searchOperation != this.currentSearchOperation) {
950             Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
951             return;
952         }
953
954         final Index.IndexEntry searchResult = searchOperation.searchResult;
955         Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
956
957         currentSearchOperation = null;
958         uiHandler.postDelayed(new Runnable() {
959             @Override
960             public void run() {
961                 if (currentSearchOperation == null) {
962                     if (searchResult != null) {
963                         if (isFiltered()) {
964                             clearFiltered();
965                         }
966                         jumpToRow(searchResult.startRow);
967                     } else if (searchOperation.multiWordSearchResult != null) {
968                         // Multi-row search....
969                         setFiltered(searchOperation);
970                     } else {
971                         throw new IllegalStateException("This should never happen.");
972                     }
973                 } else {
974                     Log.d(LOG, "More coming, waiting for currentSearchOperation.");
975                 }
976             }
977         }, 20);
978     }
979     
980     private final void jumpToRow(final int row) {
981         Log.d(LOG, "jumpToRow: " + row);
982         setSelection(row);
983         getListView().setSelected(true);
984     }
985
986     static final Pattern WHITESPACE = Pattern.compile("\\s+");
987
988     final class SearchOperation implements Runnable {
989
990         final AtomicBoolean interrupted = new AtomicBoolean(false);
991
992         final String searchText;
993
994         List<String> searchTokens; // filled in for multiWord.
995
996         final Index index;
997
998         long searchStartMillis;
999
1000         Index.IndexEntry searchResult;
1001
1002         List<RowBase> multiWordSearchResult;
1003
1004         boolean done = false;
1005
1006         SearchOperation(final String searchText, final Index index) {
1007             this.searchText = searchText.trim();
1008             this.index = index;
1009         }
1010
1011         public String toString() {
1012             return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1013         }
1014
1015         @Override
1016         public void run() {
1017             try {
1018                 searchStartMillis = System.currentTimeMillis();
1019                 final String[] searchTokenArray = WHITESPACE.split(searchText);
1020                 if (searchTokenArray.length == 1) {
1021                     searchResult = index.findInsertionPoint(searchText, interrupted);
1022                 } else {
1023                     searchTokens = Arrays.asList(searchTokenArray);
1024                     multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
1025                 }
1026                 Log.d(LOG,
1027                         "searchText=" + searchText + ", searchDuration="
1028                                 + (System.currentTimeMillis() - searchStartMillis)
1029                                 + ", interrupted=" + interrupted.get());
1030                 if (!interrupted.get()) {
1031                     uiHandler.post(new Runnable() {
1032                         @Override
1033                         public void run() {
1034                             searchFinished(SearchOperation.this);
1035                         }
1036                     });
1037                 } else {
1038                     Log.d(LOG, "interrupted, skipping searchFinished.");
1039                 }
1040             } catch (Exception e) {
1041                 Log.e(LOG, "Failure during search (can happen during Activity close.");
1042             } finally {
1043                 synchronized (this) {
1044                     done = true;
1045                     this.notifyAll();
1046                 }
1047             }
1048         }
1049     }
1050
1051     // --------------------------------------------------------------------------
1052     // IndexAdapter
1053     // --------------------------------------------------------------------------
1054
1055     static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1056             ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1057
1058     static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1059             ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1060
1061     final class IndexAdapter extends BaseAdapter {
1062
1063         private static final float PADDING_DEFAULT_DP = 8;
1064
1065         private static final float PADDING_LARGE_DP = 16;
1066
1067         final Index index;
1068
1069         final List<RowBase> rows;
1070
1071         final Set<String> toHighlight;
1072
1073         private int mPaddingDefault;
1074
1075         private int mPaddingLarge;
1076
1077         IndexAdapter(final Index index) {
1078             this.index = index;
1079             rows = index.rows;
1080             this.toHighlight = null;
1081             getMetrics();
1082         }
1083
1084         IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1085             this.index = index;
1086             this.rows = rows;
1087             this.toHighlight = new LinkedHashSet<String>(toHighlight);
1088             getMetrics();
1089         }
1090
1091         private void getMetrics() {
1092             // Get the screen's density scale
1093             final float scale = getResources().getDisplayMetrics().density;
1094             // Convert the dps to pixels, based on density scale
1095             mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1096             mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1097         }
1098
1099         @Override
1100         public int getCount() {
1101             return rows.size();
1102         }
1103
1104         @Override
1105         public RowBase getItem(int position) {
1106             return rows.get(position);
1107         }
1108
1109         @Override
1110         public long getItemId(int position) {
1111             return getItem(position).index();
1112         }
1113
1114         @Override
1115         public TableLayout getView(int position, View convertView, ViewGroup parent) {
1116             final TableLayout result;
1117             if (convertView instanceof TableLayout) {
1118                 result = (TableLayout) convertView;
1119                 result.removeAllViews();
1120             } else {
1121                 result = new TableLayout(parent.getContext());
1122             }
1123             final RowBase row = getItem(position);
1124             if (row instanceof PairEntry.Row) {
1125                 return getView(position, (PairEntry.Row) row, parent, result);
1126             } else if (row instanceof TokenRow) {
1127                 return getView((TokenRow) row, parent, result);
1128             } else if (row instanceof HtmlEntry.Row) {
1129                 return getView((HtmlEntry.Row) row, parent, result);
1130             } else {
1131                 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1132             }
1133         }
1134
1135         private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1136                 final TableLayout result) {
1137             final PairEntry entry = row.getEntry();
1138             final int rowCount = entry.pairs.size();
1139
1140             final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1141             layoutParams.weight = 0.5f;
1142             layoutParams.leftMargin = mPaddingLarge;
1143
1144             for (int r = 0; r < rowCount; ++r) {
1145                 final TableRow tableRow = new TableRow(result.getContext());
1146
1147                 final TextView col1 = new TextView(tableRow.getContext());
1148                 final TextView col2 = new TextView(tableRow.getContext());
1149
1150                 // Set the columns in the table.
1151                 if (r > 0) {
1152                     final TextView bullet = new TextView(tableRow.getContext());
1153                     bullet.setText(" â€¢ ");
1154                     tableRow.addView(bullet);
1155                 }
1156                 tableRow.addView(col1, layoutParams);
1157                 final TextView margin = new TextView(tableRow.getContext());
1158                 margin.setText(" ");
1159                 tableRow.addView(margin);
1160                 if (r > 0) {
1161                     final TextView bullet = new TextView(tableRow.getContext());
1162                     bullet.setText(" â€¢ ");
1163                     tableRow.addView(bullet);
1164                 }
1165                 tableRow.addView(col2, layoutParams);
1166                 col1.setWidth(1);
1167                 col2.setWidth(1);
1168
1169                 // Set what's in the columns.
1170
1171                 final Pair pair = entry.pairs.get(r);
1172                 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1173                 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1174
1175                 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1176                 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1177
1178                 // Bold the token instances in col1.
1179                 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1180                         .singleton(row.getTokenRow(true).getToken());
1181                 final Spannable col1Spannable = (Spannable) col1.getText();
1182                 for (final String token : toBold) {
1183                     int startPos = 0;
1184                     while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1185                         col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1186                                 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1187                         startPos += token.length();
1188                     }
1189                 }
1190
1191                 createTokenLinkSpans(col1, col1Spannable, col1Text);
1192                 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1193
1194                 col1.setTypeface(typeface);
1195                 col2.setTypeface(typeface);
1196                 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1197                 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1198                 // col2.setBackgroundResource(theme.otherLangBg);
1199
1200                 if (index.swapPairEntries) {
1201                     col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1202                     col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1203                 } else {
1204                     col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1205                     col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1206                 }
1207
1208                 result.addView(tableRow);
1209             }
1210
1211             // Because we have a Button inside a ListView row:
1212             // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1213             result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1214             result.setClickable(true);
1215             result.setFocusable(true);
1216             result.setLongClickable(true);
1217             result.setBackgroundResource(android.R.drawable.menuitem_background);
1218             result.setOnClickListener(new TextView.OnClickListener() {
1219                 @Override
1220                 public void onClick(View v) {
1221                     DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1222                 }
1223             });
1224
1225             return result;
1226         }
1227
1228         private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow, final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries, final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1229             final Context context = parent.getContext();
1230             
1231             final TableRow tableRow = new TableRow(result.getContext());
1232             tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1233                     : theme.tokenRowOtherBg);
1234             if (isTokenRow) {
1235                 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1236             } else {
1237                 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1238             }
1239             result.addView(tableRow);
1240
1241             final TextView textView = new TextView(context);
1242             textView.setText(text);
1243             // Doesn't work:
1244             // textView.setTextColor(android.R.color.secondary_text_light);
1245             textView.setTypeface(typeface);
1246             TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1247             if (isTokenRow) {
1248                 textView.setTextAppearance(context, theme.tokenRowFg);
1249                 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1250             } else {
1251                 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1252             }
1253             lp.weight = 1.0f;
1254             
1255             textView.setLayoutParams(lp);
1256             tableRow.addView(textView);
1257
1258             
1259             if (!htmlEntries.isEmpty()) {
1260                 final ImageButton button = new ImageButton(context);
1261                 button.setImageResource(R.drawable.ic_menu_forward);
1262                 button.setOnClickListener(new OnClickListener() {
1263                     @Override
1264                     public void onClick(View v) {
1265                         final String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1266                         startActivityForResult(
1267                                 HtmlDisplayActivity.getHtmlIntent(String.format("<html><head></head><body>%s</body></html>", html), htmlTextToHighlight, false),
1268                                 0);
1269                     }
1270                 });
1271                 tableRow.addView(button);
1272                 lp = new TableRow.LayoutParams(1);
1273                 lp.weight = 0.0f;
1274                 button.setLayoutParams(lp);
1275                 //result.setColumnStretchable(0, true);
1276                 //result.setColumnStretchable(1, false);
1277             }
1278             result.setLongClickable(true);
1279             return result;
1280         }
1281         
1282         private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1283             final IndexEntry indexEntry = row.getIndexEntry();
1284             return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry, indexEntry.htmlEntries, null, parent, result);
1285         }
1286         
1287         private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1288             final HtmlEntry htmlEntry = row.getEntry();
1289             final TokenRow tokenRow = row.getTokenRow(true);
1290             return getPossibleLinkToHtmlEntryView(false, getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()), 
1291                     false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent, result);
1292         }
1293
1294
1295     }
1296     
1297
1298
1299     static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1300
1301     private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1302             final String text) {
1303         // Saw from the source code that LinkMovementMethod sets the selection!
1304         // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1305         textView.setMovementMethod(LinkMovementMethod.getInstance());
1306         final Matcher matcher = CHAR_DASH.matcher(text);
1307         while (matcher.find()) {
1308             spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(),
1309                     Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1310         }
1311     }
1312
1313     String selectedSpannableText = null;
1314
1315     int selectedSpannableIndex = -1;
1316
1317     @Override
1318     public boolean onTouchEvent(MotionEvent event) {
1319         selectedSpannableText = null;
1320         selectedSpannableIndex = -1;
1321         return super.onTouchEvent(event);
1322     }
1323
1324     private class TextViewLongClickListener implements OnLongClickListener {
1325         final int index;
1326
1327         private TextViewLongClickListener(final int index) {
1328             this.index = index;
1329         }
1330
1331         @Override
1332         public boolean onLongClick(final View v) {
1333             final TextView textView = (TextView) v;
1334             final int start = textView.getSelectionStart();
1335             final int end = textView.getSelectionEnd();
1336             if (start >= 0 && end >= 0) {
1337                 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1338                 selectedSpannableIndex = index;
1339             }
1340             return false;
1341         }
1342     }
1343
1344     final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1345             0);
1346
1347     final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1348             1);
1349
1350     // --------------------------------------------------------------------------
1351     // SearchText
1352     // --------------------------------------------------------------------------
1353
1354     void onSearchTextChange(final String text) {
1355         if ("thadolina".equals(text)) {
1356             final Dialog dialog = new Dialog(getListView().getContext());
1357             dialog.setContentView(R.layout.thadolina_dialog);
1358             dialog.setTitle("Ti amo, amore mio!");
1359             final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1360             imageView.setOnClickListener(new OnClickListener() {
1361                 @Override
1362                 public void onClick(View v) {
1363                     final Intent intent = new Intent(Intent.ACTION_VIEW);
1364                     intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1365                     startActivity(intent);
1366                 }
1367             });
1368             dialog.show();
1369         }
1370         if (dictRaf == null) {
1371             Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1372             return;
1373         }
1374         if (!searchText.isFocused()) {
1375             Log.d(LOG, "searchText changed without focus, doing nothing.");
1376             return;
1377         }
1378         Log.d(LOG, "onSearchTextChange: " + text);
1379         if (currentSearchOperation != null) {
1380             Log.d(LOG, "Interrupting currentSearchOperation.");
1381             currentSearchOperation.interrupted.set(true);
1382         }
1383         currentSearchOperation = new SearchOperation(text, index);
1384         searchExecutor.execute(currentSearchOperation);
1385     }
1386
1387     private class SearchTextWatcher implements TextWatcher {
1388         public void afterTextChanged(final Editable searchTextEditable) {
1389             if (searchText.hasFocus()) {
1390                 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
1391                 // If they were typing to cause the change, update the UI.
1392                 onSearchTextChange(searchText.getText().toString());
1393             }
1394         }
1395
1396         public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1397         }
1398
1399         public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1400         }
1401     }
1402
1403     // --------------------------------------------------------------------------
1404     // Filtered results.
1405     // --------------------------------------------------------------------------
1406
1407     boolean isFiltered() {
1408         return rowsToShow != null;
1409     }
1410
1411     void setFiltered(final SearchOperation searchOperation) {
1412         ((ImageButton) findViewById(R.id.UpButton)).setEnabled(false);
1413         ((ImageButton) findViewById(R.id.DownButton)).setEnabled(false);
1414         rowsToShow = searchOperation.multiWordSearchResult;
1415         setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1416     }
1417
1418     void clearFiltered() {
1419         ((ImageButton) findViewById(R.id.UpButton)).setEnabled(true);
1420         ((ImageButton) findViewById(R.id.DownButton)).setEnabled(true);
1421         setListAdapter(new IndexAdapter(index));
1422         rowsToShow = null;
1423     }
1424
1425 }