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