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