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