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