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