]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryActivity.java
Add code to speak full left/right side entries.
[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         if (row instanceof PairEntry.Row && ttsReady) {
1079             final List<Pair> pairs = ((PairEntry.Row)row).getEntry().pairs;
1080             final MenuItem speakLeft = menu.add(R.string.speak_left);
1081             speakLeft.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1082                 @Override
1083                 public boolean onMenuItemClick(android.view.MenuItem item) {
1084                     int idx = index.swapPairEntries ? 1 : 0;
1085                     updateTTSLanguage(idx);
1086                     String text = "";
1087                     for (Pair p : pairs) text += p.get(idx);
1088                     text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1089                     textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
1090                                        new HashMap<String, String>());
1091                     return false;
1092                 }
1093             });
1094             final MenuItem speakRight = menu.add(R.string.speak_right);
1095             speakRight.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1096                 @Override
1097                 public boolean onMenuItemClick(android.view.MenuItem item) {
1098                     int idx = index.swapPairEntries ? 0 : 1;
1099                     updateTTSLanguage(idx);
1100                     String text = "";
1101                     for (Pair p : pairs) text += p.get(idx);
1102                     text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1103                     textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
1104                                        new HashMap<String, String>());
1105                     return false;
1106                 }
1107             });
1108         }
1109     }
1110
1111     private void jumpToTextFromHyperLink(
1112         final String selectedText, final int defaultIndexToUse) {
1113         int indexToUse = -1;
1114         int numFound = 0;
1115         for (int i = 0; i < dictionary.indices.size(); ++i) {
1116             final Index index = dictionary.indices.get(i);
1117             if (indexPrepFinished) {
1118                 System.out.println("Doing index lookup: on " + selectedText);
1119                 final IndexEntry indexEntry = index.findExact(selectedText);
1120                 if (indexEntry != null) {
1121                     final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1122                                               .getTokenRow(false);
1123                     if (tokenRow != null && tokenRow.hasMainEntry) {
1124                         indexToUse = i;
1125                         ++numFound;
1126                     }
1127                 }
1128             } else {
1129                 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1130             }
1131         }
1132         if (numFound != 1 || indexToUse == -1) {
1133             indexToUse = defaultIndexToUse;
1134         }
1135         // Without this extra delay, the call to jumpToRow that this
1136         // invokes doesn't always actually have any effect.
1137         final int actualIndexToUse = indexToUse;
1138         getListView().postDelayed(new Runnable() {
1139             @Override
1140             public void run() {
1141                 setIndexAndSearchText(actualIndexToUse, selectedText, true);
1142             }
1143         }, 100);
1144     }
1145
1146     /**
1147      * Called when user clicks outside of search text, so that they can start
1148      * typing again immediately.
1149      */
1150     void defocusSearchText() {
1151         // Log.d(LOG, "defocusSearchText");
1152         // Request focus so that if we start typing again, it clears the text
1153         // input.
1154         getListView().requestFocus();
1155
1156         // Visual indication that a new keystroke will clear the search text.
1157         // Doesn't seem to work unless searchText has focus.
1158         // searchView.selectAll();
1159     }
1160
1161     protected void onListItemClick(ListView l, View v, int row, long id) {
1162         defocusSearchText();
1163         if (clickOpensContextMenu && dictRaf != null) {
1164             openContextMenu(v);
1165         }
1166     }
1167
1168     @SuppressLint("SimpleDateFormat")
1169     void onAppendToWordList(final RowBase row) {
1170         defocusSearchText();
1171
1172         final StringBuilder rawText = new StringBuilder();
1173         rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1174         rawText.append(index.longName).append("\t");
1175         rawText.append(row.getTokenRow(true).getToken()).append("\t");
1176         rawText.append(row.getRawText(saveOnlyFirstSubentry));
1177         Log.d(LOG, "Writing : " + rawText);
1178
1179         try {
1180             wordList.getParentFile().mkdirs();
1181             final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1182             out.println(rawText.toString());
1183             out.close();
1184         } catch (Exception e) {
1185             Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1186             Toast.makeText(this,
1187                            getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1188                            Toast.LENGTH_LONG).show();
1189         }
1190         return;
1191     }
1192
1193     @SuppressWarnings("deprecation")
1194     void onCopy(final RowBase row) {
1195         defocusSearchText();
1196
1197         Log.d(LOG, "Copy, row=" + row);
1198         final StringBuilder result = new StringBuilder();
1199         result.append(row.getRawText(false));
1200         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1201         clipboardManager.setText(result.toString());
1202         Log.d(LOG, "Copied: " + result);
1203     }
1204
1205     @Override
1206     public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1207         if (event.getUnicodeChar() != 0) {
1208             if (!searchView.hasFocus()) {
1209                 setSearchText("" + (char) event.getUnicodeChar(), true);
1210                 searchView.requestFocus();
1211             }
1212             return true;
1213         }
1214         if (keyCode == KeyEvent.KEYCODE_BACK) {
1215             // Log.d(LOG, "Clearing dictionary prefs.");
1216             // Pretend that we just autolaunched so that we won't do it again.
1217             // DictionaryManagerActivity.lastAutoLaunchMillis =
1218             // System.currentTimeMillis();
1219         }
1220         if (keyCode == KeyEvent.KEYCODE_ENTER) {
1221             Log.d(LOG, "Trying to hide soft keyboard.");
1222             final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1223             View focus = getCurrentFocus();
1224             if (focus != null) {
1225                 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1226                                                      InputMethodManager.HIDE_NOT_ALWAYS);
1227             }
1228             return true;
1229         }
1230         return super.onKeyDown(keyCode, event);
1231     }
1232
1233     private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
1234         Log.d(LOG, "Changing index to: " + newIndex);
1235         if (newIndex == -1) {
1236             Log.e(LOG, "Invalid index.");
1237             newIndex = 0;
1238         }
1239         if (newIndex != indexIndex) {
1240             indexIndex = newIndex;
1241             index = dictionary.indices.get(indexIndex);
1242             indexAdapter = new IndexAdapter(index);
1243             setListAdapter(indexAdapter);
1244             Log.d(LOG, "changingIndex, newLang=" + index.longName);
1245             setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1246             updateLangButton();
1247         }
1248         setSearchText(newSearchText, true, hideKeyboard);
1249     }
1250
1251     private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
1252         Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1253         // Disable the listener, because sometimes it doesn't work.
1254         searchView.setOnQueryTextListener(null);
1255         searchView.setQuery(text, false);
1256         moveCursorToRight();
1257         searchView.setOnQueryTextListener(onQueryTextListener);
1258
1259         if (triggerSearch) {
1260             onSearchTextChange(text);
1261         }
1262
1263         // We don't want to show virtual keyboard when we're changing searchView text programatically:
1264         if (hideKeyboard) {
1265             hideKeyboard();
1266         }
1267     }
1268
1269     private void setSearchText(final String text, final boolean triggerSearch) {
1270         setSearchText(text, triggerSearch, true);
1271     }
1272
1273     // private long cursorDelayMillis = 100;
1274     private void moveCursorToRight() {
1275         // if (searchText.getLayout() != null) {
1276         // cursorDelayMillis = 100;
1277         // // Surprising, but this can crash when you rotate...
1278         // Selection.moveToRightEdge(searchView.getQuery(),
1279         // searchText.getLayout());
1280         // } else {
1281         // uiHandler.postDelayed(new Runnable() {
1282         // @Override
1283         // public void run() {
1284         // moveCursorToRight();
1285         // }
1286         // }, cursorDelayMillis);
1287         // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1288         // }
1289     }
1290
1291     // --------------------------------------------------------------------------
1292     // SearchOperation
1293     // --------------------------------------------------------------------------
1294
1295     private void searchFinished(final SearchOperation searchOperation) {
1296         if (searchOperation.interrupted.get()) {
1297             Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1298             return;
1299         }
1300         if (searchOperation != this.currentSearchOperation) {
1301             Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1302             return;
1303         }
1304
1305         final Index.IndexEntry searchResult = searchOperation.searchResult;
1306         Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1307
1308         currentSearchOperation = null;
1309         uiHandler.postDelayed(new Runnable() {
1310             @Override
1311             public void run() {
1312                 if (currentSearchOperation == null) {
1313                     if (searchResult != null) {
1314                         if (isFiltered()) {
1315                             clearFiltered();
1316                         }
1317                         jumpToRow(searchResult.startRow);
1318                     } else if (searchOperation.multiWordSearchResult != null) {
1319                         // Multi-row search....
1320                         setFiltered(searchOperation);
1321                     } else {
1322                         throw new IllegalStateException("This should never happen.");
1323                     }
1324                 } else {
1325                     Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1326                 }
1327             }
1328         }, 20);
1329     }
1330
1331     private final void jumpToRow(final int row) {
1332         Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1333         // getListView().requestFocusFromTouch();
1334         getListView().setSelectionFromTop(row, 0);
1335         getListView().setSelected(true);
1336     }
1337
1338     static final Pattern WHITESPACE = Pattern.compile("\\s+");
1339
1340     final class SearchOperation implements Runnable {
1341
1342         final AtomicBoolean interrupted = new AtomicBoolean(false);
1343
1344         final String searchText;
1345
1346         List<String> searchTokens; // filled in for multiWord.
1347
1348         final Index index;
1349
1350         long searchStartMillis;
1351
1352         Index.IndexEntry searchResult;
1353
1354         List<RowBase> multiWordSearchResult;
1355
1356         boolean done = false;
1357
1358         SearchOperation(final String searchText, final Index index) {
1359             this.searchText = StringUtil.normalizeWhitespace(searchText);
1360             this.index = index;
1361         }
1362
1363         public String toString() {
1364             return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1365         }
1366
1367         @Override
1368         public void run() {
1369             try {
1370                 searchStartMillis = System.currentTimeMillis();
1371                 final String[] searchTokenArray = WHITESPACE.split(searchText);
1372                 if (searchTokenArray.length == 1) {
1373                     searchResult = index.findInsertionPoint(searchText, interrupted);
1374                 } else {
1375                     searchTokens = Arrays.asList(searchTokenArray);
1376                     multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1377                                             interrupted);
1378                 }
1379                 Log.d(LOG,
1380                       "searchText=" + searchText + ", searchDuration="
1381                       + (System.currentTimeMillis() - searchStartMillis)
1382                       + ", interrupted=" + interrupted.get());
1383                 if (!interrupted.get()) {
1384                     uiHandler.post(new Runnable() {
1385                         @Override
1386                         public void run() {
1387                             searchFinished(SearchOperation.this);
1388                         }
1389                     });
1390                 } else {
1391                     Log.d(LOG, "interrupted, skipping searchFinished.");
1392                 }
1393             } catch (Exception e) {
1394                 Log.e(LOG, "Failure during search (can happen during Activity close.");
1395             } finally {
1396                 synchronized (this) {
1397                     done = true;
1398                     this.notifyAll();
1399                 }
1400             }
1401         }
1402     }
1403
1404     // --------------------------------------------------------------------------
1405     // IndexAdapter
1406     // --------------------------------------------------------------------------
1407
1408     static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1409         ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1410
1411     static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1412         ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1413
1414     final class IndexAdapter extends BaseAdapter {
1415
1416         private static final float PADDING_DEFAULT_DP = 8;
1417
1418         private static final float PADDING_LARGE_DP = 16;
1419
1420         final Index index;
1421
1422         final List<RowBase> rows;
1423
1424         final Set<String> toHighlight;
1425
1426         private int mPaddingDefault;
1427
1428         private int mPaddingLarge;
1429
1430         IndexAdapter(final Index index) {
1431             this.index = index;
1432             rows = index.rows;
1433             this.toHighlight = null;
1434             getMetrics();
1435         }
1436
1437         IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1438             this.index = index;
1439             this.rows = rows;
1440             this.toHighlight = new LinkedHashSet<String>(toHighlight);
1441             getMetrics();
1442         }
1443
1444         private void getMetrics() {
1445             // Get the screen's density scale
1446             final float scale = getResources().getDisplayMetrics().density;
1447             // Convert the dps to pixels, based on density scale
1448             mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1449             mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1450         }
1451
1452         @Override
1453         public int getCount() {
1454             return rows.size();
1455         }
1456
1457         @Override
1458         public RowBase getItem(int position) {
1459             return rows.get(position);
1460         }
1461
1462         @Override
1463         public long getItemId(int position) {
1464             return getItem(position).index();
1465         }
1466
1467         @Override
1468         public TableLayout getView(int position, View convertView, ViewGroup parent) {
1469             final TableLayout result;
1470             if (convertView instanceof TableLayout) {
1471                 result = (TableLayout) convertView;
1472                 result.removeAllViews();
1473             } else {
1474                 result = new TableLayout(parent.getContext());
1475             }
1476             final RowBase row = getItem(position);
1477             if (row instanceof PairEntry.Row) {
1478                 return getView(position, (PairEntry.Row) row, parent, result);
1479             } else if (row instanceof TokenRow) {
1480                 return getView((TokenRow) row, parent, result);
1481             } else if (row instanceof HtmlEntry.Row) {
1482                 return getView((HtmlEntry.Row) row, parent, result);
1483             } else {
1484                 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1485             }
1486         }
1487
1488         private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1489                                     final TableLayout result) {
1490             final PairEntry entry = row.getEntry();
1491             final int rowCount = entry.pairs.size();
1492
1493             final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1494             layoutParams.weight = 0.5f;
1495             layoutParams.leftMargin = mPaddingLarge;
1496
1497             for (int r = 0; r < rowCount; ++r) {
1498                 final TableRow tableRow = new TableRow(result.getContext());
1499
1500                 final TextView col1 = new TextView(tableRow.getContext());
1501                 final TextView col2 = new TextView(tableRow.getContext());
1502                 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1503                     col1.setTextIsSelectable(true);
1504                     col2.setTextIsSelectable(true);
1505                 }
1506
1507                 // Set the columns in the table.
1508                 if (r > 0) {
1509                     final TextView bullet = new TextView(tableRow.getContext());
1510                     bullet.setText(" • ");
1511                     tableRow.addView(bullet);
1512                 }
1513                 tableRow.addView(col1, layoutParams);
1514                 final TextView margin = new TextView(tableRow.getContext());
1515                 margin.setText(" ");
1516                 tableRow.addView(margin);
1517                 if (r > 0) {
1518                     final TextView bullet = new TextView(tableRow.getContext());
1519                     bullet.setText(" • ");
1520                     tableRow.addView(bullet);
1521                 }
1522                 tableRow.addView(col2, layoutParams);
1523                 col1.setWidth(1);
1524                 col2.setWidth(1);
1525
1526                 // Set what's in the columns.
1527
1528                 final Pair pair = entry.pairs.get(r);
1529                 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1530                 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1531
1532                 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1533                 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1534
1535                 // Bold the token instances in col1.
1536                 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1537                                            .singleton(row.getTokenRow(true).getToken());
1538                 final Spannable col1Spannable = (Spannable) col1.getText();
1539                 for (final String token : toBold) {
1540                     int startPos = 0;
1541                     while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1542                         col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1543                                               + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1544                         startPos += token.length();
1545                     }
1546                 }
1547
1548                 createTokenLinkSpans(col1, col1Spannable, col1Text);
1549                 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1550
1551                 col1.setTypeface(typeface);
1552                 col2.setTypeface(typeface);
1553                 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1554                 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1555                 // col2.setBackgroundResource(theme.otherLangBg);
1556
1557                 if (index.swapPairEntries) {
1558                     col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1559                     col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1560                 } else {
1561                     col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1562                     col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1563                 }
1564
1565                 result.addView(tableRow);
1566             }
1567
1568             // Because we have a Button inside a ListView row:
1569             // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1570             result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1571             result.setClickable(true);
1572             result.setFocusable(true);
1573             result.setLongClickable(true);
1574 //            result.setBackgroundResource(android.R.drawable.menuitem_background);
1575
1576             result.setBackgroundResource(theme.normalRowBg);
1577
1578             result.setOnClickListener(new TextView.OnClickListener() {
1579                 @Override
1580                 public void onClick(View v) {
1581                     DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1582                 }
1583             });
1584
1585             return result;
1586         }
1587
1588         private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1589                 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1590                 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1591             final Context context = parent.getContext();
1592
1593             final TableRow tableRow = new TableRow(result.getContext());
1594             tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1595                                            : theme.tokenRowOtherBg);
1596             if (isTokenRow) {
1597                 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1598             } else {
1599                 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1600             }
1601             result.addView(tableRow);
1602
1603             // Make it so we can long-click on these token rows, too:
1604             final TextView textView = new TextView(context);
1605             textView.setText(text, BufferType.SPANNABLE);
1606             createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1607             textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1608             result.setLongClickable(true);
1609
1610             // Doesn't work:
1611             // textView.setTextColor(android.R.color.secondary_text_light);
1612             textView.setTypeface(typeface);
1613             TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1614             if (isTokenRow) {
1615                 textView.setTextAppearance(context, theme.tokenRowFg);
1616                 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1617             } else {
1618                 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1619             }
1620             lp.weight = 1.0f;
1621
1622             textView.setLayoutParams(lp);
1623             tableRow.addView(textView);
1624
1625             if (!htmlEntries.isEmpty()) {
1626                 final ClickableSpan clickableSpan = new ClickableSpan() {
1627                     @Override
1628                     public void onClick(View widget) {
1629                     }
1630                 };
1631                 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1632                         Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1633                 result.setClickable(true);
1634                 textView.setClickable(true);
1635                 textView.setMovementMethod(LinkMovementMethod.getInstance());
1636                 textView.setOnClickListener(new OnClickListener() {
1637                     @Override
1638                     public void onClick(View v) {
1639                         String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1640                         // Log.d(LOG, "html=" + html);
1641                         startActivityForResult(
1642                             HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1643                                     "<html><head></head><body>%s</body></html>", html),
1644                                                               htmlTextToHighlight, false),
1645                             0);
1646                     }
1647                 });
1648             }
1649             return result;
1650         }
1651
1652         private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1653             final IndexEntry indexEntry = row.getIndexEntry();
1654             return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1655                                                   indexEntry.htmlEntries, null, parent, result);
1656         }
1657
1658         private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1659             final HtmlEntry htmlEntry = row.getEntry();
1660             final TokenRow tokenRow = row.getTokenRow(true);
1661             return getPossibleLinkToHtmlEntryView(false,
1662                                                   getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1663                                                   false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1664                                                   result);
1665         }
1666
1667     }
1668
1669     static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1670
1671     private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1672                                       final String text) {
1673         // Saw from the source code that LinkMovementMethod sets the selection!
1674         // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1675         textView.setMovementMethod(LinkMovementMethod.getInstance());
1676         final Matcher matcher = CHAR_DASH.matcher(text);
1677         while (matcher.find()) {
1678             spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1679                               matcher.end(),
1680                               Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1681         }
1682     }
1683
1684     String selectedSpannableText = null;
1685
1686     int selectedSpannableIndex = -1;
1687
1688     @Override
1689     public boolean onTouchEvent(MotionEvent event) {
1690         selectedSpannableText = null;
1691         selectedSpannableIndex = -1;
1692         return super.onTouchEvent(event);
1693     }
1694
1695     private class TextViewLongClickListener implements OnLongClickListener {
1696         final int index;
1697
1698         private TextViewLongClickListener(final int index) {
1699             this.index = index;
1700         }
1701
1702         @Override
1703         public boolean onLongClick(final View v) {
1704             final TextView textView = (TextView) v;
1705             final int start = textView.getSelectionStart();
1706             final int end = textView.getSelectionEnd();
1707             if (start >= 0 && end >= 0) {
1708                 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1709                 selectedSpannableIndex = index;
1710             }
1711             return false;
1712         }
1713     }
1714
1715     final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1716         0);
1717
1718     final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1719         1);
1720
1721     // --------------------------------------------------------------------------
1722     // SearchText
1723     // --------------------------------------------------------------------------
1724
1725     void onSearchTextChange(final String text) {
1726         if ("thadolina".equals(text)) {
1727             final Dialog dialog = new Dialog(getListView().getContext());
1728             dialog.setContentView(R.layout.thadolina_dialog);
1729             dialog.setTitle("Ti amo, amore mio!");
1730             final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1731             imageView.setOnClickListener(new OnClickListener() {
1732                 @Override
1733                 public void onClick(View v) {
1734                     final Intent intent = new Intent(Intent.ACTION_VIEW);
1735                     intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1736                     startActivity(intent);
1737                 }
1738             });
1739             dialog.show();
1740         }
1741         if (dictRaf == null) {
1742             Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1743             return;
1744         }
1745
1746         // if (!searchView.hasFocus()) {
1747         // Log.d(LOG, "searchText changed without focus, doing nothing.");
1748         // return;
1749         // }
1750         Log.d(LOG, "onSearchTextChange: " + text);
1751         if (currentSearchOperation != null) {
1752             Log.d(LOG, "Interrupting currentSearchOperation.");
1753             currentSearchOperation.interrupted.set(true);
1754         }
1755         currentSearchOperation = new SearchOperation(text, index);
1756         searchExecutor.execute(currentSearchOperation);
1757         ((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
1758     }
1759
1760     // --------------------------------------------------------------------------
1761     // Filtered results.
1762     // --------------------------------------------------------------------------
1763
1764     boolean isFiltered() {
1765         return rowsToShow != null;
1766     }
1767
1768     void setFiltered(final SearchOperation searchOperation) {
1769         if (nextWordMenuItem != null) {
1770             nextWordMenuItem.setEnabled(false);
1771             previousWordMenuItem.setEnabled(false);
1772         }
1773         rowsToShow = searchOperation.multiWordSearchResult;
1774         setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1775     }
1776
1777     void clearFiltered() {
1778         if (nextWordMenuItem != null) {
1779             nextWordMenuItem.setEnabled(true);
1780             previousWordMenuItem.setEnabled(true);
1781         }
1782         setListAdapter(new IndexAdapter(index));
1783         rowsToShow = null;
1784     }
1785
1786 }