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