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