]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryActivity.java
Relayout search bar to improve usability, use ImageButton for clear
[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
297         langButton = (Button) findViewById(R.id.LangButton);
298
299         searchText.requestFocus();
300         searchText.addTextChangedListener(searchTextWatcher);
301
302         // Set the search text from the intent, then the saved state.
303         String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
304         if (savedInstanceState != null) {
305             text = savedInstanceState.getString(C.SEARCH_TOKEN);
306         }
307         if (text == null) {
308             text = "";
309         }
310         setSearchText(text, true);
311         Log.d(LOG, "Trying to restore searchText=" + text);
312
313         final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
314         clearSearchTextButton.setOnClickListener(new OnClickListener() {
315             public void onClick(View v) {
316                 onClearSearchTextButton();
317             }
318         });
319         clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
320                 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
321                 : View.GONE);
322
323         final Button langButton = (Button) findViewById(R.id.LangButton);
324         langButton.setOnClickListener(new OnClickListener() {
325             public void onClick(View v) {
326                 onLanguageButton();
327             }
328         });
329         langButton.setOnLongClickListener(new OnLongClickListener() {
330             @Override
331             public boolean onLongClick(View v) {
332                 onLanguageButtonLongClick(v.getContext());
333                 return true;
334             }
335         });
336         updateLangButton();
337
338         final Button upButton = (Button) findViewById(R.id.UpButton);
339         upButton.setOnClickListener(new OnClickListener() {
340             public void onClick(View v) {
341                 onUpDownButton(true);
342             }
343         });
344         final Button downButton = (Button) findViewById(R.id.DownButton);
345         downButton.setOnClickListener(new OnClickListener() {
346             public void onClick(View v) {
347                 onUpDownButton(false);
348             }
349         });
350
351         getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
352             @Override
353             public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
354                     long id) {
355                 if (!searchText.isFocused()) {
356                     if (!isFiltered()) {
357                         final RowBase row = (RowBase) getListAdapter().getItem(position);
358                         Log.d(LOG, "onItemSelected: " + row.index());
359                         final TokenRow tokenRow = row.getTokenRow(true);
360                         searchText.setText(tokenRow.getToken());
361                     }
362                 }
363             }
364
365             @Override
366             public void onNothingSelected(AdapterView<?> arg0) {
367             }
368         });
369
370         // ContextMenu.
371         registerForContextMenu(getListView());
372
373         // Prefs.
374         wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
375                 getString(R.string.wordListFileDefault)));
376         saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
377                 false);
378         clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
379                 false);
380         // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
381         // true)) {
382         // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
383         // }
384         Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
385
386         setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
387     }
388
389     @Override
390     protected void onResume() {
391         super.onResume();
392         if (PreferenceActivity.prefsMightHaveChanged) {
393             PreferenceActivity.prefsMightHaveChanged = false;
394             finish();
395             startActivity(getIntent());
396         }
397         if (initialSearchText != null) {
398             setSearchText(initialSearchText, true);
399         }
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         Log.d(LOG, "Trying to show soft keyboard.");
450         final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
451         manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
452     }
453
454     void updateLangButton() {
455         // final LanguageResources languageResources =
456         // Language.isoCodeToResources.get(index.shortName);
457         // if (languageResources != null && languageResources.flagId != 0) {
458         // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
459         // languageResources.flagId, 0);
460         // } else {
461         // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
462         langButton.setText(index.shortName);
463         // }
464     }
465
466     void onLanguageButton() {
467         if (currentSearchOperation != null) {
468             currentSearchOperation.interrupted.set(true);
469             currentSearchOperation = null;
470         }
471         changeIndexGetFocusAndResearch((indexIndex + 1) % dictionary.indices.size());
472     }
473
474     void onLanguageButtonLongClick(final Context context) {
475         final Dialog dialog = new Dialog(context);
476         dialog.setContentView(R.layout.select_dictionary_dialog);
477         dialog.setTitle(R.string.selectDictionary);
478
479         final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
480                 .getUsableDicts();
481
482         ListView listView = (ListView) dialog.findViewById(android.R.id.list);
483
484         // final LinearLayout.LayoutParams layoutParams = new
485         // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
486         // ViewGroup.LayoutParams.WRAP_CONTENT);
487         // layoutParams.width = 0;
488         // layoutParams.weight = 1.0f;
489
490         final Button button = new Button(listView.getContext());
491         final String name = getString(R.string.dictionaryManager);
492         button.setText(name);
493         final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
494                 DictionaryManagerActivity.getLaunchIntent()) {
495             @Override
496             protected void onGo() {
497                 dialog.dismiss();
498                 DictionaryActivity.this.finish();
499             };
500         };
501         button.setOnClickListener(intentLauncher);
502         // button.setLayoutParams(layoutParams);
503         listView.addHeaderView(button);
504         // listView.setHeaderDividersEnabled(true);
505
506         listView.setAdapter(new BaseAdapter() {
507             @Override
508             public View getView(int position, View convertView, ViewGroup parent) {
509                 final LinearLayout result = new LinearLayout(parent.getContext());
510
511                 final DictionaryInfo dictionaryInfo = getItem(position);
512                 final Button button = new Button(parent.getContext());
513                 final String name = application
514                         .getDictionaryName(dictionaryInfo.uncompressedFilename);
515                 button.setText(name);
516                 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
517                         getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
518                                 0, searchText.getText().toString())) {
519                     @Override
520                     protected void onGo() {
521                         dialog.dismiss();
522                         DictionaryActivity.this.finish();
523                     };
524                 };
525                 button.setOnClickListener(intentLauncher);
526                 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
527                         ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
528                 layoutParams.width = 0;
529                 layoutParams.weight = 1.0f;
530                 button.setLayoutParams(layoutParams);
531                 result.addView(button);
532                 return result;
533             }
534
535             @Override
536             public long getItemId(int position) {
537                 return position;
538             }
539
540             @Override
541             public DictionaryInfo getItem(int position) {
542                 return installedDicts.get(position);
543             }
544
545             @Override
546             public int getCount() {
547                 return installedDicts.size();
548             }
549         });
550
551         dialog.show();
552     }
553
554     private void changeIndexGetFocusAndResearch(final int newIndex) {
555         indexIndex = newIndex;
556         index = dictionary.indices.get(indexIndex);
557         indexAdapter = new IndexAdapter(index);
558         Log.d(LOG, "changingIndex, newLang=" + index.longName);
559         setListAdapter(indexAdapter);
560         updateLangButton();
561         searchText.requestFocus(); // Otherwise, nothing may happen.
562         onSearchTextChange(searchText.getText().toString());
563         setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
564     }
565
566     void onUpDownButton(final boolean up) {
567         if (isFiltered()) {
568             return;
569         }
570         final int firstVisibleRow = getListView().getFirstVisiblePosition();
571         final RowBase row = index.rows.get(firstVisibleRow);
572         final TokenRow tokenRow = row.getTokenRow(true);
573         final int destIndexEntry;
574         if (up) {
575             if (row != tokenRow) {
576                 destIndexEntry = tokenRow.referenceIndex;
577             } else {
578                 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
579             }
580         } else {
581             // Down
582             destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
583         }
584         final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
585         Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
586         searchText.removeTextChangedListener(searchTextWatcher);
587         searchText.setText(dest.token);
588         if (searchText.getLayout() != null) {
589             // Surprising, but this can otherwise crash sometimes...
590             Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
591         }
592         jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
593         searchText.addTextChangedListener(searchTextWatcher);
594     }
595
596     // --------------------------------------------------------------------------
597     // Options Menu
598     // --------------------------------------------------------------------------
599
600     final Random random = new Random();
601
602     @Override
603     public boolean onCreateOptionsMenu(final Menu menu) {
604         application.onCreateGlobalOptionsMenu(this, menu);
605
606         {
607             final MenuItem randomWord = menu.add(getString(R.string.randomWord));
608             randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
609                 public boolean onMenuItemClick(final MenuItem menuItem) {
610                     final String word = index.sortedIndexEntries.get(random
611                             .nextInt(index.sortedIndexEntries.size())).token;
612                     setSearchText(word, true);
613                     return false;
614                 }
615             });
616         }
617
618         {
619             final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
620             dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
621                 public boolean onMenuItemClick(final MenuItem menuItem) {
622                     startActivity(DictionaryManagerActivity.getLaunchIntent());
623                     finish();
624                     return false;
625                 }
626             });
627         }
628
629         {
630             final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
631             aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
632                 public boolean onMenuItemClick(final MenuItem menuItem) {
633                     final Context context = getListView().getContext();
634                     final Dialog dialog = new Dialog(context);
635                     dialog.setContentView(R.layout.about_dictionary_dialog);
636                     final TextView textView = (TextView) dialog.findViewById(R.id.text);
637
638                     final String name = application.getDictionaryName(dictFile.getName());
639                     dialog.setTitle(name);
640
641                     final StringBuilder builder = new StringBuilder();
642                     final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
643                     dictionaryInfo.uncompressedBytes = dictFile.length();
644                     if (dictionaryInfo != null) {
645                         builder.append(dictionaryInfo.dictInfo).append("\n\n");
646                         builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
647                                 .append("\n");
648                         builder.append(
649                                 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
650                                 .append("\n");
651                         builder.append(
652                                 getString(R.string.dictionaryCreationTime,
653                                         dictionaryInfo.creationMillis)).append("\n");
654                         for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
655                             builder.append("\n");
656                             builder.append(getString(R.string.indexName, indexInfo.shortName))
657                                     .append("\n");
658                             builder.append(
659                                     getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
660                                     .append("\n");
661                         }
662                         builder.append("\n");
663                         builder.append(getString(R.string.sources)).append("\n");
664                         for (final EntrySource source : dictionary.sources) {
665                             builder.append(
666                                     getString(R.string.sourceInfo, source.getName(),
667                                             source.getNumEntries())).append("\n");
668                         }
669                     }
670                     // } else {
671                     // builder.append(getString(R.string.invalidDictionary));
672                     // }
673                     textView.setText(builder.toString());
674
675                     dialog.show();
676                     final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
677                     layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
678                     layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
679                     dialog.getWindow().setAttributes(layoutParams);
680                     return false;
681                 }
682             });
683         }
684
685         return true;
686     }
687
688     // --------------------------------------------------------------------------
689     // Context Menu + clicks
690     // --------------------------------------------------------------------------
691
692     @Override
693     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
694         AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
695         final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
696
697         final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
698                 wordList.getName()));
699         addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
700             public boolean onMenuItemClick(MenuItem item) {
701                 onAppendToWordList(row);
702                 return false;
703             }
704         });
705
706         final MenuItem copy = menu.add(android.R.string.copy);
707         copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
708             public boolean onMenuItemClick(MenuItem item) {
709                 onCopy(row);
710                 return false;
711             }
712         });
713
714         if (selectedSpannableText != null) {
715             final String selectedText = selectedSpannableText;
716             final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
717                     selectedSpannableText));
718             searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
719                 public boolean onMenuItemClick(MenuItem item) {
720                     int indexToUse = -1;
721                     for (int i = 0; i < dictionary.indices.size(); ++i) {
722                         final Index index = dictionary.indices.get(i);
723                         if (indexPrepFinished) {
724                             System.out.println("Doing index lookup: on " + selectedText);
725                             final IndexEntry indexEntry = index.findExact(selectedText);
726                             if (indexEntry != null) {
727                                 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
728                                         .getTokenRow(false);
729                                 if (tokenRow != null && tokenRow.hasMainEntry) {
730                                     indexToUse = i;
731                                     break;
732                                 }
733                             }
734                         } else {
735                             Log.w(LOG, "Skipping findExact on index " + index.shortName);
736                         }
737                     }
738                     if (indexToUse == -1) {
739                         indexToUse = selectedSpannableIndex;
740                     }
741                     final boolean changeIndex = indexIndex != indexToUse;
742                     setSearchText(selectedText, !changeIndex); // If we're not
743                                                                // changing
744                                                                // index, we have
745                                                                // to
746                                                                // triggerSearch.
747                     if (changeIndex) {
748                         changeIndexGetFocusAndResearch(indexToUse);
749                     }
750                     // Give focus back to list view because typing is done.
751                     getListView().requestFocus();
752                     return false;
753                 }
754             });
755         }
756
757     }
758
759     @Override
760     protected void onListItemClick(ListView l, View v, int row, long id) {
761         defocusSearchText();
762         if (clickOpensContextMenu && dictRaf != null) {
763             openContextMenu(v);
764         }
765     }
766
767     void onAppendToWordList(final RowBase row) {
768         defocusSearchText();
769
770         final StringBuilder rawText = new StringBuilder();
771         rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
772         rawText.append(index.longName).append("\t");
773         rawText.append(row.getTokenRow(true).getToken()).append("\t");
774         rawText.append(row.getRawText(saveOnlyFirstSubentry));
775         Log.d(LOG, "Writing : " + rawText);
776
777         try {
778             wordList.getParentFile().mkdirs();
779             final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
780             out.println(rawText.toString());
781             out.close();
782         } catch (IOException e) {
783             Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
784             Toast.makeText(this,
785                     getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
786                     Toast.LENGTH_LONG).show();
787         }
788         return;
789     }
790
791     /**
792      * Called when user clicks outside of search text, so that they can start
793      * typing again immediately.
794      */
795     void defocusSearchText() {
796         // Log.d(LOG, "defocusSearchText");
797         // Request focus so that if we start typing again, it clears the text
798         // input.
799         getListView().requestFocus();
800
801         // Visual indication that a new keystroke will clear the search text.
802         searchText.selectAll();
803     }
804
805     @SuppressWarnings("deprecation")
806     void onCopy(final RowBase row) {
807         defocusSearchText();
808
809         Log.d(LOG, "Copy, row=" + row);
810         final StringBuilder result = new StringBuilder();
811         result.append(row.getRawText(false));
812         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
813         clipboardManager.setText(result.toString());
814         Log.d(LOG, "Copied: " + result);
815     }
816
817     @Override
818     public boolean onKeyDown(final int keyCode, final KeyEvent event) {
819         if (event.getUnicodeChar() != 0) {
820             if (!searchText.hasFocus()) {
821                 setSearchText("" + (char) event.getUnicodeChar(), true);
822             }
823             return true;
824         }
825         if (keyCode == KeyEvent.KEYCODE_BACK) {
826             // Log.d(LOG, "Clearing dictionary prefs.");
827             // Pretend that we just autolaunched so that we won't do it again.
828             // DictionaryManagerActivity.lastAutoLaunchMillis =
829             // System.currentTimeMillis();
830         }
831         if (keyCode == KeyEvent.KEYCODE_ENTER) {
832             Log.d(LOG, "Trying to hide soft keyboard.");
833             final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
834             inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
835                     InputMethodManager.HIDE_NOT_ALWAYS);
836             return true;
837         }
838         return super.onKeyDown(keyCode, event);
839     }
840
841     private void setSearchText(final String text, final boolean triggerSearch) {
842         if (!triggerSearch) {
843             getListView().requestFocus();
844         }
845         searchText.setText(text);
846         searchText.requestFocus();
847         moveCursorToRight();
848         if (triggerSearch) {
849             onSearchTextChange(text);
850         }
851     }
852
853     private long cursorDelayMillis = 100;
854
855     private void moveCursorToRight() {
856         if (searchText.getLayout() != null) {
857             cursorDelayMillis = 100;
858             // Surprising, but this can crash when you rotate...
859             Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
860         } else {
861             uiHandler.postDelayed(new Runnable() {
862                 @Override
863                 public void run() {
864                     moveCursorToRight();
865                 }
866             }, cursorDelayMillis);
867             cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
868         }
869     }
870
871     // --------------------------------------------------------------------------
872     // SearchOperation
873     // --------------------------------------------------------------------------
874
875     private void searchFinished(final SearchOperation searchOperation) {
876         if (searchOperation.interrupted.get()) {
877             Log.d(LOG, "Search operation was interrupted: " + searchOperation);
878             return;
879         }
880         if (searchOperation != this.currentSearchOperation) {
881             Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
882             return;
883         }
884
885         final Index.IndexEntry searchResult = searchOperation.searchResult;
886         Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
887
888         currentSearchOperation = null;
889         uiHandler.postDelayed(new Runnable() {
890             @Override
891             public void run() {
892                 if (currentSearchOperation == null) {
893                     if (searchResult != null) {
894                         if (isFiltered()) {
895                             clearFiltered();
896                         }
897                         jumpToRow(searchResult.startRow);
898                     } else if (searchOperation.multiWordSearchResult != null) {
899                         // Multi-row search....
900                         setFiltered(searchOperation);
901                     } else {
902                         throw new IllegalStateException("This should never happen.");
903                     }
904                 } else {
905                     Log.d(LOG, "More coming, waiting for currentSearchOperation.");
906                 }
907             }
908         }, 20);
909
910     }
911
912     private final void jumpToRow(final int row) {
913         setSelection(row);
914         getListView().setSelected(true);
915     }
916
917     static final Pattern WHITESPACE = Pattern.compile("\\s+");
918
919     final class SearchOperation implements Runnable {
920
921         final AtomicBoolean interrupted = new AtomicBoolean(false);
922
923         final String searchText;
924
925         List<String> searchTokens; // filled in for multiWord.
926
927         final Index index;
928
929         long searchStartMillis;
930
931         Index.IndexEntry searchResult;
932
933         List<RowBase> multiWordSearchResult;
934
935         boolean done = false;
936
937         SearchOperation(final String searchText, final Index index) {
938             this.searchText = searchText.trim();
939             this.index = index;
940         }
941
942         public String toString() {
943             return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
944         }
945
946         @Override
947         public void run() {
948             try {
949                 searchStartMillis = System.currentTimeMillis();
950                 final String[] searchTokenArray = WHITESPACE.split(searchText);
951                 if (searchTokenArray.length == 1) {
952                     searchResult = index.findInsertionPoint(searchText, interrupted);
953                 } else {
954                     searchTokens = Arrays.asList(searchTokenArray);
955                     multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
956                 }
957                 Log.d(LOG,
958                         "searchText=" + searchText + ", searchDuration="
959                                 + (System.currentTimeMillis() - searchStartMillis)
960                                 + ", interrupted=" + interrupted.get());
961                 if (!interrupted.get()) {
962                     uiHandler.post(new Runnable() {
963                         @Override
964                         public void run() {
965                             searchFinished(SearchOperation.this);
966                         }
967                     });
968                 }
969             } catch (Exception e) {
970                 Log.e(LOG, "Failure during search (can happen during Activity close.");
971             } finally {
972                 synchronized (this) {
973                     done = true;
974                     this.notifyAll();
975                 }
976             }
977         }
978     }
979
980     // --------------------------------------------------------------------------
981     // IndexAdapter
982     // --------------------------------------------------------------------------
983
984     static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
985             ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
986
987     static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
988             ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
989
990     final class IndexAdapter extends BaseAdapter {
991
992         private static final float PADDING_DEFAULT_DP = 8;
993
994         private static final float PADDING_LARGE_DP = 16;
995
996         final Index index;
997
998         final List<RowBase> rows;
999
1000         final Set<String> toHighlight;
1001
1002         private int mPaddingDefault;
1003
1004         private int mPaddingLarge;
1005
1006         IndexAdapter(final Index index) {
1007             this.index = index;
1008             rows = index.rows;
1009             this.toHighlight = null;
1010             getMetrics();
1011         }
1012
1013         IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1014             this.index = index;
1015             this.rows = rows;
1016             this.toHighlight = new LinkedHashSet<String>(toHighlight);
1017             getMetrics();
1018         }
1019
1020         private void getMetrics() {
1021             // Get the screen's density scale
1022             final float scale = getResources().getDisplayMetrics().density;
1023             // Convert the dps to pixels, based on density scale
1024             mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1025             mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1026         }
1027
1028         @Override
1029         public int getCount() {
1030             return rows.size();
1031         }
1032
1033         @Override
1034         public RowBase getItem(int position) {
1035             return rows.get(position);
1036         }
1037
1038         @Override
1039         public long getItemId(int position) {
1040             return getItem(position).index();
1041         }
1042
1043         @Override
1044         public TableLayout getView(int position, View convertView, ViewGroup parent) {
1045             final TableLayout result;
1046             if (convertView instanceof TableLayout) {
1047                 result = (TableLayout) convertView;
1048                 result.removeAllViews();
1049             } else {
1050                 result = new TableLayout(parent.getContext());
1051             }
1052             final RowBase row = getItem(position);
1053             if (row instanceof PairEntry.Row) {
1054                 return getView(position, (PairEntry.Row) row, parent, result);
1055             } else if (row instanceof TokenRow) {
1056                 return getView((TokenRow) row, parent, result);
1057             } else if (row instanceof HtmlEntry.Row) {
1058                 return getView((HtmlEntry.Row) row, parent, result);
1059             } else {
1060                 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1061             }
1062         }
1063
1064         private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1065                 final TableLayout result) {
1066             final PairEntry entry = row.getEntry();
1067             final int rowCount = entry.pairs.size();
1068
1069             final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1070             layoutParams.weight = 0.5f;
1071             layoutParams.leftMargin = mPaddingLarge;
1072
1073             for (int r = 0; r < rowCount; ++r) {
1074                 final TableRow tableRow = new TableRow(result.getContext());
1075
1076                 final TextView col1 = new TextView(tableRow.getContext());
1077                 final TextView col2 = new TextView(tableRow.getContext());
1078
1079                 // Set the columns in the table.
1080                 if (r > 0) {
1081                     final TextView bullet = new TextView(tableRow.getContext());
1082                     bullet.setText(" â€¢ ");
1083                     tableRow.addView(bullet);
1084                 }
1085                 tableRow.addView(col1, layoutParams);
1086                 final TextView margin = new TextView(tableRow.getContext());
1087                 margin.setText(" ");
1088                 tableRow.addView(margin);
1089                 if (r > 0) {
1090                     final TextView bullet = new TextView(tableRow.getContext());
1091                     bullet.setText(" â€¢ ");
1092                     tableRow.addView(bullet);
1093                 }
1094                 tableRow.addView(col2, layoutParams);
1095                 col1.setWidth(1);
1096                 col2.setWidth(1);
1097
1098                 // Set what's in the columns.
1099
1100                 final Pair pair = entry.pairs.get(r);
1101                 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1102                 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1103
1104                 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1105                 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1106
1107                 // Bold the token instances in col1.
1108                 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1109                         .singleton(row.getTokenRow(true).getToken());
1110                 final Spannable col1Spannable = (Spannable) col1.getText();
1111                 for (final String token : toBold) {
1112                     int startPos = 0;
1113                     while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1114                         col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1115                                 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1116                         startPos += token.length();
1117                     }
1118                 }
1119
1120                 createTokenLinkSpans(col1, col1Spannable, col1Text);
1121                 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1122
1123                 col1.setTypeface(typeface);
1124                 col2.setTypeface(typeface);
1125                 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1126                 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1127                 // col2.setBackgroundResource(theme.otherLangBg);
1128
1129                 if (index.swapPairEntries) {
1130                     col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1131                     col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1132                 } else {
1133                     col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1134                     col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1135                 }
1136
1137                 result.addView(tableRow);
1138             }
1139
1140             // Because we have a Button inside a ListView row:
1141             // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1142             result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1143             result.setClickable(true);
1144             result.setFocusable(true);
1145             result.setLongClickable(true);
1146             result.setBackgroundResource(android.R.drawable.menuitem_background);
1147             result.setOnClickListener(new TextView.OnClickListener() {
1148                 @Override
1149                 public void onClick(View v) {
1150                     DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1151                 }
1152             });
1153
1154             return result;
1155         }
1156
1157         private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1158             final Context context = parent.getContext();
1159
1160             final HtmlEntry htmlEntry = row.getEntry();
1161
1162             // final TableRow tableRow = new TableRow(context);
1163             final LinearLayout tableRow = new LinearLayout(context);
1164             result.addView(tableRow);
1165
1166             // Text.
1167             final TextView textView = new TextView(context);
1168             textView.setText(htmlEntry.title);
1169             textView.setLayoutParams(new LinearLayout.LayoutParams(0,
1170                     ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
1171             tableRow.addView(textView);
1172
1173             // Button.
1174             final Button button = new Button(context);
1175             button.setText("open");
1176             button.setLayoutParams(new LinearLayout.LayoutParams(
1177                     ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.0f));
1178             tableRow.addView(button);
1179
1180             button.setOnClickListener(new OnClickListener() {
1181                 @Override
1182                 public void onClick(View v) {
1183                     startActivity(HtmlDisplayActivity.getHtmlIntent(String.format(
1184                             "<html><head></head><body>%s</body></html>", htmlEntry.html)));
1185                 }
1186             });
1187
1188             return result;
1189         }
1190
1191         private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1192             final Context context = parent.getContext();
1193             final TextView textView = new TextView(context);
1194             textView.setText(row.getToken());
1195             // Doesn't work:
1196             // textView.setTextColor(android.R.color.secondary_text_light);
1197             textView.setTextAppearance(context, theme.tokenRowFg);
1198             textView.setTypeface(typeface);
1199             textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
1200
1201             final TableRow tableRow = new TableRow(result.getContext());
1202             tableRow.addView(textView);
1203             tableRow.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg
1204                     : theme.tokenRowOtherBg);
1205             tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1206             result.addView(tableRow);
1207             return result;
1208         }
1209
1210     }
1211
1212     static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1213
1214     private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1215             final String text) {
1216         // Saw from the source code that LinkMovementMethod sets the selection!
1217         // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1218         textView.setMovementMethod(LinkMovementMethod.getInstance());
1219         final Matcher matcher = CHAR_DASH.matcher(text);
1220         while (matcher.find()) {
1221             spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(),
1222                     Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1223         }
1224     }
1225
1226     String selectedSpannableText = null;
1227
1228     int selectedSpannableIndex = -1;
1229
1230     @Override
1231     public boolean onTouchEvent(MotionEvent event) {
1232         selectedSpannableText = null;
1233         selectedSpannableIndex = -1;
1234         return super.onTouchEvent(event);
1235     }
1236
1237     private class TextViewLongClickListener implements OnLongClickListener {
1238         final int index;
1239
1240         private TextViewLongClickListener(final int index) {
1241             this.index = index;
1242         }
1243
1244         @Override
1245         public boolean onLongClick(final View v) {
1246             final TextView textView = (TextView) v;
1247             final int start = textView.getSelectionStart();
1248             final int end = textView.getSelectionEnd();
1249             if (start >= 0 && end >= 0) {
1250                 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1251                 selectedSpannableIndex = index;
1252             }
1253             return false;
1254         }
1255     }
1256
1257     final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1258             0);
1259
1260     final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1261             1);
1262
1263     // --------------------------------------------------------------------------
1264     // SearchText
1265     // --------------------------------------------------------------------------
1266
1267     void onSearchTextChange(final String text) {
1268         if ("thadolina".equals(text)) {
1269             final Dialog dialog = new Dialog(getListView().getContext());
1270             dialog.setContentView(R.layout.thadolina_dialog);
1271             dialog.setTitle("Ti amo, amore mio!");
1272             final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1273             imageView.setOnClickListener(new OnClickListener() {
1274                 @Override
1275                 public void onClick(View v) {
1276                     final Intent intent = new Intent(Intent.ACTION_VIEW);
1277                     intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1278                     startActivity(intent);
1279                 }
1280             });
1281             dialog.show();
1282         }
1283         if (dictRaf == null) {
1284             Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1285             return;
1286         }
1287         if (!searchText.isFocused()) {
1288             Log.d(LOG, "searchText changed without focus, doing nothing.");
1289             return;
1290         }
1291         Log.d(LOG, "onSearchTextChange: " + text);
1292         if (currentSearchOperation != null) {
1293             Log.d(LOG, "Interrupting currentSearchOperation.");
1294             currentSearchOperation.interrupted.set(true);
1295         }
1296         currentSearchOperation = new SearchOperation(text, index);
1297         searchExecutor.execute(currentSearchOperation);
1298     }
1299
1300     private class SearchTextWatcher implements TextWatcher {
1301         public void afterTextChanged(final Editable searchTextEditable) {
1302             if (searchText.hasFocus()) {
1303                 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
1304                 // If they were typing to cause the change, update the UI.
1305                 onSearchTextChange(searchText.getText().toString());
1306             }
1307         }
1308
1309         public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1310         }
1311
1312         public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1313         }
1314     }
1315
1316     // --------------------------------------------------------------------------
1317     // Filtered results.
1318     // --------------------------------------------------------------------------
1319
1320     boolean isFiltered() {
1321         return rowsToShow != null;
1322     }
1323
1324     void setFiltered(final SearchOperation searchOperation) {
1325         ((Button) findViewById(R.id.UpButton)).setEnabled(false);
1326         ((Button) findViewById(R.id.DownButton)).setEnabled(false);
1327         rowsToShow = searchOperation.multiWordSearchResult;
1328         setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1329     }
1330
1331     void clearFiltered() {
1332         ((Button) findViewById(R.id.UpButton)).setEnabled(true);
1333         ((Button) findViewById(R.id.DownButton)).setEnabled(true);
1334         setListAdapter(new IndexAdapter(index));
1335         rowsToShow = null;
1336     }
1337
1338 }