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