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