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