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