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