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