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