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