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