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