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