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