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