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