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