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