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