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