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