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