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