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