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