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