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