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