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