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