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