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