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