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