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