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