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