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