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