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