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