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