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