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