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