]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryActivity.java
Update name in acknowledgments.
[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 = new File(prefs.getString(getString(R.string.wordListFileKey),
417                 new File(application.getDictDir(), "wordList.txt").getAbsolutePath()));
418         saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
419                 false);
420         clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
421                 false);
422         Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
423
424         onCreateSetupActionBarAndSearchView();
425
426         // Set the search text from the intent, then the saved state.
427         String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
428         if (savedInstanceState != null) {
429             text = savedInstanceState.getString(C.SEARCH_TOKEN);
430         }
431         if (text == null) {
432             text = "";
433         }
434         setSearchText(text, true);
435         Log.d(LOG, "Trying to restore searchText=" + text);
436
437         setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
438
439         updateLangButton();
440         searchView.requestFocus();
441
442         // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
443         getListView().setCacheColorHint(0);
444     }
445
446     private void onCreateSetupActionBarAndSearchView() {
447         ActionBar actionBar = getSupportActionBar();
448         actionBar.setDisplayShowTitleEnabled(false);
449         actionBar.setDisplayShowHomeEnabled(false);
450         actionBar.setDisplayHomeAsUpEnabled(false);
451         
452         final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
453         
454         final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
455                 getResources().getDisplayMetrics());
456         final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
457                 width, ViewGroup.LayoutParams.WRAP_CONTENT);
458         customSearchView.setLayoutParams(layoutParams);
459
460         languageButton = new ImageButton(customSearchView.getContext());
461         languageButton.setMinimumWidth(application.languageButtonPixels);
462         languageButton.setMinimumHeight(application.languageButtonPixels * 2 / 3);
463         languageButton.setScaleType(ScaleType.FIT_CENTER);
464         languageButton.setOnClickListener(new OnClickListener() {
465             @Override
466             public void onClick(View arg0) {
467                 onLanguageButtonClick();
468             }
469         });
470         languageButton.setOnLongClickListener(new OnLongClickListener() {
471             @Override
472             public boolean onLongClick(View v) {
473                 onLanguageButtonLongClick(v.getContext());
474                 return true;
475             }
476         });
477         customSearchView.addView(languageButton);
478
479         searchView = new SearchView(customSearchView.getContext());
480         searchView.setIconifiedByDefault(false);
481         // searchView.setIconified(false); // puts the magnifying glass in the
482         // wrong place.
483         searchView.setQueryHint(getString(R.string.searchText));
484         searchView.setSubmitButtonEnabled(false);
485         LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
486                 FrameLayout.LayoutParams.WRAP_CONTENT);
487         lp.weight = 1;
488         searchView.setLayoutParams(lp);
489         searchView.setImeOptions(
490                 EditorInfo.IME_ACTION_SEARCH |
491                         EditorInfo.IME_FLAG_NO_EXTRACT_UI |
492                         EditorInfo.IME_FLAG_NO_ENTER_ACTION |
493                         // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
494                         // 11
495                         EditorInfo.IME_MASK_ACTION |
496                         EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
497         onQueryTextListener = new OnQueryTextListener() {
498             @Override
499             public boolean onQueryTextSubmit(String query) {
500                 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
501                 return true;
502             }
503
504             @Override
505             public boolean onQueryTextChange(String newText) {
506                 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
507                 onSearchTextChange(searchView.getQuery().toString());
508                 return true;
509             }
510         };
511         searchView.setOnQueryTextListener(onQueryTextListener);
512         searchView.setFocusable(true);
513         customSearchView.addView(searchView);
514
515         // Clear the searchHint icon so that it takes as little space as possible.
516         ImageView searchHintIcon = (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
517         searchHintIcon.setBackgroundResource(android.R.color.transparent);
518         searchHintIcon.setLayoutParams(new LinearLayout.LayoutParams(1, 1));
519         searchHintIcon.setAdjustViewBounds(true);
520         searchHintIcon.setPadding(0, 0, 0, 0);
521         
522         actionBar.setCustomView(customSearchView);
523         actionBar.setDisplayShowCustomEnabled(true);
524     }
525
526     @Override
527     protected void onResume() {
528         Log.d(LOG, "onResume");
529         super.onResume();
530         if (PreferenceActivity.prefsMightHaveChanged) {
531             PreferenceActivity.prefsMightHaveChanged = false;
532             finish();
533             startActivity(getIntent());
534         }
535         showKeyboard();
536     }
537
538     @Override
539     protected void onPause() {
540         super.onPause();
541     }
542
543     @Override
544     /**
545      * Invoked when MyWebView returns, since the user might have clicked some
546      * hypertext in the MyWebView.
547      */
548     protected void onActivityResult(int requestCode, int resultCode, Intent result) {
549         super.onActivityResult(requestCode, resultCode, result);
550         if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
551             Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
552             jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
553         }
554     }
555
556     private static void setDictionaryPrefs(final Context context, final File dictFile,
557             final String indexShortName, final String searchToken) {
558         final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
559                 context).edit();
560         prefs.putString(C.DICT_FILE, dictFile.getPath());
561         prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
562         prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
563         prefs.commit();
564     }
565
566     @Override
567     protected void onDestroy() {
568         super.onDestroy();
569         if (dictRaf == null) {
570             return;
571         }
572
573         final SearchOperation searchOperation = currentSearchOperation;
574         currentSearchOperation = null;
575
576         // Before we close the RAF, we have to wind the current search down.
577         if (searchOperation != null) {
578             Log.d(LOG, "Interrupting search to shut down.");
579             currentSearchOperation = null;
580             searchOperation.interrupted.set(true);
581         }
582
583         try {
584             Log.d(LOG, "Closing RAF.");
585             dictRaf.close();
586         } catch (IOException e) {
587             Log.e(LOG, "Failed to close dictionary", e);
588         }
589         dictRaf = null;
590     }
591
592     // --------------------------------------------------------------------------
593     // Buttons
594     // --------------------------------------------------------------------------
595
596     private void showKeyboard() {
597         // For some reason, this doesn't always work the first time.
598         // One way to replicate the problem:
599         // Press the "task switch" button repeatedly to pause and resume
600         for (int delay = 1; delay <= 101; delay += 100) {
601             searchView.postDelayed(new Runnable() {
602                 @Override
603                 public void run() {
604                     Log.d(LOG, "Trying to show soft keyboard.");
605                     final boolean searchTextHadFocus = searchView.hasFocus();
606                     searchView.requestFocusFromTouch();
607                     final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
608                     manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
609                     if (!searchTextHadFocus) {
610                         defocusSearchText();
611                     }
612                 }
613             }, delay);
614         }
615     }
616
617     void updateLangButton() {
618         final LanguageResources languageResources =
619                 Language.isoCodeToResources.get(index.shortName);
620         if (languageResources != null && languageResources.flagId != 0) {
621             languageButton.setImageResource(languageResources.flagId);
622         } else {
623             if (indexIndex % 2 == 0) {
624                 languageButton.setImageResource(android.R.drawable.ic_media_next);
625             } else {
626                 languageButton.setImageResource(android.R.drawable.ic_media_previous);
627             }
628         }
629         updateTTSLanguage();
630     }
631
632     private void updateTTSLanguage() {
633         if (!ttsReady || index == null || textToSpeech == null) {
634             Log.d(LOG, "Can't updateTTSLanguage.");
635             return;
636         }
637         final Locale locale = new Locale(index.sortLanguage.getIsoCode());
638         Log.d(LOG, "Setting TTS locale to: " + locale);
639         final int ttsResult = textToSpeech.setLanguage(locale);
640         if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
641                 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
642             Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
643         }
644     }
645
646     void onLanguageButtonClick() {
647         if (dictionary.indices.size() == 1) {
648             // No need to work to switch indices.
649             return;
650         }
651         if (currentSearchOperation != null) {
652             currentSearchOperation.interrupted.set(true);
653             currentSearchOperation = null;
654         }
655         setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
656                 searchView.getQuery().toString());
657     }
658
659     void onLanguageButtonLongClick(final Context context) {
660         final Dialog dialog = new Dialog(context);
661         dialog.setContentView(R.layout.select_dictionary_dialog);
662         dialog.setTitle(R.string.selectDictionary);
663
664         final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
665
666         ListView listView = (ListView) dialog.findViewById(android.R.id.list);
667         final Button button = new Button(listView.getContext());
668         final String name = getString(R.string.dictionaryManager);
669         button.setText(name);
670         final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
671                 DictionaryManagerActivity.getLaunchIntent()) {
672             @Override
673             protected void onGo() {
674                 dialog.dismiss();
675                 DictionaryActivity.this.finish();
676             };
677         };
678         button.setOnClickListener(intentLauncher);
679         listView.addHeaderView(button);
680
681         listView.setAdapter(new BaseAdapter() {
682             @Override
683             public View getView(int position, View convertView, ViewGroup parent) {
684                 final DictionaryInfo dictionaryInfo = getItem(position);
685
686                 final LinearLayout result = new LinearLayout(parent.getContext());
687
688                 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
689                     final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
690                     final View button = application.createButton(parent.getContext(),
691                             dictionaryInfo, indexInfo);
692                     final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
693                             getLaunchIntent(
694                                     application.getPath(dictionaryInfo.uncompressedFilename),
695                                     indexInfo.shortName, searchView.getQuery().toString())) {
696                         @Override
697                         protected void onGo() {
698                             dialog.dismiss();
699                             DictionaryActivity.this.finish();
700                         };
701                     };
702                     button.setOnClickListener(intentLauncher);
703                     result.addView(button);
704                 }
705
706                 final TextView nameView = new TextView(parent.getContext());
707                 final String name = application
708                         .getDictionaryName(dictionaryInfo.uncompressedFilename);
709                 nameView.setText(name);
710                 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
711                         ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
712                 layoutParams.width = 0;
713                 layoutParams.weight = 1.0f;
714                 nameView.setLayoutParams(layoutParams);
715                 nameView.setGravity(Gravity.CENTER_VERTICAL);
716                 result.addView(nameView);
717                 return result;
718             }
719
720             @Override
721             public long getItemId(int position) {
722                 return position;
723             }
724
725             @Override
726             public DictionaryInfo getItem(int position) {
727                 return installedDicts.get(position);
728             }
729
730             @Override
731             public int getCount() {
732                 return installedDicts.size();
733             }
734         });
735         dialog.show();
736     }
737
738     void onUpDownButton(final boolean up) {
739         if (isFiltered()) {
740             return;
741         }
742         final int firstVisibleRow = getListView().getFirstVisiblePosition();
743         final RowBase row = index.rows.get(firstVisibleRow);
744         final TokenRow tokenRow = row.getTokenRow(true);
745         final int destIndexEntry;
746         if (up) {
747             if (row != tokenRow) {
748                 destIndexEntry = tokenRow.referenceIndex;
749             } else {
750                 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
751             }
752         } else {
753             // Down
754             destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
755         }
756         final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
757         Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
758         setSearchText(dest.token, false);
759         jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
760         defocusSearchText();
761     }
762
763     // --------------------------------------------------------------------------
764     // Options Menu
765     // --------------------------------------------------------------------------
766
767     final Random random = new Random();
768
769     @Override
770     public boolean onCreateOptionsMenu(final Menu menu) {
771
772         if (PreferenceManager.getDefaultSharedPreferences(this)
773                 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
774             // Next word.
775             nextWordMenuItem = menu.add(getString(R.string.nextWord))
776                     .setIcon(R.drawable.arrow_down_float);
777             nextWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
778             nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
779                 @Override
780                 public boolean onMenuItemClick(MenuItem item) {
781                     onUpDownButton(false);
782                     return true;
783                 }
784             });
785
786             // Previous word.
787             previousWordMenuItem = menu.add(getString(R.string.previousWord))
788                     .setIcon(R.drawable.arrow_up_float);
789             previousWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
790             previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
791                 @Override
792                 public boolean onMenuItemClick(MenuItem item) {
793                     onUpDownButton(true);
794                     return true;
795                 }
796             });
797         }
798
799         application.onCreateGlobalOptionsMenu(this, menu);
800
801         {
802             final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
803             dictionaryManager.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
804             dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
805                 public boolean onMenuItemClick(final MenuItem menuItem) {
806                     startActivity(DictionaryManagerActivity.getLaunchIntent());
807                     finish();
808                     return false;
809                 }
810             });
811         }
812
813         {
814             final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
815             aboutDictionary.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
816             aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
817                 public boolean onMenuItemClick(final MenuItem menuItem) {
818                     final Context context = getListView().getContext();
819                     final Dialog dialog = new Dialog(context);
820                     dialog.setContentView(R.layout.about_dictionary_dialog);
821                     final TextView textView = (TextView) dialog.findViewById(R.id.text);
822
823                     final String name = application.getDictionaryName(dictFile.getName());
824                     dialog.setTitle(name);
825
826                     final StringBuilder builder = new StringBuilder();
827                     final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
828                     dictionaryInfo.uncompressedBytes = dictFile.length();
829                     if (dictionaryInfo != null) {
830                         builder.append(dictionaryInfo.dictInfo).append("\n\n");
831                         builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
832                                 .append("\n");
833                         builder.append(
834                                 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
835                                 .append("\n");
836                         builder.append(
837                                 getString(R.string.dictionaryCreationTime,
838                                         dictionaryInfo.creationMillis)).append("\n");
839                         for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
840                             builder.append("\n");
841                             builder.append(getString(R.string.indexName, indexInfo.shortName))
842                                     .append("\n");
843                             builder.append(
844                                     getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
845                                     .append("\n");
846                         }
847                         builder.append("\n");
848                         builder.append(getString(R.string.sources)).append("\n");
849                         for (final EntrySource source : dictionary.sources) {
850                             builder.append(
851                                     getString(R.string.sourceInfo, source.getName(),
852                                             source.getNumEntries())).append("\n");
853                         }
854                     }
855                     textView.setText(builder.toString());
856
857                     dialog.show();
858                     final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
859                     layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
860                     layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
861                     dialog.getWindow().setAttributes(layoutParams);
862                     return false;
863                 }
864             });
865         }
866
867         return true;
868     }
869
870     // --------------------------------------------------------------------------
871     // Context Menu + clicks
872     // --------------------------------------------------------------------------
873
874     @Override
875     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
876         AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
877         final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
878
879         final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
880                 wordList.getName()));
881         addToWordlist
882                 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
883                     public boolean onMenuItemClick(android.view.MenuItem item) {
884                         onAppendToWordList(row);
885                         return false;
886                     }
887                 });
888
889         final android.view.MenuItem share = menu.add("Share");
890         share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
891             public boolean onMenuItemClick(android.view.MenuItem item) {
892                 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
893                 shareIntent.setType("text/plain");
894                 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
895                         .getToken());
896                 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
897                         row.getRawText(saveOnlyFirstSubentry));
898                 startActivity(shareIntent);
899                 return false;
900             }
901         });
902
903         final android.view.MenuItem copy = menu.add(android.R.string.copy);
904         copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
905             public boolean onMenuItemClick(android.view.MenuItem item) {
906                 onCopy(row);
907                 return false;
908             }
909         });
910
911         if (selectedSpannableText != null) {
912             final String selectedText = selectedSpannableText;
913             final android.view.MenuItem searchForSelection = menu.add(getString(
914                     R.string.searchForSelection,
915                     selectedSpannableText));
916             searchForSelection
917                     .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
918                         public boolean onMenuItemClick(android.view.MenuItem item) {
919                             jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
920                             return false;
921                         }
922                     });
923         }
924
925         if (row instanceof TokenRow && ttsReady) {
926             final android.view.MenuItem speak = menu.add(R.string.speak);
927             speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
928                 @Override
929                 public boolean onMenuItemClick(android.view.MenuItem item) {
930                     textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
931                             new HashMap<String, String>());
932                     return false;
933                 }
934             });
935         }
936     }
937
938     private void jumpToTextFromHyperLink(
939             final String selectedText, final int defaultIndexToUse) {
940         int indexToUse = -1;
941         for (int i = 0; i < dictionary.indices.size(); ++i) {
942             final Index index = dictionary.indices.get(i);
943             if (indexPrepFinished) {
944                 System.out.println("Doing index lookup: on " + selectedText);
945                 final IndexEntry indexEntry = index.findExact(selectedText);
946                 if (indexEntry != null) {
947                     final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
948                             .getTokenRow(false);
949                     if (tokenRow != null && tokenRow.hasMainEntry) {
950                         indexToUse = i;
951                         break;
952                     }
953                 }
954             } else {
955                 Log.w(LOG, "Skipping findExact on index " + index.shortName);
956             }
957         }
958         if (indexToUse == -1) {
959             indexToUse = defaultIndexToUse;
960         }
961         // Without this extra delay, the call to jumpToRow that this
962         // invokes doesn't always actually have any effect.
963         final int actualIndexToUse = indexToUse;
964         getListView().postDelayed(new Runnable() {
965             @Override
966             public void run() {
967                 setIndexAndSearchText(actualIndexToUse, selectedText);
968             }
969         }, 100);
970     }
971
972     /**
973      * Called when user clicks outside of search text, so that they can start
974      * typing again immediately.
975      */
976     void defocusSearchText() {
977         // Log.d(LOG, "defocusSearchText");
978         // Request focus so that if we start typing again, it clears the text
979         // input.
980         getListView().requestFocus();
981
982         // Visual indication that a new keystroke will clear the search text.
983         // Doesn't seem to work unless earchText has focus.
984         // searchView.selectAll();
985     }
986
987     @Override
988     protected void onListItemClick(ListView l, View v, int row, long id) {
989         defocusSearchText();
990         if (clickOpensContextMenu && dictRaf != null) {
991             openContextMenu(v);
992         }
993     }
994
995     @SuppressLint("SimpleDateFormat")
996     void onAppendToWordList(final RowBase row) {
997         defocusSearchText();
998
999         final StringBuilder rawText = new StringBuilder();
1000         rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1001         rawText.append(index.longName).append("\t");
1002         rawText.append(row.getTokenRow(true).getToken()).append("\t");
1003         rawText.append(row.getRawText(saveOnlyFirstSubentry));
1004         Log.d(LOG, "Writing : " + rawText);
1005
1006         try {
1007             wordList.getParentFile().mkdirs();
1008             final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1009             out.println(rawText.toString());
1010             out.close();
1011         } catch (IOException e) {
1012             Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1013             Toast.makeText(this,
1014                     getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1015                     Toast.LENGTH_LONG).show();
1016         }
1017         return;
1018     }
1019
1020     @SuppressWarnings("deprecation")
1021     void onCopy(final RowBase row) {
1022         defocusSearchText();
1023
1024         Log.d(LOG, "Copy, row=" + row);
1025         final StringBuilder result = new StringBuilder();
1026         result.append(row.getRawText(false));
1027         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1028         clipboardManager.setText(result.toString());
1029         Log.d(LOG, "Copied: " + result);
1030     }
1031
1032     @Override
1033     public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1034         if (event.getUnicodeChar() != 0) {
1035             if (!searchView.hasFocus()) {
1036                 setSearchText("" + (char) event.getUnicodeChar(), true);
1037                 searchView.requestFocus();
1038             }
1039             return true;
1040         }
1041         if (keyCode == KeyEvent.KEYCODE_BACK) {
1042             // Log.d(LOG, "Clearing dictionary prefs.");
1043             // Pretend that we just autolaunched so that we won't do it again.
1044             // DictionaryManagerActivity.lastAutoLaunchMillis =
1045             // System.currentTimeMillis();
1046         }
1047         if (keyCode == KeyEvent.KEYCODE_ENTER) {
1048             Log.d(LOG, "Trying to hide soft keyboard.");
1049             final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1050             inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
1051                     InputMethodManager.HIDE_NOT_ALWAYS);
1052             return true;
1053         }
1054         return super.onKeyDown(keyCode, event);
1055     }
1056
1057     private void setIndexAndSearchText(int newIndex, String newSearchText) {
1058         Log.d(LOG, "Changing index to: " + newIndex);
1059         if (newIndex == -1) {
1060             Log.e(LOG, "Invalid index.");
1061             newIndex = 0;
1062         }
1063         if (newIndex != indexIndex) {
1064             indexIndex = newIndex;
1065             index = dictionary.indices.get(indexIndex);
1066             indexAdapter = new IndexAdapter(index);
1067             setListAdapter(indexAdapter);
1068             Log.d(LOG, "changingIndex, newLang=" + index.longName);
1069             setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1070             updateLangButton();
1071         }
1072         setSearchText(newSearchText, true);
1073     }
1074
1075     private void setSearchText(final String text, final boolean triggerSearch) {
1076         Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1077         // Disable the listener, because sometimes it doesn't work.
1078         searchView.setOnQueryTextListener(null);
1079         searchView.setQuery(text, false);
1080         moveCursorToRight();
1081         searchView.setOnQueryTextListener(onQueryTextListener);
1082         if (triggerSearch) {
1083             onQueryTextListener.onQueryTextChange(text);
1084         }
1085     }
1086
1087     // private long cursorDelayMillis = 100;
1088     private void moveCursorToRight() {
1089         // if (searchText.getLayout() != null) {
1090         // cursorDelayMillis = 100;
1091         // // Surprising, but this can crash when you rotate...
1092         // Selection.moveToRightEdge(searchView.getQuery(),
1093         // searchText.getLayout());
1094         // } else {
1095         // uiHandler.postDelayed(new Runnable() {
1096         // @Override
1097         // public void run() {
1098         // moveCursorToRight();
1099         // }
1100         // }, cursorDelayMillis);
1101         // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1102         // }
1103     }
1104
1105     // --------------------------------------------------------------------------
1106     // SearchOperation
1107     // --------------------------------------------------------------------------
1108
1109     private void searchFinished(final SearchOperation searchOperation) {
1110         if (searchOperation.interrupted.get()) {
1111             Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1112             return;
1113         }
1114         if (searchOperation != this.currentSearchOperation) {
1115             Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1116             return;
1117         }
1118
1119         final Index.IndexEntry searchResult = searchOperation.searchResult;
1120         Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1121
1122         currentSearchOperation = null;
1123         uiHandler.postDelayed(new Runnable() {
1124             @Override
1125             public void run() {
1126                 if (currentSearchOperation == null) {
1127                     if (searchResult != null) {
1128                         if (isFiltered()) {
1129                             clearFiltered();
1130                         }
1131                         jumpToRow(searchResult.startRow);
1132                     } else if (searchOperation.multiWordSearchResult != null) {
1133                         // Multi-row search....
1134                         setFiltered(searchOperation);
1135                     } else {
1136                         throw new IllegalStateException("This should never happen.");
1137                     }
1138                 } else {
1139                     Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1140                 }
1141             }
1142         }, 20);
1143     }
1144
1145     private final void jumpToRow(final int row) {
1146         Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1147         // getListView().requestFocusFromTouch();
1148         getListView().setSelectionFromTop(row, 0);
1149         getListView().setSelected(true);
1150     }
1151
1152     static final Pattern WHITESPACE = Pattern.compile("\\s+");
1153
1154     final class SearchOperation implements Runnable {
1155
1156         final AtomicBoolean interrupted = new AtomicBoolean(false);
1157
1158         final String searchText;
1159
1160         List<String> searchTokens; // filled in for multiWord.
1161
1162         final Index index;
1163
1164         long searchStartMillis;
1165
1166         Index.IndexEntry searchResult;
1167
1168         List<RowBase> multiWordSearchResult;
1169
1170         boolean done = false;
1171
1172         SearchOperation(final String searchText, final Index index) {
1173             this.searchText = StringUtil.normalizeWhitespace(searchText);
1174             this.index = index;
1175         }
1176
1177         public String toString() {
1178             return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1179         }
1180
1181         @Override
1182         public void run() {
1183             try {
1184                 searchStartMillis = System.currentTimeMillis();
1185                 final String[] searchTokenArray = WHITESPACE.split(searchText);
1186                 if (searchTokenArray.length == 1) {
1187                     searchResult = index.findInsertionPoint(searchText, interrupted);
1188                 } else {
1189                     searchTokens = Arrays.asList(searchTokenArray);
1190                     multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1191                             interrupted);
1192                 }
1193                 Log.d(LOG,
1194                         "searchText=" + searchText + ", searchDuration="
1195                                 + (System.currentTimeMillis() - searchStartMillis)
1196                                 + ", interrupted=" + interrupted.get());
1197                 if (!interrupted.get()) {
1198                     uiHandler.post(new Runnable() {
1199                         @Override
1200                         public void run() {
1201                             searchFinished(SearchOperation.this);
1202                         }
1203                     });
1204                 } else {
1205                     Log.d(LOG, "interrupted, skipping searchFinished.");
1206                 }
1207             } catch (Exception e) {
1208                 Log.e(LOG, "Failure during search (can happen during Activity close.");
1209             } finally {
1210                 synchronized (this) {
1211                     done = true;
1212                     this.notifyAll();
1213                 }
1214             }
1215         }
1216     }
1217
1218     // --------------------------------------------------------------------------
1219     // IndexAdapter
1220     // --------------------------------------------------------------------------
1221
1222     static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1223             ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1224
1225     static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1226             ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1227
1228     final class IndexAdapter extends BaseAdapter {
1229
1230         private static final float PADDING_DEFAULT_DP = 8;
1231
1232         private static final float PADDING_LARGE_DP = 16;
1233
1234         final Index index;
1235
1236         final List<RowBase> rows;
1237
1238         final Set<String> toHighlight;
1239
1240         private int mPaddingDefault;
1241
1242         private int mPaddingLarge;
1243
1244         IndexAdapter(final Index index) {
1245             this.index = index;
1246             rows = index.rows;
1247             this.toHighlight = null;
1248             getMetrics();
1249         }
1250
1251         IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1252             this.index = index;
1253             this.rows = rows;
1254             this.toHighlight = new LinkedHashSet<String>(toHighlight);
1255             getMetrics();
1256         }
1257
1258         private void getMetrics() {
1259             // Get the screen's density scale
1260             final float scale = getResources().getDisplayMetrics().density;
1261             // Convert the dps to pixels, based on density scale
1262             mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1263             mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1264         }
1265
1266         @Override
1267         public int getCount() {
1268             return rows.size();
1269         }
1270
1271         @Override
1272         public RowBase getItem(int position) {
1273             return rows.get(position);
1274         }
1275
1276         @Override
1277         public long getItemId(int position) {
1278             return getItem(position).index();
1279         }
1280
1281         @Override
1282         public TableLayout getView(int position, View convertView, ViewGroup parent) {
1283             final TableLayout result;
1284             if (convertView instanceof TableLayout) {
1285                 result = (TableLayout) convertView;
1286                 result.removeAllViews();
1287             } else {
1288                 result = new TableLayout(parent.getContext());
1289             }
1290             final RowBase row = getItem(position);
1291             if (row instanceof PairEntry.Row) {
1292                 return getView(position, (PairEntry.Row) row, parent, result);
1293             } else if (row instanceof TokenRow) {
1294                 return getView((TokenRow) row, parent, result);
1295             } else if (row instanceof HtmlEntry.Row) {
1296                 return getView((HtmlEntry.Row) row, parent, result);
1297             } else {
1298                 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1299             }
1300         }
1301
1302         private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1303                 final TableLayout result) {
1304             final PairEntry entry = row.getEntry();
1305             final int rowCount = entry.pairs.size();
1306
1307             final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1308             layoutParams.weight = 0.5f;
1309             layoutParams.leftMargin = mPaddingLarge;
1310
1311             for (int r = 0; r < rowCount; ++r) {
1312                 final TableRow tableRow = new TableRow(result.getContext());
1313
1314                 final TextView col1 = new TextView(tableRow.getContext());
1315                 final TextView col2 = new TextView(tableRow.getContext());
1316
1317                 // Set the columns in the table.
1318                 if (r > 0) {
1319                     final TextView bullet = new TextView(tableRow.getContext());
1320                     bullet.setText(" • ");
1321                     tableRow.addView(bullet);
1322                 }
1323                 tableRow.addView(col1, layoutParams);
1324                 final TextView margin = new TextView(tableRow.getContext());
1325                 margin.setText(" ");
1326                 tableRow.addView(margin);
1327                 if (r > 0) {
1328                     final TextView bullet = new TextView(tableRow.getContext());
1329                     bullet.setText(" • ");
1330                     tableRow.addView(bullet);
1331                 }
1332                 tableRow.addView(col2, layoutParams);
1333                 col1.setWidth(1);
1334                 col2.setWidth(1);
1335
1336                 // Set what's in the columns.
1337
1338                 final Pair pair = entry.pairs.get(r);
1339                 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1340                 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1341
1342                 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1343                 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1344
1345                 // Bold the token instances in col1.
1346                 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1347                         .singleton(row.getTokenRow(true).getToken());
1348                 final Spannable col1Spannable = (Spannable) col1.getText();
1349                 for (final String token : toBold) {
1350                     int startPos = 0;
1351                     while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1352                         col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1353                                 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1354                         startPos += token.length();
1355                     }
1356                 }
1357
1358                 createTokenLinkSpans(col1, col1Spannable, col1Text);
1359                 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1360
1361                 col1.setTypeface(typeface);
1362                 col2.setTypeface(typeface);
1363                 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1364                 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1365                 // col2.setBackgroundResource(theme.otherLangBg);
1366
1367                 if (index.swapPairEntries) {
1368                     col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1369                     col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1370                 } else {
1371                     col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1372                     col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1373                 }
1374
1375                 result.addView(tableRow);
1376             }
1377
1378             // Because we have a Button inside a ListView row:
1379             // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1380             result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1381             result.setClickable(true);
1382             result.setFocusable(true);
1383             result.setLongClickable(true);
1384 //            result.setBackgroundResource(android.R.drawable.menuitem_background);
1385             
1386             result.setBackgroundResource(theme.normalRowBg);
1387
1388             result.setOnClickListener(new TextView.OnClickListener() {
1389                 @Override
1390                 public void onClick(View v) {
1391                     DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1392                 }
1393             });
1394
1395             return result;
1396         }
1397
1398         private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1399                 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1400                 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1401             final Context context = parent.getContext();
1402
1403             final TableRow tableRow = new TableRow(result.getContext());
1404             tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1405                     : theme.tokenRowOtherBg);
1406             if (isTokenRow) {
1407                 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1408             } else {
1409                 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1410             }
1411             result.addView(tableRow);
1412
1413             // Make it so we can long-click on these token rows, too:
1414             final TextView textView = new TextView(context);
1415             textView.setText(text, BufferType.SPANNABLE);
1416             createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1417             final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1418                     0);
1419             textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1420             result.setLongClickable(true);
1421
1422             // Doesn't work:
1423             // textView.setTextColor(android.R.color.secondary_text_light);
1424             textView.setTypeface(typeface);
1425             TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1426             if (isTokenRow) {
1427                 textView.setTextAppearance(context, theme.tokenRowFg);
1428                 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1429             } else {
1430                 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1431             }
1432             lp.weight = 1.0f;
1433
1434             textView.setLayoutParams(lp);
1435             tableRow.addView(textView);
1436
1437             if (!htmlEntries.isEmpty()) {
1438                 final ClickableSpan clickableSpan = new ClickableSpan() {
1439                     @Override
1440                     public void onClick(View widget) {
1441                     }
1442                 };
1443                 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1444                         Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1445                 result.setClickable(true);
1446                 textView.setClickable(true);
1447                 textView.setMovementMethod(LinkMovementMethod.getInstance());
1448                 textView.setOnClickListener(new OnClickListener() {
1449                     @Override
1450                     public void onClick(View v) {
1451                         String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1452                         // Log.d(LOG, "html=" + html);
1453                         startActivityForResult(
1454                                 HtmlDisplayActivity.getHtmlIntent(String.format(
1455                                         "<html><head></head><body>%s</body></html>", html),
1456                                         htmlTextToHighlight, false),
1457                                 0);
1458                     }
1459                 });
1460             }
1461             return result;
1462         }
1463
1464         private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1465             final IndexEntry indexEntry = row.getIndexEntry();
1466             return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1467                     indexEntry.htmlEntries, null, parent, result);
1468         }
1469
1470         private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1471             final HtmlEntry htmlEntry = row.getEntry();
1472             final TokenRow tokenRow = row.getTokenRow(true);
1473             return getPossibleLinkToHtmlEntryView(false,
1474                     getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1475                     false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1476                     result);
1477         }
1478
1479     }
1480
1481     static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1482
1483     private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1484             final String text) {
1485         // Saw from the source code that LinkMovementMethod sets the selection!
1486         // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1487         textView.setMovementMethod(LinkMovementMethod.getInstance());
1488         final Matcher matcher = CHAR_DASH.matcher(text);
1489         while (matcher.find()) {
1490             spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1491                     matcher.end(),
1492                     Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1493         }
1494     }
1495
1496     String selectedSpannableText = null;
1497
1498     int selectedSpannableIndex = -1;
1499
1500     @Override
1501     public boolean onTouchEvent(MotionEvent event) {
1502         selectedSpannableText = null;
1503         selectedSpannableIndex = -1;
1504         return super.onTouchEvent(event);
1505     }
1506
1507     private class TextViewLongClickListener implements OnLongClickListener {
1508         final int index;
1509
1510         private TextViewLongClickListener(final int index) {
1511             this.index = index;
1512         }
1513
1514         @Override
1515         public boolean onLongClick(final View v) {
1516             final TextView textView = (TextView) v;
1517             final int start = textView.getSelectionStart();
1518             final int end = textView.getSelectionEnd();
1519             if (start >= 0 && end >= 0) {
1520                 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1521                 selectedSpannableIndex = index;
1522             }
1523             return false;
1524         }
1525     }
1526
1527     final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1528             0);
1529
1530     final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1531             1);
1532
1533     // --------------------------------------------------------------------------
1534     // SearchText
1535     // --------------------------------------------------------------------------
1536
1537     void onSearchTextChange(final String text) {
1538         if ("thadolina".equals(text)) {
1539             final Dialog dialog = new Dialog(getListView().getContext());
1540             dialog.setContentView(R.layout.thadolina_dialog);
1541             dialog.setTitle("Ti amo, amore mio!");
1542             final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1543             imageView.setOnClickListener(new OnClickListener() {
1544                 @Override
1545                 public void onClick(View v) {
1546                     final Intent intent = new Intent(Intent.ACTION_VIEW);
1547                     intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1548                     startActivity(intent);
1549                 }
1550             });
1551             dialog.show();
1552         }
1553         if (dictRaf == null) {
1554             Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1555             return;
1556         }
1557         // if (!searchView.hasFocus()) {
1558         // Log.d(LOG, "searchText changed without focus, doing nothing.");
1559         // return;
1560         // }
1561         Log.d(LOG, "onSearchTextChange: " + text);
1562         if (currentSearchOperation != null) {
1563             Log.d(LOG, "Interrupting currentSearchOperation.");
1564             currentSearchOperation.interrupted.set(true);
1565         }
1566         currentSearchOperation = new SearchOperation(text, index);
1567         searchExecutor.execute(currentSearchOperation);
1568     }
1569
1570     // --------------------------------------------------------------------------
1571     // Filtered results.
1572     // --------------------------------------------------------------------------
1573
1574     boolean isFiltered() {
1575         return rowsToShow != null;
1576     }
1577
1578     void setFiltered(final SearchOperation searchOperation) {
1579         if (nextWordMenuItem != null) {
1580             nextWordMenuItem.setEnabled(false);
1581             previousWordMenuItem.setEnabled(false);
1582         }
1583         rowsToShow = searchOperation.multiWordSearchResult;
1584         setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1585     }
1586
1587     void clearFiltered() {
1588         if (nextWordMenuItem != null) {
1589             nextWordMenuItem.setEnabled(true);
1590             previousWordMenuItem.setEnabled(true);
1591         }
1592         setListAdapter(new IndexAdapter(index));
1593         rowsToShow = null;
1594     }
1595
1596 }