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