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