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