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