]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryActivity.java
66aee42061b2aa9267dc54c712527eaf7b335ee7
[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.DictionaryInfo.IndexInfo;\r
77 import com.hughes.android.dictionary.engine.Dictionary;\r
78 import com.hughes.android.dictionary.engine.Index;\r
79 import com.hughes.android.dictionary.engine.PairEntry;\r
80 import com.hughes.android.dictionary.engine.PairEntry.Pair;\r
81 import com.hughes.android.dictionary.engine.RowBase;\r
82 import com.hughes.android.dictionary.engine.TokenRow;\r
83 import com.hughes.android.dictionary.engine.TransliteratorManager;\r
84 import com.hughes.android.util.IntentLauncher;\r
85 import com.hughes.android.util.NonLinkClickableSpan;\r
86 \r
87 public class DictionaryActivity extends ListActivity {\r
88 \r
89   static final String LOG = "QuickDic";\r
90   \r
91   DictionaryApplication application;\r
92   File dictFile = null;\r
93   RandomAccessFile dictRaf = null;\r
94   Dictionary dictionary = null;\r
95   int indexIndex = 0;\r
96   Index index = null;\r
97   \r
98   // package for test.\r
99   final Handler uiHandler = new Handler();\r
100   private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {\r
101     @Override\r
102     public Thread newThread(Runnable r) {\r
103       return new Thread(r, "searchExecutor");\r
104     }\r
105   });\r
106   private SearchOperation currentSearchOperation = null;\r
107 \r
108   C.Theme theme = C.Theme.LIGHT;\r
109   int fontSizeSp;\r
110   EditText searchText;\r
111   Button langButton;\r
112 \r
113   // Never null.\r
114   private File wordList = null;\r
115   private boolean saveOnlyFirstSubentry = false;\r
116   private boolean clickOpensContextMenu = false;\r
117 \r
118   // Visible for testing.\r
119   ListAdapter indexAdapter = null;\r
120   \r
121   final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();\r
122 \r
123   public DictionaryActivity() {\r
124   }\r
125   \r
126   public static Intent getLaunchIntent(final File dictFile, final int indexIndex, final String searchToken) {\r
127     final Intent intent = new Intent();\r
128     intent.setClassName(DictionaryActivity.class.getPackage().getName(), DictionaryActivity.class.getName());\r
129     intent.putExtra(C.DICT_FILE, dictFile.getPath());\r
130     intent.putExtra(C.INDEX_INDEX, indexIndex);\r
131     intent.putExtra(C.SEARCH_TOKEN, searchToken);\r
132     return intent;\r
133   }\r
134   \r
135   @Override\r
136   protected void onSaveInstanceState(final Bundle outState) {\r
137     super.onSaveInstanceState(outState);\r
138     outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());\r
139   }\r
140 \r
141   @Override\r
142   protected void onRestoreInstanceState(final Bundle outState) {\r
143     super.onRestoreInstanceState(outState);\r
144     setSearchText(outState.getString(C.SEARCH_TOKEN));\r
145   }\r
146 \r
147   @Override\r
148   public void onCreate(Bundle savedInstanceState) {    \r
149     Log.d(LOG, "onCreate:" + this);\r
150     super.onCreate(savedInstanceState);\r
151 \r
152     application = (DictionaryApplication) getApplication();\r
153     theme = application.getSelectedTheme();\r
154 \r
155     // Clear them so that if something goes wrong, we won't relaunch.\r
156     clearDictionaryPrefs(this);\r
157     \r
158     final Intent intent = getIntent();\r
159     dictFile = new File(intent.getStringExtra(C.DICT_FILE));\r
160     \r
161     try {\r
162       final String name = application.getDictionaryName(dictFile.getName());\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(v.getContext());\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 File 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.getPath());\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 Intent intent;\r
407 \r
408     public OpenIndexButton(final Context context, final Activity activity, final String text, final Intent intent) {\r
409       super(context);\r
410       this.activity = activity;\r
411       this.intent = intent;\r
412       setOnClickListener(this);\r
413       setText(text, BufferType.NORMAL);\r
414     }\r
415 \r
416     @Override\r
417     public void onClick(View v) {\r
418       activity.finish();\r
419       getContext().startActivity(intent);\r
420     }\r
421     \r
422   }\r
423 \r
424   void onLanguageButtonLongClick(final Context context) {\r
425     final Dialog dialog = new Dialog(context);\r
426     dialog.setContentView(R.layout.select_dictionary_dialog);\r
427     dialog.setTitle(R.string.selectDictionary);\r
428 \r
429     final List<DictionaryInfo> installedDicts = ((DictionaryApplication)getApplication()).getUsableDicts();\r
430     ListView listView = (ListView) dialog.findViewById(android.R.id.list);\r
431     listView.setAdapter(new BaseAdapter() {\r
432       @Override\r
433       public View getView(int position, View convertView, ViewGroup parent) {\r
434         final LinearLayout result = new LinearLayout(parent.getContext());\r
435         final DictionaryInfo dictionaryInfo = getItem(position);\r
436         for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {\r
437           final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);\r
438           final Button button = new Button(parent.getContext());\r
439           String name = application.getLanguageName(indexInfo.shortName);\r
440           if (name == null) {\r
441             name = indexInfo.shortName;\r
442           }\r
443           button.setText(name);\r
444           final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(), getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename), i, "")) {\r
445             @Override\r
446             protected void onGo() {\r
447               dialog.dismiss();\r
448               DictionaryActivity.this.finish();\r
449             };\r
450           };\r
451           button.setOnClickListener(intentLauncher);\r
452           \r
453           final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);\r
454           layoutParams.width = 0;\r
455           layoutParams.weight = 1.0f;\r
456           button.setLayoutParams(layoutParams);\r
457 \r
458           result.addView(button);\r
459         }\r
460         return result;\r
461       }\r
462       \r
463       @Override\r
464       public long getItemId(int position) {\r
465         return position;\r
466       }\r
467       \r
468       @Override\r
469       public DictionaryInfo getItem(int position) {\r
470         return installedDicts.get(position);\r
471       }\r
472       \r
473       @Override\r
474       public int getCount() {\r
475         return installedDicts.size();\r
476       }\r
477     });\r
478     \r
479     dialog.show();\r
480   }\r
481 \r
482 \r
483   private void changeIndex(final int newIndex) {\r
484     indexIndex = newIndex;\r
485     index = dictionary.indices.get(indexIndex);\r
486     indexAdapter = new IndexAdapter(index);\r
487     Log.d(LOG, "changingIndex, newLang=" + index.longName);\r
488     setListAdapter(indexAdapter);\r
489     updateLangButton();\r
490     searchText.requestFocus();  // Otherwise, nothing may happen.\r
491     onSearchTextChange(searchText.getText().toString());\r
492   }\r
493   \r
494   void onUpDownButton(final boolean up) {\r
495     final int firstVisibleRow = getListView().getFirstVisiblePosition();\r
496     final RowBase row = index.rows.get(firstVisibleRow);\r
497     final TokenRow tokenRow = row.getTokenRow(true);\r
498     final int destIndexEntry;\r
499     if (up) {\r
500       if (row != tokenRow) {\r
501         destIndexEntry = tokenRow.referenceIndex;\r
502       } else {\r
503         destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);\r
504       }\r
505     } else {\r
506       // Down\r
507       destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());\r
508     }\r
509     final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);\r
510     Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);\r
511     searchText.removeTextChangedListener(searchTextWatcher);\r
512     searchText.setText(dest.token);\r
513     jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);\r
514     searchText.addTextChangedListener(searchTextWatcher);\r
515   }\r
516 \r
517   // --------------------------------------------------------------------------\r
518   // Options Menu\r
519   // --------------------------------------------------------------------------\r
520   \r
521   @Override\r
522   public boolean onCreateOptionsMenu(final Menu menu) {\r
523     application.onCreateGlobalOptionsMenu(this, menu);\r
524 \r
525     {\r
526       final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));\r
527       dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {\r
528         public boolean onMenuItemClick(final MenuItem menuItem) {\r
529           startActivity(DictionaryManagerActivity.getLaunchIntent());\r
530           finish();\r
531           return false;\r
532         }\r
533       });\r
534     }\r
535 \r
536     return true;\r
537   }\r
538 \r
539 \r
540   // --------------------------------------------------------------------------\r
541   // Context Menu + clicks\r
542   // --------------------------------------------------------------------------\r
543 \r
544   @Override\r
545   public void onCreateContextMenu(ContextMenu menu, View v,\r
546       ContextMenuInfo menuInfo) {\r
547     AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;\r
548     final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);\r
549 \r
550     final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList, wordList.getName()));\r
551     addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {\r
552       public boolean onMenuItemClick(MenuItem item) {\r
553         onAppendToWordList(row);\r
554         return false;\r
555       }\r
556     });\r
557 \r
558     final MenuItem copy = menu.add(android.R.string.copy);\r
559     copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {\r
560       public boolean onMenuItemClick(MenuItem item) {\r
561         onCopy(row);\r
562         return false;\r
563       }\r
564     });\r
565     \r
566     if (selectedSpannableText != null) {\r
567       final String selectedText = selectedSpannableText;\r
568       final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection, selectedSpannableText));\r
569       searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {\r
570         public boolean onMenuItemClick(MenuItem item) {\r
571           if (indexIndex != selectedSpannableIndex) {\r
572             changeIndex(selectedSpannableIndex);\r
573           }\r
574           setSearchText(selectedText);\r
575           return false;\r
576         }\r
577       });\r
578     }\r
579     \r
580 \r
581   }\r
582   \r
583   @Override\r
584   protected void onListItemClick(ListView l, View v, int row, long id) {\r
585     defocusSearchText();\r
586     \r
587     if (clickOpensContextMenu && dictRaf != null) {\r
588       openContextMenu(v);\r
589     }\r
590   }\r
591   \r
592   void onAppendToWordList(final RowBase row) {\r
593     defocusSearchText();\r
594     \r
595     final StringBuilder rawText = new StringBuilder();\r
596     rawText.append(\r
597         new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date()))\r
598         .append("\t");\r
599     rawText.append(index.longName).append("\t");\r
600     rawText.append(row.getTokenRow(true).getToken()).append("\t");\r
601     rawText.append(row.getRawText(saveOnlyFirstSubentry));\r
602     Log.d(LOG, "Writing : " + rawText);\r
603 \r
604     try {\r
605       wordList.getParentFile().mkdirs();\r
606       final PrintWriter out = new PrintWriter(\r
607           new FileWriter(wordList, true));\r
608       out.println(rawText.toString());\r
609       out.close();\r
610     } catch (IOException e) {\r
611       Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);\r
612       Toast.makeText(this, getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()), Toast.LENGTH_LONG);\r
613     }\r
614     return;\r
615   }\r
616   \r
617   /**\r
618    * Called when user clicks outside of search text, so that they can start\r
619    * typing again immediately.\r
620    */\r
621   void defocusSearchText() {\r
622     //Log.d(LOG, "defocusSearchText");\r
623     // Request focus so that if we start typing again, it clears the text input.\r
624     getListView().requestFocus();\r
625     \r
626     // Visual indication that a new keystroke will clear the search text.\r
627     searchText.selectAll();\r
628   }\r
629 \r
630   void onCopy(final RowBase row) {\r
631     defocusSearchText();\r
632 \r
633     Log.d(LOG, "Copy, row=" + row);\r
634     final StringBuilder result = new StringBuilder();\r
635     result.append(row.getRawText(false));\r
636     final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\r
637     clipboardManager.setText(result.toString());\r
638     Log.d(LOG, "Copied: " + result);\r
639   }\r
640 \r
641   @Override\r
642   public boolean onKeyDown(final int keyCode, final KeyEvent event) {\r
643     if (event.getUnicodeChar() != 0) {\r
644       if (!searchText.hasFocus()) {\r
645         setSearchText("" + (char) event.getUnicodeChar());\r
646       }\r
647       return true;\r
648     }\r
649     if (keyCode == KeyEvent.KEYCODE_BACK) {\r
650       Log.d(LOG, "Clearing dictionary prefs.");\r
651       DictionaryActivity.clearDictionaryPrefs(this);\r
652     }\r
653     if (keyCode == KeyEvent.KEYCODE_ENTER) {\r
654       Log.d(LOG, "Trying to hide soft keyboard.");\r
655       final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);\r
656       inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);\r
657       return true;\r
658     }\r
659     return super.onKeyDown(keyCode, event);\r
660   }\r
661 \r
662   private void setSearchText(final String text) {\r
663     searchText.setText(text);\r
664     searchText.requestFocus();\r
665     onSearchTextChange(searchText.getText().toString());\r
666     Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());\r
667   }\r
668 \r
669 \r
670   // --------------------------------------------------------------------------\r
671   // SearchOperation\r
672   // --------------------------------------------------------------------------\r
673 \r
674   private void searchFinished(final SearchOperation searchOperation) {\r
675     if (searchOperation.interrupted.get()) {\r
676       Log.d(LOG, "Search operation was interrupted: " + searchOperation);\r
677       return;\r
678     }\r
679     if (searchOperation != this.currentSearchOperation) {\r
680       Log.d(LOG, "Stale searchOperation finished: " + searchOperation);\r
681       return;\r
682     }\r
683     \r
684     final Index.IndexEntry searchResult = searchOperation.searchResult;\r
685     Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);\r
686 \r
687     currentSearchOperation = null;\r
688 \r
689     uiHandler.postDelayed(new Runnable() {\r
690       @Override\r
691       public void run() {\r
692         if (currentSearchOperation == null) {\r
693           jumpToRow(searchResult.startRow);\r
694         } else {\r
695           Log.d(LOG, "More coming, waiting for currentSearchOperation.");\r
696         }\r
697       }\r
698     }, 50);\r
699     \r
700 //    if (!searchResult.success) {\r
701 //      if (vibrator != null) {\r
702 //        vibrator.vibrate(VIBRATE_MILLIS);\r
703 //      }\r
704 //      searchText.setText(searchResult.longestPrefixString);\r
705 //      searchText.setSelection(searchResult.longestPrefixString.length());\r
706 //      return;\r
707 //    }\r
708     \r
709   }\r
710   \r
711   private final void jumpToRow(final int row) {\r
712     setSelection(row);\r
713     getListView().setSelected(true);\r
714   }\r
715 \r
716   final class SearchOperation implements Runnable {\r
717     \r
718     final AtomicBoolean interrupted = new AtomicBoolean(false);\r
719     final String searchText;\r
720     final Index index;\r
721     \r
722     long searchStartMillis;\r
723 \r
724     Index.IndexEntry searchResult;\r
725     \r
726     boolean done = false;\r
727     \r
728     SearchOperation(final String searchText, final Index index) {\r
729       this.searchText = searchText.trim();\r
730       this.index = index;\r
731     }\r
732     \r
733     public String toString() {\r
734       return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());\r
735     }\r
736 \r
737     @Override\r
738     public void run() {\r
739       try {\r
740         searchStartMillis = System.currentTimeMillis();\r
741         searchResult = index.findInsertionPoint(searchText, interrupted);\r
742         Log.d(LOG, "searchText=" + searchText + ", searchDuration="\r
743             + (System.currentTimeMillis() - searchStartMillis) + ", interrupted="\r
744             + interrupted.get());\r
745         if (!interrupted.get()) {\r
746           uiHandler.post(new Runnable() {\r
747             @Override\r
748             public void run() {            \r
749               searchFinished(SearchOperation.this);\r
750             }\r
751           });\r
752         }\r
753       } finally {\r
754         synchronized (this) {\r
755           done = true;\r
756           this.notifyAll();\r
757         }\r
758       }\r
759     }\r
760   }\r
761 \r
762   \r
763   // --------------------------------------------------------------------------\r
764   // IndexAdapter\r
765   // --------------------------------------------------------------------------\r
766 \r
767   final class IndexAdapter extends BaseAdapter {\r
768     \r
769     final Index index;\r
770 \r
771     IndexAdapter(final Index index) {\r
772       this.index = index;\r
773     }\r
774 \r
775     @Override\r
776     public int getCount() {\r
777       return index.rows.size();\r
778     }\r
779 \r
780     @Override\r
781     public RowBase getItem(int position) {\r
782       return index.rows.get(position);\r
783     }\r
784 \r
785     @Override\r
786     public long getItemId(int position) {\r
787       return getItem(position).index();\r
788     }\r
789 \r
790     @Override\r
791     public View getView(int position, final View convertView, ViewGroup parent) {\r
792       final RowBase row = index.rows.get(position);\r
793       if (row instanceof PairEntry.Row) {\r
794         return getView((PairEntry.Row) row, parent, convertView);\r
795       } else if (row instanceof TokenRow) {\r
796         return getView((TokenRow) row, parent, convertView);\r
797       } else {\r
798         throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());\r
799       }\r
800     }\r
801 \r
802     private View getView(PairEntry.Row row, ViewGroup parent, final View convertView) {\r
803       final TableLayout result = new TableLayout(parent.getContext());\r
804       final PairEntry entry = row.getEntry();\r
805       final int rowCount = entry.pairs.size();\r
806       for (int r = 0; r < rowCount; ++r) {\r
807         final TableRow tableRow = new TableRow(result.getContext());\r
808 \r
809         final TextView col1 = new TextView(tableRow.getContext());\r
810         final TextView col2 = new TextView(tableRow.getContext());\r
811         final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();\r
812         layoutParams.weight = 0.5f;\r
813 \r
814         // Set the columns in the table.\r
815         if (r > 0) {\r
816           final TextView bullet = new TextView(tableRow.getContext());\r
817           bullet.setText(" • ");\r
818           tableRow.addView(bullet);\r
819         }\r
820         tableRow.addView(col1, layoutParams);\r
821         final TextView margin = new TextView(tableRow.getContext());\r
822         margin.setText(" ");\r
823         tableRow.addView(margin);\r
824         if (r > 0) {\r
825           final TextView bullet = new TextView(tableRow.getContext());\r
826           bullet.setText(" • ");\r
827           tableRow.addView(bullet);\r
828         }\r
829         tableRow.addView(col2, layoutParams);\r
830         col1.setWidth(1);\r
831         col2.setWidth(1);\r
832         \r
833         // Set what's in the columns.\r
834 \r
835         // TODO: color words by gender\r
836         final Pair pair = entry.pairs.get(r);\r
837         final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;\r
838         final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;\r
839         \r
840         col1.setText(col1Text, TextView.BufferType.SPANNABLE);\r
841         col2.setText(col2Text, TextView.BufferType.SPANNABLE);\r
842         \r
843         // Bold the token instances in col1.\r
844         final Spannable col1Spannable = (Spannable) col1.getText();\r
845         int startPos = 0;\r
846         final String token = row.getTokenRow(true).getToken();\r
847         while ((startPos = col1Text.indexOf(token, startPos)) != -1) {\r
848           col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos,\r
849               startPos + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);\r
850           startPos += token.length();\r
851         }\r
852         \r
853         createTokenLinkSpans(col1, col1Spannable, col1Text);\r
854         createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);\r
855         \r
856         col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);\r
857         col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);\r
858         // col2.setBackgroundResource(theme.otherLangBg);\r
859         \r
860         if (index.swapPairEntries) {\r
861           col2.setOnLongClickListener(textViewLongClickListenerIndex0);\r
862           col1.setOnLongClickListener(textViewLongClickListenerIndex1);\r
863         } else {\r
864           col1.setOnLongClickListener(textViewLongClickListenerIndex0);\r
865           col2.setOnLongClickListener(textViewLongClickListenerIndex1);\r
866         }\r
867         \r
868         result.addView(tableRow);\r
869       }\r
870 \r
871       return result;\r
872 \r
873       \r
874 //      final WebView result = (WebView) (convertView instanceof WebView ? convertView : new WebView(parent.getContext()));\r
875 //        \r
876 //      final PairEntry entry = row.getEntry();\r
877 //      final int rowCount = entry.pairs.size();\r
878 //      final StringBuilder html = new StringBuilder();\r
879 //      html.append("<html><body><table width=\"100%\">");\r
880 //      for (int r = 0; r < rowCount; ++r) {\r
881 //        html.append("<tr>");\r
882 //\r
883 //        final Pair pair = entry.pairs.get(r);\r
884 //        // TODO: escape both the token and the text.\r
885 //        final String token = row.getTokenRow(true).getToken();\r
886 //        final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;\r
887 //        final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;\r
888 //        \r
889 //        col1Text.replaceAll(token, String.format("<b>%s</b>", token));\r
890 //\r
891 //        // Column1\r
892 //        html.append("<td width=\"50%\">");\r
893 //        if (r > 0) {\r
894 //          html.append("<li>");\r
895 //        }\r
896 //        html.append(col1Text);\r
897 //        html.append("</td>");\r
898 //\r
899 //        // Column2\r
900 //        html.append("<td width=\"50%\">");\r
901 //        if (r > 0) {\r
902 //          html.append("<li>");\r
903 //        }\r
904 //        html.append(col2Text);\r
905 //        html.append("</td>");\r
906 //\r
907 ////        column1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);\r
908 ////        column2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);\r
909 //\r
910 //        html.append("</tr>");\r
911 //      }\r
912 //      html.append("</table></body></html>");\r
913 //      \r
914 //      Log.i(LOG, html.toString());\r
915 //      \r
916 //      result.getSettings().setRenderPriority(RenderPriority.HIGH);\r
917 //      result.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);\r
918 //      \r
919 //      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
920 //\r
921 //      return result;\r
922     }\r
923 \r
924     private View getView(TokenRow row, ViewGroup parent, final View convertView) {\r
925       final Context context = parent.getContext();\r
926       final TextView textView = new TextView(context);\r
927       textView.setText(row.getToken());\r
928       textView.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg : theme.tokenRowOtherBg);\r
929       // Doesn't work:\r
930       //textView.setTextColor(android.R.color.secondary_text_light);\r
931       textView.setTextAppearance(context, theme.tokenRowFg);\r
932       textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);\r
933       return textView;\r
934     }\r
935     \r
936   }\r
937 \r
938   static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}0-9]+");\r
939 \r
940   private void createTokenLinkSpans(final TextView textView, final Spannable spannable, final String text) {\r
941     // Saw from the source code that LinkMovementMethod sets the selection!\r
942     // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod\r
943     textView.setMovementMethod(LinkMovementMethod.getInstance());\r
944     final Matcher matcher = CHAR_DASH.matcher(text);\r
945     while (matcher.find()) {\r
946       spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);\r
947     }\r
948   }\r
949   \r
950 \r
951   String selectedSpannableText = null;\r
952   int selectedSpannableIndex = -1;\r
953 \r
954   @Override\r
955   public boolean onTouchEvent(MotionEvent event) {\r
956     selectedSpannableText = null;\r
957     selectedSpannableIndex = -1;\r
958     return super.onTouchEvent(event);\r
959   }\r
960 \r
961   private class TextViewLongClickListener implements OnLongClickListener {\r
962     final int index;\r
963     \r
964     private TextViewLongClickListener(final int index) {\r
965       this.index = index;\r
966     }\r
967 \r
968     @Override\r
969     public boolean onLongClick(final View v) {\r
970       final TextView textView = (TextView) v;\r
971       final int start = textView.getSelectionStart();\r
972       final int end = textView.getSelectionEnd();\r
973       if (start >= 0 &&  end >= 0) {\r
974         selectedSpannableText = textView.getText().subSequence(start, end).toString();\r
975         selectedSpannableIndex = index;\r
976       }\r
977       return false;\r
978     }\r
979   }\r
980   final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(0);\r
981   final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(1);\r
982   \r
983 \r
984   // --------------------------------------------------------------------------\r
985   // SearchText\r
986   // --------------------------------------------------------------------------\r
987 \r
988   void onSearchTextChange(final String text) {\r
989     if (dictRaf == null) {\r
990       Log.d(LOG, "searchText changed during shutdown, doing nothing.");\r
991       return;\r
992     }\r
993     if (!searchText.isFocused()) {\r
994       Log.d(LOG, "searchText changed without focus, doing nothing.");\r
995       return;\r
996     }\r
997     Log.d(LOG, "onSearchTextChange: " + text);    \r
998     if (currentSearchOperation != null) {\r
999       Log.d(LOG, "Interrupting currentSearchOperation.");\r
1000       currentSearchOperation.interrupted.set(true);\r
1001     }\r
1002     currentSearchOperation = new SearchOperation(text, index);\r
1003     searchExecutor.execute(currentSearchOperation);\r
1004   }\r
1005   \r
1006   private class SearchTextWatcher implements TextWatcher {\r
1007     public void afterTextChanged(final Editable searchTextEditable) {\r
1008       if (searchText.hasFocus()) {\r
1009         Log.d(LOG, "Search text changed with focus: " + searchText.getText());\r
1010         // If they were typing to cause the change, update the UI.\r
1011         onSearchTextChange(searchText.getText().toString());\r
1012       }\r
1013     }\r
1014 \r
1015     public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,\r
1016         int arg3) {\r
1017     }\r
1018 \r
1019     public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {\r
1020     }\r
1021   }\r
1022 \r
1023 }\r