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