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