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