]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryActivity.java
Format DictionaryActivity using Android style so one can read this.
[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 com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
18 import com.hughes.android.dictionary.engine.Dictionary;
19 import com.hughes.android.dictionary.engine.EntrySource;
20 import com.hughes.android.dictionary.engine.HtmlEntry;
21 import com.hughes.android.dictionary.engine.Index;
22 import com.hughes.android.dictionary.engine.Index.IndexEntry;
23 import com.hughes.android.dictionary.engine.PairEntry;
24 import com.hughes.android.dictionary.engine.PairEntry.Pair;
25 import com.hughes.android.dictionary.engine.RowBase;
26 import com.hughes.android.dictionary.engine.TokenRow;
27 import com.hughes.android.dictionary.engine.TransliteratorManager;
28 import com.hughes.android.util.IntentLauncher;
29 import com.hughes.android.util.NonLinkClickableSpan;
30
31 import android.app.Dialog;
32 import android.app.ListActivity;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.SharedPreferences;
36 import android.graphics.Typeface;
37 import android.net.Uri;
38 import android.os.Bundle;
39 import android.os.Handler;
40 import android.preference.PreferenceManager;
41 import android.text.ClipboardManager;
42 import android.text.Editable;
43 import android.text.Selection;
44 import android.text.Spannable;
45 import android.text.TextWatcher;
46 import android.text.method.LinkMovementMethod;
47 import android.text.style.StyleSpan;
48 import android.util.Log;
49 import android.util.TypedValue;
50 import android.view.ContextMenu;
51 import android.view.ContextMenu.ContextMenuInfo;
52 import android.view.KeyEvent;
53 import android.view.Menu;
54 import android.view.MenuItem;
55 import android.view.MenuItem.OnMenuItemClickListener;
56 import android.view.MotionEvent;
57 import android.view.View;
58 import android.view.View.OnClickListener;
59 import android.view.View.OnLongClickListener;
60 import android.view.ViewGroup;
61 import android.view.WindowManager;
62 import android.view.inputmethod.InputMethodManager;
63 import android.widget.AdapterView;
64 import android.widget.AdapterView.AdapterContextMenuInfo;
65 import android.widget.BaseAdapter;
66 import android.widget.Button;
67 import android.widget.EditText;
68 import android.widget.ImageView;
69 import android.widget.LinearLayout;
70 import android.widget.ListAdapter;
71 import android.widget.ListView;
72 import android.widget.TableLayout;
73 import android.widget.TableRow;
74 import android.widget.TextView;
75 import android.widget.Toast;
76
77 import java.io.File;
78 import java.io.FileWriter;
79 import java.io.IOException;
80 import java.io.PrintWriter;
81 import java.io.RandomAccessFile;
82 import java.text.SimpleDateFormat;
83 import java.util.Arrays;
84 import java.util.Collections;
85 import java.util.Date;
86 import java.util.LinkedHashSet;
87 import java.util.List;
88 import java.util.Random;
89 import java.util.Set;
90 import java.util.concurrent.Executor;
91 import java.util.concurrent.Executors;
92 import java.util.concurrent.ThreadFactory;
93 import java.util.concurrent.atomic.AtomicBoolean;
94 import java.util.regex.Matcher;
95 import java.util.regex.Pattern;
96
97 public class DictionaryActivity extends ListActivity {
98
99     static final String LOG = "QuickDic";
100
101     private String initialSearchText;
102
103     DictionaryApplication application;
104
105     File dictFile = null;
106
107     RandomAccessFile dictRaf = null;
108
109     Dictionary dictionary = null;
110
111     int indexIndex = 0;
112
113     Index index = null;
114
115     List<RowBase> rowsToShow = null; // if not null, just show these rows.
116
117     // package for test.
118     final Handler uiHandler = new Handler();
119
120     private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
121         @Override
122         public Thread newThread(Runnable r) {
123             return new Thread(r, "searchExecutor");
124         }
125     });
126
127     private SearchOperation currentSearchOperation = null;
128
129     C.Theme theme = C.Theme.LIGHT;
130
131     Typeface typeface;
132
133     int fontSizeSp;
134
135     EditText searchText;
136
137     Button langButton;
138
139     // Never null.
140     private File wordList = null;
141
142     private boolean saveOnlyFirstSubentry = false;
143
144     private boolean clickOpensContextMenu = false;
145
146     // Visible for testing.
147     ListAdapter indexAdapter = null;
148
149     final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
150
151     /**
152      * For some languages, loading the transliterators used in this search takes
153      * a long time, so we fire it up on a different thread, and don't invoke it
154      * from the main thread until it's already finished once.
155      */
156     private volatile boolean indexPrepFinished = false;
157
158     public DictionaryActivity() {
159     }
160
161     public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
162             final String searchToken) {
163         final Intent intent = new Intent();
164         intent.setClassName(DictionaryActivity.class.getPackage().getName(),
165                 DictionaryActivity.class.getName());
166         intent.putExtra(C.DICT_FILE, dictFile.getPath());
167         intent.putExtra(C.INDEX_INDEX, indexIndex);
168         intent.putExtra(C.SEARCH_TOKEN, searchToken);
169         return intent;
170     }
171
172     @Override
173     protected void onSaveInstanceState(final Bundle outState) {
174         super.onSaveInstanceState(outState);
175         Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
176         outState.putInt(C.INDEX_INDEX, indexIndex);
177         outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
178     }
179
180     @Override
181     protected void onRestoreInstanceState(final Bundle outState) {
182         super.onRestoreInstanceState(outState);
183         Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
184         onCreate(outState);
185     }
186
187     @Override
188     public void onCreate(Bundle savedInstanceState) {
189         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
190         prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
191                                                      // this fails.
192
193         setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
194
195         Log.d(LOG, "onCreate:" + this);
196         super.onCreate(savedInstanceState);
197
198         application = (DictionaryApplication) getApplication();
199         theme = application.getSelectedTheme();
200
201         final Intent intent = getIntent();
202         dictFile = new File(intent.getStringExtra(C.DICT_FILE));
203
204         try {
205             final String name = application.getDictionaryName(dictFile.getName());
206             this.setTitle("QuickDic: " + name);
207             dictRaf = new RandomAccessFile(dictFile, "r");
208             dictionary = new Dictionary(dictRaf);
209         } catch (Exception e) {
210             Log.e(LOG, "Unable to load dictionary.", e);
211             if (dictRaf != null) {
212                 try {
213                     dictRaf.close();
214                 } catch (IOException e1) {
215                     Log.e(LOG, "Unable to close dictRaf.", e1);
216                 }
217                 dictRaf = null;
218             }
219             Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
220                     Toast.LENGTH_LONG).show();
221             startActivity(DictionaryManagerActivity.getLaunchIntent());
222             finish();
223             return;
224         }
225         indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
226         if (savedInstanceState != null) {
227             indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
228         }
229         indexIndex %= dictionary.indices.size();
230         Log.d(LOG, "Loading index " + indexIndex);
231         index = dictionary.indices.get(indexIndex);
232         setListAdapter(new IndexAdapter(index));
233
234         // Pre-load the collators.
235         new Thread(new Runnable() {
236             public void run() {
237                 final long startMillis = System.currentTimeMillis();
238                 try {
239                     TransliteratorManager.init(new TransliteratorManager.Callback() {
240                         @Override
241                         public void onTransliteratorReady() {
242                             uiHandler.post(new Runnable() {
243                                 @Override
244                                 public void run() {
245                                     onSearchTextChange(searchText.getText().toString());
246                                 }
247                             });
248                         }
249                     });
250
251                     for (final Index index : dictionary.indices) {
252                         final String searchToken = index.sortedIndexEntries.get(0).token;
253                         final IndexEntry entry = index.findExact(searchToken);
254                         if (!searchToken.equals(entry.token)) {
255                             Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
256                         }
257                     }
258                     indexPrepFinished = true;
259                 } catch (Exception e) {
260                     Log.w(LOG,
261                             "Exception while prepping.  This can happen if dictionary is closed while search is happening.");
262                 }
263                 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
264             }
265         }).start();
266
267         String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
268         if ("SYSTEM".equals(fontName)) {
269             typeface = Typeface.DEFAULT;
270         } else {
271             try {
272                 typeface = Typeface.createFromAsset(getAssets(), fontName);
273             } catch (Exception e) {
274                 Log.w(LOG, "Exception trying to use typeface, using default.", e);
275                 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
276                         Toast.LENGTH_LONG).show();
277             }
278         }
279         // if (!"SYSTEM".equals(fontName)) {
280         // throw new RuntimeException("Test force using system font: " +
281         // fontName);
282         // }
283         if (typeface == null) {
284             Log.w(LOG, "Unable to create typeface, using default.");
285             typeface = Typeface.DEFAULT;
286         }
287         final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
288         try {
289             fontSizeSp = Integer.parseInt(fontSize.trim());
290         } catch (NumberFormatException e) {
291             fontSizeSp = 14;
292         }
293
294         setContentView(R.layout.dictionary_activity);
295         searchText = (EditText) findViewById(R.id.SearchText);
296         searchText.setTypeface(typeface);
297         searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
298
299         langButton = (Button) findViewById(R.id.LangButton);
300
301         searchText.requestFocus();
302         searchText.addTextChangedListener(searchTextWatcher);
303
304         // Set the search text from the intent, then the saved state.
305         String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
306         if (savedInstanceState != null) {
307             text = savedInstanceState.getString(C.SEARCH_TOKEN);
308         }
309         if (text == null) {
310             text = "";
311         }
312         setSearchText(text, true);
313         Log.d(LOG, "Trying to restore searchText=" + text);
314
315         final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
316         clearSearchTextButton.setOnClickListener(new OnClickListener() {
317             public void onClick(View v) {
318                 onClearSearchTextButton(clearSearchTextButton);
319             }
320         });
321         clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
322                 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
323                 : View.GONE);
324
325         final Button langButton = (Button) findViewById(R.id.LangButton);
326         langButton.setOnClickListener(new OnClickListener() {
327             public void onClick(View v) {
328                 onLanguageButton();
329             }
330         });
331         langButton.setOnLongClickListener(new OnLongClickListener() {
332             @Override
333             public boolean onLongClick(View v) {
334                 onLanguageButtonLongClick(v.getContext());
335                 return true;
336             }
337         });
338         updateLangButton();
339
340         final Button upButton = (Button) findViewById(R.id.UpButton);
341         upButton.setOnClickListener(new OnClickListener() {
342             public void onClick(View v) {
343                 onUpDownButton(true);
344             }
345         });
346         final Button downButton = (Button) findViewById(R.id.DownButton);
347         downButton.setOnClickListener(new OnClickListener() {
348             public void onClick(View v) {
349                 onUpDownButton(false);
350             }
351         });
352
353         getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
354             @Override
355             public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
356                     long id) {
357                 if (!searchText.isFocused()) {
358                     if (!isFiltered()) {
359                         final RowBase row = (RowBase) getListAdapter().getItem(position);
360                         Log.d(LOG, "onItemSelected: " + row.index());
361                         final TokenRow tokenRow = row.getTokenRow(true);
362                         searchText.setText(tokenRow.getToken());
363                     }
364                 }
365             }
366
367             @Override
368             public void onNothingSelected(AdapterView<?> arg0) {
369             }
370         });
371
372         // ContextMenu.
373         registerForContextMenu(getListView());
374
375         // Prefs.
376         wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
377                 getString(R.string.wordListFileDefault)));
378         saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
379                 false);
380         clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
381                 false);
382         // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
383         // true)) {
384         // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
385         // }
386         Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
387
388         setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
389     }
390
391     @Override
392     protected void onResume() {
393         super.onResume();
394         if (PreferenceActivity.prefsMightHaveChanged) {
395             PreferenceActivity.prefsMightHaveChanged = false;
396             finish();
397             startActivity(getIntent());
398         }
399         if (initialSearchText != null) {
400             setSearchText(initialSearchText, true);
401         }
402     }
403
404     @Override
405     protected void onPause() {
406         super.onPause();
407     }
408
409     private static void setDictionaryPrefs(final Context context, final File dictFile,
410             final int indexIndex, final String searchToken) {
411         final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
412                 context).edit();
413         prefs.putString(C.DICT_FILE, dictFile.getPath());
414         prefs.putInt(C.INDEX_INDEX, indexIndex);
415         prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
416         prefs.commit();
417     }
418
419     @Override
420     protected void onDestroy() {
421         super.onDestroy();
422         if (dictRaf == null) {
423             return;
424         }
425
426         final SearchOperation searchOperation = currentSearchOperation;
427         currentSearchOperation = null;
428
429         // Before we close the RAF, we have to wind the current search down.
430         if (searchOperation != null) {
431             Log.d(LOG, "Interrupting search to shut down.");
432             currentSearchOperation = null;
433             searchOperation.interrupted.set(true);
434         }
435
436         try {
437             Log.d(LOG, "Closing RAF.");
438             dictRaf.close();
439         } catch (IOException e) {
440             Log.e(LOG, "Failed to close dictionary", e);
441         }
442         dictRaf = null;
443     }
444
445     // --------------------------------------------------------------------------
446     // Buttons
447     // --------------------------------------------------------------------------
448
449     private void onClearSearchTextButton(final Button clearSearchTextButton) {
450         setSearchText("", true);
451         Log.d(LOG, "Trying to show soft keyboard.");
452         final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
453         manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
454     }
455
456     void updateLangButton() {
457         // final LanguageResources languageResources =
458         // Language.isoCodeToResources.get(index.shortName);
459         // if (languageResources != null && languageResources.flagId != 0) {
460         // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
461         // languageResources.flagId, 0);
462         // } else {
463         // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
464         langButton.setText(index.shortName);
465         // }
466     }
467
468     void onLanguageButton() {
469         if (currentSearchOperation != null) {
470             currentSearchOperation.interrupted.set(true);
471             currentSearchOperation = null;
472         }
473         changeIndexGetFocusAndResearch((indexIndex + 1) % dictionary.indices.size());
474     }
475
476     void onLanguageButtonLongClick(final Context context) {
477         final Dialog dialog = new Dialog(context);
478         dialog.setContentView(R.layout.select_dictionary_dialog);
479         dialog.setTitle(R.string.selectDictionary);
480
481         final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
482                 .getUsableDicts();
483
484         ListView listView = (ListView) dialog.findViewById(android.R.id.list);
485
486         // final LinearLayout.LayoutParams layoutParams = new
487         // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
488         // ViewGroup.LayoutParams.WRAP_CONTENT);
489         // layoutParams.width = 0;
490         // layoutParams.weight = 1.0f;
491
492         final Button button = new Button(listView.getContext());
493         final String name = getString(R.string.dictionaryManager);
494         button.setText(name);
495         final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
496                 DictionaryManagerActivity.getLaunchIntent()) {
497             @Override
498             protected void onGo() {
499                 dialog.dismiss();
500                 DictionaryActivity.this.finish();
501             };
502         };
503         button.setOnClickListener(intentLauncher);
504         // button.setLayoutParams(layoutParams);
505         listView.addHeaderView(button);
506         // listView.setHeaderDividersEnabled(true);
507
508         listView.setAdapter(new BaseAdapter() {
509             @Override
510             public View getView(int position, View convertView, ViewGroup parent) {
511                 final LinearLayout result = new LinearLayout(parent.getContext());
512
513                 final DictionaryInfo dictionaryInfo = getItem(position);
514                 final Button button = new Button(parent.getContext());
515                 final String name = application
516                         .getDictionaryName(dictionaryInfo.uncompressedFilename);
517                 button.setText(name);
518                 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
519                         getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
520                                 0, searchText.getText().toString())) {
521                     @Override
522                     protected void onGo() {
523                         dialog.dismiss();
524                         DictionaryActivity.this.finish();
525                     };
526                 };
527                 button.setOnClickListener(intentLauncher);
528                 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
529                         ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
530                 layoutParams.width = 0;
531                 layoutParams.weight = 1.0f;
532                 button.setLayoutParams(layoutParams);
533                 result.addView(button);
534                 return result;
535             }
536
537             @Override
538             public long getItemId(int position) {
539                 return position;
540             }
541
542             @Override
543             public DictionaryInfo getItem(int position) {
544                 return installedDicts.get(position);
545             }
546
547             @Override
548             public int getCount() {
549                 return installedDicts.size();
550             }
551         });
552
553         dialog.show();
554     }
555
556     private void changeIndexGetFocusAndResearch(final int newIndex) {
557         indexIndex = newIndex;
558         index = dictionary.indices.get(indexIndex);
559         indexAdapter = new IndexAdapter(index);
560         Log.d(LOG, "changingIndex, newLang=" + index.longName);
561         setListAdapter(indexAdapter);
562         updateLangButton();
563         searchText.requestFocus(); // Otherwise, nothing may happen.
564         onSearchTextChange(searchText.getText().toString());
565         setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
566     }
567
568     void onUpDownButton(final boolean up) {
569         if (isFiltered()) {
570             return;
571         }
572         final int firstVisibleRow = getListView().getFirstVisiblePosition();
573         final RowBase row = index.rows.get(firstVisibleRow);
574         final TokenRow tokenRow = row.getTokenRow(true);
575         final int destIndexEntry;
576         if (up) {
577             if (row != tokenRow) {
578                 destIndexEntry = tokenRow.referenceIndex;
579             } else {
580                 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
581             }
582         } else {
583             // Down
584             destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
585         }
586         final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
587         Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
588         searchText.removeTextChangedListener(searchTextWatcher);
589         searchText.setText(dest.token);
590         if (searchText.getLayout() != null) {
591             // Surprising, but this can otherwise crash sometimes...
592             Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
593         }
594         jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
595         searchText.addTextChangedListener(searchTextWatcher);
596     }
597
598     // --------------------------------------------------------------------------
599     // Options Menu
600     // --------------------------------------------------------------------------
601
602     final Random random = new Random();
603
604     @Override
605     public boolean onCreateOptionsMenu(final Menu menu) {
606         application.onCreateGlobalOptionsMenu(this, menu);
607
608         {
609             final MenuItem randomWord = menu.add(getString(R.string.randomWord));
610             randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
611                 public boolean onMenuItemClick(final MenuItem menuItem) {
612                     final String word = index.sortedIndexEntries.get(random
613                             .nextInt(index.sortedIndexEntries.size())).token;
614                     setSearchText(word, true);
615                     return false;
616                 }
617             });
618         }
619
620         {
621             final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
622             dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
623                 public boolean onMenuItemClick(final MenuItem menuItem) {
624                     startActivity(DictionaryManagerActivity.getLaunchIntent());
625                     finish();
626                     return false;
627                 }
628             });
629         }
630
631         {
632             final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
633             aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
634                 public boolean onMenuItemClick(final MenuItem menuItem) {
635                     final Context context = getListView().getContext();
636                     final Dialog dialog = new Dialog(context);
637                     dialog.setContentView(R.layout.about_dictionary_dialog);
638                     final TextView textView = (TextView) dialog.findViewById(R.id.text);
639
640                     final String name = application.getDictionaryName(dictFile.getName());
641                     dialog.setTitle(name);
642
643                     final StringBuilder builder = new StringBuilder();
644                     final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
645                     dictionaryInfo.uncompressedBytes = dictFile.length();
646                     if (dictionaryInfo != null) {
647                         builder.append(dictionaryInfo.dictInfo).append("\n\n");
648                         builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
649                                 .append("\n");
650                         builder.append(
651                                 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
652                                 .append("\n");
653                         builder.append(
654                                 getString(R.string.dictionaryCreationTime,
655                                         dictionaryInfo.creationMillis)).append("\n");
656                         for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
657                             builder.append("\n");
658                             builder.append(getString(R.string.indexName, indexInfo.shortName))
659                                     .append("\n");
660                             builder.append(
661                                     getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
662                                     .append("\n");
663                         }
664                         builder.append("\n");
665                         builder.append(getString(R.string.sources)).append("\n");
666                         for (final EntrySource source : dictionary.sources) {
667                             builder.append(
668                                     getString(R.string.sourceInfo, source.getName(),
669                                             source.getNumEntries())).append("\n");
670                         }
671                     }
672                     // } else {
673                     // builder.append(getString(R.string.invalidDictionary));
674                     // }
675                     textView.setText(builder.toString());
676
677                     dialog.show();
678                     final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
679                     layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
680                     layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
681                     dialog.getWindow().setAttributes(layoutParams);
682                     return false;
683                 }
684             });
685         }
686
687         return true;
688     }
689
690     // --------------------------------------------------------------------------
691     // Context Menu + clicks
692     // --------------------------------------------------------------------------
693
694     @Override
695     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
696         AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
697         final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
698
699         final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
700                 wordList.getName()));
701         addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
702             public boolean onMenuItemClick(MenuItem item) {
703                 onAppendToWordList(row);
704                 return false;
705             }
706         });
707
708         final MenuItem copy = menu.add(android.R.string.copy);
709         copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
710             public boolean onMenuItemClick(MenuItem item) {
711                 onCopy(row);
712                 return false;
713             }
714         });
715
716         if (selectedSpannableText != null) {
717             final String selectedText = selectedSpannableText;
718             final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
719                     selectedSpannableText));
720             searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
721                 public boolean onMenuItemClick(MenuItem item) {
722                     int indexToUse = -1;
723                     for (int i = 0; i < dictionary.indices.size(); ++i) {
724                         final Index index = dictionary.indices.get(i);
725                         if (indexPrepFinished) {
726                             System.out.println("Doing index lookup: on " + selectedText);
727                             final IndexEntry indexEntry = index.findExact(selectedText);
728                             if (indexEntry != null) {
729                                 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
730                                         .getTokenRow(false);
731                                 if (tokenRow != null && tokenRow.hasMainEntry) {
732                                     indexToUse = i;
733                                     break;
734                                 }
735                             }
736                         } else {
737                             Log.w(LOG, "Skipping findExact on index " + index.shortName);
738                         }
739                     }
740                     if (indexToUse == -1) {
741                         indexToUse = selectedSpannableIndex;
742                     }
743                     final boolean changeIndex = indexIndex != indexToUse;
744                     setSearchText(selectedText, !changeIndex); // If we're not
745                                                                // changing
746                                                                // index, we have
747                                                                // to
748                                                                // triggerSearch.
749                     if (changeIndex) {
750                         changeIndexGetFocusAndResearch(indexToUse);
751                     }
752                     // Give focus back to list view because typing is done.
753                     getListView().requestFocus();
754                     return false;
755                 }
756             });
757         }
758
759     }
760
761     @Override
762     protected void onListItemClick(ListView l, View v, int row, long id) {
763         defocusSearchText();
764         if (clickOpensContextMenu && dictRaf != null) {
765             openContextMenu(v);
766         }
767     }
768
769     void onAppendToWordList(final RowBase row) {
770         defocusSearchText();
771
772         final StringBuilder rawText = new StringBuilder();
773         rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
774         rawText.append(index.longName).append("\t");
775         rawText.append(row.getTokenRow(true).getToken()).append("\t");
776         rawText.append(row.getRawText(saveOnlyFirstSubentry));
777         Log.d(LOG, "Writing : " + rawText);
778
779         try {
780             wordList.getParentFile().mkdirs();
781             final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
782             out.println(rawText.toString());
783             out.close();
784         } catch (IOException e) {
785             Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
786             Toast.makeText(this,
787                     getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
788                     Toast.LENGTH_LONG).show();
789         }
790         return;
791     }
792
793     /**
794      * Called when user clicks outside of search text, so that they can start
795      * typing again immediately.
796      */
797     void defocusSearchText() {
798         // Log.d(LOG, "defocusSearchText");
799         // Request focus so that if we start typing again, it clears the text
800         // input.
801         getListView().requestFocus();
802
803         // Visual indication that a new keystroke will clear the search text.
804         searchText.selectAll();
805     }
806
807     @SuppressWarnings("deprecation")
808     void onCopy(final RowBase row) {
809         defocusSearchText();
810
811         Log.d(LOG, "Copy, row=" + row);
812         final StringBuilder result = new StringBuilder();
813         result.append(row.getRawText(false));
814         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
815         clipboardManager.setText(result.toString());
816         Log.d(LOG, "Copied: " + result);
817     }
818
819     @Override
820     public boolean onKeyDown(final int keyCode, final KeyEvent event) {
821         if (event.getUnicodeChar() != 0) {
822             if (!searchText.hasFocus()) {
823                 setSearchText("" + (char) event.getUnicodeChar(), true);
824             }
825             return true;
826         }
827         if (keyCode == KeyEvent.KEYCODE_BACK) {
828             // Log.d(LOG, "Clearing dictionary prefs.");
829             // Pretend that we just autolaunched so that we won't do it again.
830             // DictionaryManagerActivity.lastAutoLaunchMillis =
831             // System.currentTimeMillis();
832         }
833         if (keyCode == KeyEvent.KEYCODE_ENTER) {
834             Log.d(LOG, "Trying to hide soft keyboard.");
835             final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
836             inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
837                     InputMethodManager.HIDE_NOT_ALWAYS);
838             return true;
839         }
840         return super.onKeyDown(keyCode, event);
841     }
842
843     private void setSearchText(final String text, final boolean triggerSearch) {
844         if (!triggerSearch) {
845             getListView().requestFocus();
846         }
847         searchText.setText(text);
848         searchText.requestFocus();
849         moveCursorToRight();
850         if (triggerSearch) {
851             onSearchTextChange(text);
852         }
853     }
854
855     private long cursorDelayMillis = 100;
856
857     private void moveCursorToRight() {
858         if (searchText.getLayout() != null) {
859             cursorDelayMillis = 100;
860             // Surprising, but this can crash when you rotate...
861             Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
862         } else {
863             uiHandler.postDelayed(new Runnable() {
864                 @Override
865                 public void run() {
866                     moveCursorToRight();
867                 }
868             }, cursorDelayMillis);
869             cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
870         }
871     }
872
873     // --------------------------------------------------------------------------
874     // SearchOperation
875     // --------------------------------------------------------------------------
876
877     private void searchFinished(final SearchOperation searchOperation) {
878         if (searchOperation.interrupted.get()) {
879             Log.d(LOG, "Search operation was interrupted: " + searchOperation);
880             return;
881         }
882         if (searchOperation != this.currentSearchOperation) {
883             Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
884             return;
885         }
886
887         final Index.IndexEntry searchResult = searchOperation.searchResult;
888         Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
889
890         currentSearchOperation = null;
891         uiHandler.postDelayed(new Runnable() {
892             @Override
893             public void run() {
894                 if (currentSearchOperation == null) {
895                     if (searchResult != null) {
896                         if (isFiltered()) {
897                             clearFiltered();
898                         }
899                         jumpToRow(searchResult.startRow);
900                     } else if (searchOperation.multiWordSearchResult != null) {
901                         // Multi-row search....
902                         setFiltered(searchOperation);
903                     } else {
904                         throw new IllegalStateException("This should never happen.");
905                     }
906                 } else {
907                     Log.d(LOG, "More coming, waiting for currentSearchOperation.");
908                 }
909             }
910         }, 20);
911
912     }
913
914     private final void jumpToRow(final int row) {
915         setSelection(row);
916         getListView().setSelected(true);
917     }
918
919     static final Pattern WHITESPACE = Pattern.compile("\\s+");
920
921     final class SearchOperation implements Runnable {
922
923         final AtomicBoolean interrupted = new AtomicBoolean(false);
924
925         final String searchText;
926
927         List<String> searchTokens; // filled in for multiWord.
928
929         final Index index;
930
931         long searchStartMillis;
932
933         Index.IndexEntry searchResult;
934
935         List<RowBase> multiWordSearchResult;
936
937         boolean done = false;
938
939         SearchOperation(final String searchText, final Index index) {
940             this.searchText = searchText.trim();
941             this.index = index;
942         }
943
944         public String toString() {
945             return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
946         }
947
948         @Override
949         public void run() {
950             try {
951                 searchStartMillis = System.currentTimeMillis();
952                 final String[] searchTokenArray = WHITESPACE.split(searchText);
953                 if (searchTokenArray.length == 1) {
954                     searchResult = index.findInsertionPoint(searchText, interrupted);
955                 } else {
956                     searchTokens = Arrays.asList(searchTokenArray);
957                     multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
958                 }
959                 Log.d(LOG,
960                         "searchText=" + searchText + ", searchDuration="
961                                 + (System.currentTimeMillis() - searchStartMillis)
962                                 + ", interrupted=" + interrupted.get());
963                 if (!interrupted.get()) {
964                     uiHandler.post(new Runnable() {
965                         @Override
966                         public void run() {
967                             searchFinished(SearchOperation.this);
968                         }
969                     });
970                 }
971             } catch (Exception e) {
972                 Log.e(LOG, "Failure during search (can happen during Activity close.");
973             } finally {
974                 synchronized (this) {
975                     done = true;
976                     this.notifyAll();
977                 }
978             }
979         }
980     }
981
982     // --------------------------------------------------------------------------
983     // IndexAdapter
984     // --------------------------------------------------------------------------
985
986     static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
987             ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
988
989     static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
990             ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
991
992     final class IndexAdapter extends BaseAdapter {
993
994         final Index index;
995
996         final List<RowBase> rows;
997
998         final Set<String> toHighlight;
999
1000         IndexAdapter(final Index index) {
1001             this.index = index;
1002             rows = index.rows;
1003             this.toHighlight = null;
1004         }
1005
1006         IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1007             this.index = index;
1008             this.rows = rows;
1009             this.toHighlight = new LinkedHashSet<String>(toHighlight);
1010         }
1011
1012         @Override
1013         public int getCount() {
1014             return rows.size();
1015         }
1016
1017         @Override
1018         public RowBase getItem(int position) {
1019             return rows.get(position);
1020         }
1021
1022         @Override
1023         public long getItemId(int position) {
1024             return getItem(position).index();
1025         }
1026
1027         @Override
1028         public TableLayout getView(int position, View convertView, ViewGroup parent) {
1029             final TableLayout result;
1030             if (convertView instanceof TableLayout) {
1031                 result = (TableLayout) convertView;
1032                 result.removeAllViews();
1033             } else {
1034                 result = new TableLayout(parent.getContext());
1035             }
1036             final RowBase row = getItem(position);
1037             if (row instanceof PairEntry.Row) {
1038                 return getView(position, (PairEntry.Row) row, parent, result);
1039             } else if (row instanceof TokenRow) {
1040                 return getView((TokenRow) row, parent, result);
1041             } else if (row instanceof HtmlEntry.Row) {
1042                 return getView((HtmlEntry.Row) row, parent, result);
1043             } else {
1044                 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1045             }
1046         }
1047
1048         private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1049                 final TableLayout result) {
1050             final PairEntry entry = row.getEntry();
1051             final int rowCount = entry.pairs.size();
1052
1053             final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1054             layoutParams.weight = 0.5f;
1055
1056             for (int r = 0; r < rowCount; ++r) {
1057                 final TableRow tableRow = new TableRow(result.getContext());
1058
1059                 final TextView col1 = new TextView(tableRow.getContext());
1060                 final TextView col2 = new TextView(tableRow.getContext());
1061
1062                 // Set the columns in the table.
1063                 if (r > 0) {
1064                     final TextView bullet = new TextView(tableRow.getContext());
1065                     bullet.setText(" â€¢ ");
1066                     tableRow.addView(bullet);
1067                 }
1068                 tableRow.addView(col1, layoutParams);
1069                 final TextView margin = new TextView(tableRow.getContext());
1070                 margin.setText(" ");
1071                 tableRow.addView(margin);
1072                 if (r > 0) {
1073                     final TextView bullet = new TextView(tableRow.getContext());
1074                     bullet.setText(" â€¢ ");
1075                     tableRow.addView(bullet);
1076                 }
1077                 tableRow.addView(col2, layoutParams);
1078                 col1.setWidth(1);
1079                 col2.setWidth(1);
1080
1081                 // Set what's in the columns.
1082
1083                 final Pair pair = entry.pairs.get(r);
1084                 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1085                 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1086
1087                 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1088                 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1089
1090                 // Bold the token instances in col1.
1091                 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1092                         .singleton(row.getTokenRow(true).getToken());
1093                 final Spannable col1Spannable = (Spannable) col1.getText();
1094                 for (final String token : toBold) {
1095                     int startPos = 0;
1096                     while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1097                         col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1098                                 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1099                         startPos += token.length();
1100                     }
1101                 }
1102
1103                 createTokenLinkSpans(col1, col1Spannable, col1Text);
1104                 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1105
1106                 col1.setTypeface(typeface);
1107                 col2.setTypeface(typeface);
1108                 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1109                 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1110                 // col2.setBackgroundResource(theme.otherLangBg);
1111
1112                 if (index.swapPairEntries) {
1113                     col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1114                     col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1115                 } else {
1116                     col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1117                     col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1118                 }
1119
1120                 result.addView(tableRow);
1121             }
1122
1123             // Because we have a Button inside a ListView row:
1124             // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1125             result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1126             result.setClickable(true);
1127             result.setFocusable(true);
1128             result.setLongClickable(true);
1129             result.setBackgroundResource(android.R.drawable.menuitem_background);
1130             result.setOnClickListener(new TextView.OnClickListener() {
1131                 @Override
1132                 public void onClick(View v) {
1133                     DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1134                 }
1135             });
1136
1137             return result;
1138         }
1139
1140         private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1141             final Context context = parent.getContext();
1142
1143             final HtmlEntry htmlEntry = row.getEntry();
1144
1145             // final TableRow tableRow = new TableRow(context);
1146             final LinearLayout tableRow = new LinearLayout(context);
1147             result.addView(tableRow);
1148
1149             // Text.
1150             final TextView textView = new TextView(context);
1151             textView.setText(htmlEntry.title);
1152             textView.setLayoutParams(new LinearLayout.LayoutParams(0,
1153                     ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
1154             tableRow.addView(textView);
1155
1156             // Button.
1157             final Button button = new Button(context);
1158             button.setText("open");
1159             button.setLayoutParams(new LinearLayout.LayoutParams(
1160                     ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.0f));
1161             tableRow.addView(button);
1162
1163             button.setOnClickListener(new OnClickListener() {
1164                 @Override
1165                 public void onClick(View v) {
1166                     startActivity(HtmlDisplayActivity.getHtmlIntent(String.format(
1167                             "<html><head></head><body>%s</body></html>", htmlEntry.html)));
1168                 }
1169             });
1170
1171             return result;
1172         }
1173
1174         private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1175             final Context context = parent.getContext();
1176             final TextView textView = new TextView(context);
1177             textView.setText(row.getToken());
1178             // Doesn't work:
1179             // textView.setTextColor(android.R.color.secondary_text_light);
1180             textView.setTextAppearance(context, theme.tokenRowFg);
1181             textView.setTypeface(typeface);
1182             textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
1183
1184             final TableRow tableRow = new TableRow(result.getContext());
1185             tableRow.addView(textView);
1186             tableRow.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg
1187                     : theme.tokenRowOtherBg);
1188             result.addView(tableRow);
1189             return result;
1190         }
1191
1192     }
1193
1194     static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1195
1196     private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1197             final String text) {
1198         // Saw from the source code that LinkMovementMethod sets the selection!
1199         // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1200         textView.setMovementMethod(LinkMovementMethod.getInstance());
1201         final Matcher matcher = CHAR_DASH.matcher(text);
1202         while (matcher.find()) {
1203             spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(),
1204                     Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1205         }
1206     }
1207
1208     String selectedSpannableText = null;
1209
1210     int selectedSpannableIndex = -1;
1211
1212     @Override
1213     public boolean onTouchEvent(MotionEvent event) {
1214         selectedSpannableText = null;
1215         selectedSpannableIndex = -1;
1216         return super.onTouchEvent(event);
1217     }
1218
1219     private class TextViewLongClickListener implements OnLongClickListener {
1220         final int index;
1221
1222         private TextViewLongClickListener(final int index) {
1223             this.index = index;
1224         }
1225
1226         @Override
1227         public boolean onLongClick(final View v) {
1228             final TextView textView = (TextView) v;
1229             final int start = textView.getSelectionStart();
1230             final int end = textView.getSelectionEnd();
1231             if (start >= 0 && end >= 0) {
1232                 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1233                 selectedSpannableIndex = index;
1234             }
1235             return false;
1236         }
1237     }
1238
1239     final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1240             0);
1241
1242     final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1243             1);
1244
1245     // --------------------------------------------------------------------------
1246     // SearchText
1247     // --------------------------------------------------------------------------
1248
1249     void onSearchTextChange(final String text) {
1250         if ("thadolina".equals(text)) {
1251             final Dialog dialog = new Dialog(getListView().getContext());
1252             dialog.setContentView(R.layout.thadolina_dialog);
1253             dialog.setTitle("Ti amo, amore mio!");
1254             final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1255             imageView.setOnClickListener(new OnClickListener() {
1256                 @Override
1257                 public void onClick(View v) {
1258                     final Intent intent = new Intent(Intent.ACTION_VIEW);
1259                     intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1260                     startActivity(intent);
1261                 }
1262             });
1263             dialog.show();
1264         }
1265         if (dictRaf == null) {
1266             Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1267             return;
1268         }
1269         if (!searchText.isFocused()) {
1270             Log.d(LOG, "searchText changed without focus, doing nothing.");
1271             return;
1272         }
1273         Log.d(LOG, "onSearchTextChange: " + text);
1274         if (currentSearchOperation != null) {
1275             Log.d(LOG, "Interrupting currentSearchOperation.");
1276             currentSearchOperation.interrupted.set(true);
1277         }
1278         currentSearchOperation = new SearchOperation(text, index);
1279         searchExecutor.execute(currentSearchOperation);
1280     }
1281
1282     private class SearchTextWatcher implements TextWatcher {
1283         public void afterTextChanged(final Editable searchTextEditable) {
1284             if (searchText.hasFocus()) {
1285                 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
1286                 // If they were typing to cause the change, update the UI.
1287                 onSearchTextChange(searchText.getText().toString());
1288             }
1289         }
1290
1291         public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1292         }
1293
1294         public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1295         }
1296     }
1297
1298     // --------------------------------------------------------------------------
1299     // Filtered results.
1300     // --------------------------------------------------------------------------
1301
1302     boolean isFiltered() {
1303         return rowsToShow != null;
1304     }
1305
1306     void setFiltered(final SearchOperation searchOperation) {
1307         ((Button) findViewById(R.id.UpButton)).setEnabled(false);
1308         ((Button) findViewById(R.id.DownButton)).setEnabled(false);
1309         rowsToShow = searchOperation.multiWordSearchResult;
1310         setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1311     }
1312
1313     void clearFiltered() {
1314         ((Button) findViewById(R.id.UpButton)).setEnabled(true);
1315         ((Button) findViewById(R.id.DownButton)).setEnabled(true);
1316         setListAdapter(new IndexAdapter(index));
1317         rowsToShow = null;
1318     }
1319
1320 }