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