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