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