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