1 // Copyright 2011 Google Inc. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 package com.hughes.android.dictionary;
17 import android.app.Dialog;
18 import android.app.ListActivity;
19 import android.content.Context;
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.graphics.Color;
23 import android.graphics.Typeface;
24 import android.net.Uri;
25 import android.os.Bundle;
26 import android.os.Handler;
27 import android.preference.PreferenceManager;
28 import android.speech.tts.TextToSpeech;
29 import android.speech.tts.TextToSpeech.OnInitListener;
30 import android.text.ClipboardManager;
31 import android.text.Editable;
32 import android.text.Selection;
33 import android.text.Spannable;
34 import android.text.TextWatcher;
35 import android.text.method.LinkMovementMethod;
36 import android.text.style.ClickableSpan;
37 import android.text.style.StyleSpan;
38 import android.util.Log;
39 import android.util.TypedValue;
40 import android.view.ContextMenu;
41 import android.view.ContextMenu.ContextMenuInfo;
42 import android.view.KeyEvent;
43 import android.view.Menu;
44 import android.view.MenuItem;
45 import android.view.MenuItem.OnMenuItemClickListener;
46 import android.view.MotionEvent;
47 import android.view.View;
48 import android.view.View.OnClickListener;
49 import android.view.View.OnFocusChangeListener;
50 import android.view.View.OnLongClickListener;
51 import android.view.ViewGroup;
52 import android.view.WindowManager;
53 import android.view.inputmethod.InputMethodManager;
54 import android.widget.AdapterView.AdapterContextMenuInfo;
55 import android.widget.BaseAdapter;
56 import android.widget.Button;
57 import android.widget.EditText;
58 import android.widget.ImageButton;
59 import android.widget.ImageView;
60 import android.widget.LinearLayout;
61 import android.widget.ListAdapter;
62 import android.widget.ListView;
63 import android.widget.TableLayout;
64 import android.widget.TableRow;
65 import android.widget.TextView;
66 import android.widget.TextView.BufferType;
67 import android.widget.Toast;
69 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
70 import com.hughes.android.dictionary.engine.Dictionary;
71 import com.hughes.android.dictionary.engine.EntrySource;
72 import com.hughes.android.dictionary.engine.HtmlEntry;
73 import com.hughes.android.dictionary.engine.Index;
74 import com.hughes.android.dictionary.engine.Index.IndexEntry;
75 import com.hughes.android.dictionary.engine.PairEntry;
76 import com.hughes.android.dictionary.engine.PairEntry.Pair;
77 import com.hughes.android.dictionary.engine.RowBase;
78 import com.hughes.android.dictionary.engine.TokenRow;
79 import com.hughes.android.dictionary.engine.TransliteratorManager;
80 import com.hughes.android.util.IntentLauncher;
81 import com.hughes.android.util.NonLinkClickableSpan;
82 import com.hughes.util.StringUtil;
85 import java.io.FileWriter;
86 import java.io.IOException;
87 import java.io.PrintWriter;
88 import java.io.RandomAccessFile;
89 import java.text.SimpleDateFormat;
90 import java.util.Arrays;
91 import java.util.Collections;
92 import java.util.Date;
93 import java.util.HashMap;
94 import java.util.LinkedHashSet;
95 import java.util.List;
96 import java.util.Locale;
97 import java.util.Random;
99 import java.util.concurrent.Executor;
100 import java.util.concurrent.Executors;
101 import java.util.concurrent.ThreadFactory;
102 import java.util.concurrent.atomic.AtomicBoolean;
103 import java.util.regex.Matcher;
104 import java.util.regex.Pattern;
106 public class DictionaryActivity extends ListActivity {
108 static final String LOG = "QuickDic";
110 DictionaryApplication application;
112 File dictFile = null;
114 RandomAccessFile dictRaf = null;
116 Dictionary dictionary = null;
122 List<RowBase> rowsToShow = null; // if not null, just show these rows.
125 final Handler uiHandler = new Handler();
127 TextToSpeech textToSpeech;
128 volatile boolean ttsReady;
130 int textColorFg = Color.BLACK;
132 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
134 public Thread newThread(Runnable r) {
135 return new Thread(r, "searchExecutor");
139 private SearchOperation currentSearchOperation = null;
141 C.Theme theme = C.Theme.LIGHT;
152 private File wordList = null;
154 private boolean saveOnlyFirstSubentry = false;
156 private boolean clickOpensContextMenu = false;
158 // Visible for testing.
159 ListAdapter indexAdapter = null;
161 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
164 * For some languages, loading the transliterators used in this search takes
165 * a long time, so we fire it up on a different thread, and don't invoke it
166 * from the main thread until it's already finished once.
168 private volatile boolean indexPrepFinished = false;
170 public DictionaryActivity() {
173 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
174 final String searchToken) {
175 final Intent intent = new Intent();
176 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
177 DictionaryActivity.class.getName());
178 intent.putExtra(C.DICT_FILE, dictFile.getPath());
179 intent.putExtra(C.INDEX_INDEX, indexIndex);
180 intent.putExtra(C.SEARCH_TOKEN, searchToken);
185 protected void onSaveInstanceState(final Bundle outState) {
186 super.onSaveInstanceState(outState);
187 Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
188 outState.putInt(C.INDEX_INDEX, indexIndex);
189 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
193 protected void onRestoreInstanceState(final Bundle outState) {
194 super.onRestoreInstanceState(outState);
195 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
200 public void onCreate(Bundle savedInstanceState) {
201 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
202 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
205 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
207 Log.d(LOG, "onCreate:" + this);
208 super.onCreate(savedInstanceState);
210 application = (DictionaryApplication) getApplication();
211 theme = application.getSelectedTheme();
212 textColorFg = getResources().getColor(theme.tokenRowFgColor);
214 final Intent intent = getIntent();
215 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
218 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
220 public void onInit(int status) {
227 final String name = application.getDictionaryName(dictFile.getName());
228 this.setTitle("QuickDic: " + name);
229 dictRaf = new RandomAccessFile(dictFile, "r");
230 dictionary = new Dictionary(dictRaf);
231 } catch (Exception e) {
232 Log.e(LOG, "Unable to load dictionary.", e);
233 if (dictRaf != null) {
236 } catch (IOException e1) {
237 Log.e(LOG, "Unable to close dictRaf.", e1);
241 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
242 Toast.LENGTH_LONG).show();
243 startActivity(DictionaryManagerActivity.getLaunchIntent());
247 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
248 if (savedInstanceState != null) {
249 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
251 indexIndex %= dictionary.indices.size();
252 Log.d(LOG, "Loading index " + indexIndex);
253 index = dictionary.indices.get(indexIndex);
254 setListAdapter(new IndexAdapter(index));
256 // Pre-load the collators.
257 new Thread(new Runnable() {
259 final long startMillis = System.currentTimeMillis();
261 TransliteratorManager.init(new TransliteratorManager.Callback() {
263 public void onTransliteratorReady() {
264 uiHandler.post(new Runnable() {
267 onSearchTextChange(searchText.getText().toString());
273 for (final Index index : dictionary.indices) {
274 final String searchToken = index.sortedIndexEntries.get(0).token;
275 final IndexEntry entry = index.findExact(searchToken);
276 if (!searchToken.equals(entry.token)) {
277 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
280 indexPrepFinished = true;
281 } catch (Exception e) {
283 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
285 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
289 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
290 if ("SYSTEM".equals(fontName)) {
291 typeface = Typeface.DEFAULT;
294 typeface = Typeface.createFromAsset(getAssets(), fontName);
295 } catch (Exception e) {
296 Log.w(LOG, "Exception trying to use typeface, using default.", e);
297 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
298 Toast.LENGTH_LONG).show();
301 // if (!"SYSTEM".equals(fontName)) {
302 // throw new RuntimeException("Test force using system font: " +
305 if (typeface == null) {
306 Log.w(LOG, "Unable to create typeface, using default.");
307 typeface = Typeface.DEFAULT;
309 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
311 fontSizeSp = Integer.parseInt(fontSize.trim());
312 } catch (NumberFormatException e) {
316 setContentView(R.layout.dictionary_activity);
317 searchText = (EditText) findViewById(R.id.SearchText);
318 searchText.requestFocus();
319 searchText.addTextChangedListener(searchTextWatcher);
320 searchText.setOnFocusChangeListener(new OnFocusChangeListener() {
322 public void onFocusChange(View v, boolean hasFocus) {
323 Log.d(LOG, "searchText onFocusChange hasFocus=" + hasFocus);
327 // Set the search text from the intent, then the saved state.
328 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
329 if (savedInstanceState != null) {
330 text = savedInstanceState.getString(C.SEARCH_TOKEN);
335 setSearchText(text, true);
336 Log.d(LOG, "Trying to restore searchText=" + text);
338 final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
339 clearSearchTextButton.setOnClickListener(new OnClickListener() {
340 public void onClick(View v) {
341 onClearSearchTextButton();
344 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
345 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
348 langButton = (Button) findViewById(R.id.LangButton);
349 langButton.setOnClickListener(new OnClickListener() {
350 public void onClick(View v) {
354 langButton.setOnLongClickListener(new OnLongClickListener() {
356 public boolean onLongClick(View v) {
357 onLanguageButtonLongClick(v.getContext());
363 final View upButton = findViewById(R.id.UpButton);
364 upButton.setOnClickListener(new OnClickListener() {
365 public void onClick(View v) {
366 onUpDownButton(true);
369 final View downButton = findViewById(R.id.DownButton);
370 downButton.setOnClickListener(new OnClickListener() {
371 public void onClick(View v) {
372 onUpDownButton(false);
376 // getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
378 // public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
380 // if (!searchText.isFocused()) {
381 // if (!isFiltered()) {
382 // final RowBase row = (RowBase) getListAdapter().getItem(position);
383 // Log.d(LOG, "onItemSelected: " + row.index());
384 // final TokenRow tokenRow = row.getTokenRow(true);
385 // searchText.setText(tokenRow.getToken());
391 // public void onNothingSelected(AdapterView<?> arg0) {
396 registerForContextMenu(getListView());
399 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
400 getString(R.string.wordListFileDefault)));
401 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
403 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
405 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
407 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
409 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
411 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
415 protected void onResume() {
416 Log.d(LOG, "onResume");
418 if (PreferenceActivity.prefsMightHaveChanged) {
419 PreferenceActivity.prefsMightHaveChanged = false;
421 startActivity(getIntent());
427 protected void onPause() {
432 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
433 super.onActivityResult(requestCode, resultCode, result);
434 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
435 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
436 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
440 private static void setDictionaryPrefs(final Context context, final File dictFile,
441 final int indexIndex, final String searchToken) {
442 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
444 prefs.putString(C.DICT_FILE, dictFile.getPath());
445 prefs.putInt(C.INDEX_INDEX, indexIndex);
446 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
451 protected void onDestroy() {
453 if (dictRaf == null) {
457 final SearchOperation searchOperation = currentSearchOperation;
458 currentSearchOperation = null;
460 // Before we close the RAF, we have to wind the current search down.
461 if (searchOperation != null) {
462 Log.d(LOG, "Interrupting search to shut down.");
463 currentSearchOperation = null;
464 searchOperation.interrupted.set(true);
468 Log.d(LOG, "Closing RAF.");
470 } catch (IOException e) {
471 Log.e(LOG, "Failed to close dictionary", e);
476 // --------------------------------------------------------------------------
478 // --------------------------------------------------------------------------
480 private void onClearSearchTextButton() {
481 setSearchText("", true);
485 private void showKeyboard() {
486 searchText.postDelayed(new Runnable() {
489 Log.d(LOG, "Trying to show soft keyboard.");
490 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
491 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
495 void updateLangButton() {
496 // final LanguageResources languageResources =
497 // Language.isoCodeToResources.get(index.shortName);
498 // if (languageResources != null && languageResources.flagId != 0) {
499 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
500 // languageResources.flagId, 0);
502 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
503 langButton.setText(index.shortName);
508 private void updateTTSLanuage() {
512 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
513 Log.d(LOG, "Setting TTS locale to: " + locale);
514 final int ttsResult = textToSpeech.setLanguage(locale);
515 if (ttsResult != TextToSpeech.LANG_AVAILABLE || ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
516 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
520 void onLanguageButton() {
521 if (currentSearchOperation != null) {
522 currentSearchOperation.interrupted.set(true);
523 currentSearchOperation = null;
525 changeIndexAndResearch((indexIndex + 1) % dictionary.indices.size());
528 void onLanguageButtonLongClick(final Context context) {
529 final Dialog dialog = new Dialog(context);
530 dialog.setContentView(R.layout.select_dictionary_dialog);
531 dialog.setTitle(R.string.selectDictionary);
533 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
536 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
538 // final LinearLayout.LayoutParams layoutParams = new
539 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
540 // ViewGroup.LayoutParams.WRAP_CONTENT);
541 // layoutParams.width = 0;
542 // layoutParams.weight = 1.0f;
544 final Button button = new Button(listView.getContext());
545 final String name = getString(R.string.dictionaryManager);
546 button.setText(name);
547 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
548 DictionaryManagerActivity.getLaunchIntent()) {
550 protected void onGo() {
552 DictionaryActivity.this.finish();
555 button.setOnClickListener(intentLauncher);
556 // button.setLayoutParams(layoutParams);
557 listView.addHeaderView(button);
558 // listView.setHeaderDividersEnabled(true);
560 listView.setAdapter(new BaseAdapter() {
562 public View getView(int position, View convertView, ViewGroup parent) {
563 final DictionaryInfo dictionaryInfo = getItem(position);
565 final LinearLayout result = new LinearLayout(parent.getContext());
567 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
569 final TextView dash = new TextView(parent.getContext());
571 result.addView(dash);
574 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
575 final Button button = new Button(parent.getContext());
576 button.setText(indexInfo.shortName);
577 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
579 application.getPath(dictionaryInfo.uncompressedFilename),
580 i, searchText.getText().toString())) {
582 protected void onGo() {
584 DictionaryActivity.this.finish();
587 button.setOnClickListener(intentLauncher);
588 result.addView(button);
592 final TextView nameView = new TextView(parent.getContext());
593 final String name = application
594 .getDictionaryName(dictionaryInfo.uncompressedFilename);
595 nameView.setText(name);
596 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
597 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
598 layoutParams.width = 0;
599 layoutParams.weight = 1.0f;
600 nameView.setLayoutParams(layoutParams);
601 result.addView(nameView);
607 public long getItemId(int position) {
612 public DictionaryInfo getItem(int position) {
613 return installedDicts.get(position);
617 public int getCount() {
618 return installedDicts.size();
625 private void changeIndexAndResearch(int newIndex) {
626 Log.d(LOG, "Changing index to: " + newIndex);
627 if (newIndex == -1) {
628 Log.e(LOG, "Invalid index.");
631 indexIndex = newIndex;
632 index = dictionary.indices.get(indexIndex);
633 indexAdapter = new IndexAdapter(index);
634 Log.d(LOG, "changingIndex, newLang=" + index.longName);
635 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
636 setListAdapter(indexAdapter);
638 setSearchText(searchText.getText().toString(), true);
641 void onUpDownButton(final boolean up) {
645 final int firstVisibleRow = getListView().getFirstVisiblePosition();
646 final RowBase row = index.rows.get(firstVisibleRow);
647 final TokenRow tokenRow = row.getTokenRow(true);
648 final int destIndexEntry;
650 if (row != tokenRow) {
651 destIndexEntry = tokenRow.referenceIndex;
653 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
657 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
659 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
660 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
661 setSearchText(dest.token, false);
662 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
666 // --------------------------------------------------------------------------
668 // --------------------------------------------------------------------------
670 final Random random = new Random();
673 public boolean onCreateOptionsMenu(final Menu menu) {
674 application.onCreateGlobalOptionsMenu(this, menu);
677 // final MenuItem randomWord = menu.add(getString(R.string.randomWord));
678 // randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
679 // public boolean onMenuItemClick(final MenuItem menuItem) {
680 // final String word = index.sortedIndexEntries.get(random
681 // .nextInt(index.sortedIndexEntries.size())).token;
682 // setSearchText(word, true);
689 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
690 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
691 public boolean onMenuItemClick(final MenuItem menuItem) {
692 startActivity(DictionaryManagerActivity.getLaunchIntent());
700 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
701 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
702 public boolean onMenuItemClick(final MenuItem menuItem) {
703 final Context context = getListView().getContext();
704 final Dialog dialog = new Dialog(context);
705 dialog.setContentView(R.layout.about_dictionary_dialog);
706 final TextView textView = (TextView) dialog.findViewById(R.id.text);
708 final String name = application.getDictionaryName(dictFile.getName());
709 dialog.setTitle(name);
711 final StringBuilder builder = new StringBuilder();
712 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
713 dictionaryInfo.uncompressedBytes = dictFile.length();
714 if (dictionaryInfo != null) {
715 builder.append(dictionaryInfo.dictInfo).append("\n\n");
716 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
719 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
722 getString(R.string.dictionaryCreationTime,
723 dictionaryInfo.creationMillis)).append("\n");
724 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
725 builder.append("\n");
726 builder.append(getString(R.string.indexName, indexInfo.shortName))
729 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
732 builder.append("\n");
733 builder.append(getString(R.string.sources)).append("\n");
734 for (final EntrySource source : dictionary.sources) {
736 getString(R.string.sourceInfo, source.getName(),
737 source.getNumEntries())).append("\n");
741 // builder.append(getString(R.string.invalidDictionary));
743 textView.setText(builder.toString());
746 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
747 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
748 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
749 dialog.getWindow().setAttributes(layoutParams);
758 // --------------------------------------------------------------------------
759 // Context Menu + clicks
760 // --------------------------------------------------------------------------
763 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
764 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
765 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
767 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
768 wordList.getName()));
769 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
770 public boolean onMenuItemClick(MenuItem item) {
771 onAppendToWordList(row);
776 final MenuItem copy = menu.add(android.R.string.copy);
777 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
778 public boolean onMenuItemClick(MenuItem item) {
784 if (selectedSpannableText != null) {
785 final String selectedText = selectedSpannableText;
786 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
787 selectedSpannableText));
788 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
789 public boolean onMenuItemClick(MenuItem item) {
790 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
796 if (row instanceof TokenRow && ttsReady) {
797 final MenuItem speak = menu.add(R.string.speak);
798 speak.setOnMenuItemClickListener(new OnMenuItemClickListener() {
800 public boolean onMenuItemClick(MenuItem item) {
801 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
802 new HashMap<String, String>());
809 private void jumpToTextFromHyperLink(final String selectedText, final int defaultIndexToUse) {
811 for (int i = 0; i < dictionary.indices.size(); ++i) {
812 final Index index = dictionary.indices.get(i);
813 if (indexPrepFinished) {
814 System.out.println("Doing index lookup: on " + selectedText);
815 final IndexEntry indexEntry = index.findExact(selectedText);
816 if (indexEntry != null) {
817 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
819 if (tokenRow != null && tokenRow.hasMainEntry) {
825 Log.w(LOG, "Skipping findExact on index " + index.shortName);
828 if (indexToUse == -1) {
829 indexToUse = defaultIndexToUse;
831 final boolean changeIndex = indexIndex != indexToUse;
833 setSearchText(selectedText, false);
834 changeIndexAndResearch(indexToUse);
836 setSearchText(selectedText, true);
841 protected void onListItemClick(ListView l, View v, int row, long id) {
843 if (clickOpensContextMenu && dictRaf != null) {
848 void onAppendToWordList(final RowBase row) {
851 final StringBuilder rawText = new StringBuilder();
852 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
853 rawText.append(index.longName).append("\t");
854 rawText.append(row.getTokenRow(true).getToken()).append("\t");
855 rawText.append(row.getRawText(saveOnlyFirstSubentry));
856 Log.d(LOG, "Writing : " + rawText);
859 wordList.getParentFile().mkdirs();
860 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
861 out.println(rawText.toString());
863 } catch (IOException e) {
864 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
866 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
867 Toast.LENGTH_LONG).show();
873 * Called when user clicks outside of search text, so that they can start
874 * typing again immediately.
876 void defocusSearchText() {
877 // Log.d(LOG, "defocusSearchText");
878 // Request focus so that if we start typing again, it clears the text
880 getListView().requestFocus();
882 // Visual indication that a new keystroke will clear the search text.
883 // Doesn't seem to work unless earchText has focus.
884 // searchText.selectAll();
887 @SuppressWarnings("deprecation")
888 void onCopy(final RowBase row) {
891 Log.d(LOG, "Copy, row=" + row);
892 final StringBuilder result = new StringBuilder();
893 result.append(row.getRawText(false));
894 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
895 clipboardManager.setText(result.toString());
896 Log.d(LOG, "Copied: " + result);
900 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
901 if (event.getUnicodeChar() != 0) {
902 if (!searchText.hasFocus()) {
903 setSearchText("" + (char) event.getUnicodeChar(), true);
907 if (keyCode == KeyEvent.KEYCODE_BACK) {
908 // Log.d(LOG, "Clearing dictionary prefs.");
909 // Pretend that we just autolaunched so that we won't do it again.
910 // DictionaryManagerActivity.lastAutoLaunchMillis =
911 // System.currentTimeMillis();
913 if (keyCode == KeyEvent.KEYCODE_ENTER) {
914 Log.d(LOG, "Trying to hide soft keyboard.");
915 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
916 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
917 InputMethodManager.HIDE_NOT_ALWAYS);
920 return super.onKeyDown(keyCode, event);
923 private void setSearchText(final String text, final boolean triggerSearch) {
924 if (!triggerSearch) {
925 getListView().requestFocus();
927 searchText.setText(text);
928 searchText.requestFocus();
931 onSearchTextChange(text);
935 private long cursorDelayMillis = 100;
937 private void moveCursorToRight() {
938 if (searchText.getLayout() != null) {
939 cursorDelayMillis = 100;
940 // Surprising, but this can crash when you rotate...
941 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
943 uiHandler.postDelayed(new Runnable() {
948 }, cursorDelayMillis);
949 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
953 // --------------------------------------------------------------------------
955 // --------------------------------------------------------------------------
957 private void searchFinished(final SearchOperation searchOperation) {
958 if (searchOperation.interrupted.get()) {
959 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
962 if (searchOperation != this.currentSearchOperation) {
963 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
967 final Index.IndexEntry searchResult = searchOperation.searchResult;
968 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
970 currentSearchOperation = null;
971 uiHandler.postDelayed(new Runnable() {
974 if (currentSearchOperation == null) {
975 if (searchResult != null) {
979 jumpToRow(searchResult.startRow);
980 } else if (searchOperation.multiWordSearchResult != null) {
981 // Multi-row search....
982 setFiltered(searchOperation);
984 throw new IllegalStateException("This should never happen.");
987 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
993 private final void jumpToRow(final int row) {
994 final boolean refocusSearchText = searchText.hasFocus();
995 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + refocusSearchText);
996 getListView().requestFocusFromTouch();
997 getListView().setSelectionFromTop(row, 0);
998 getListView().setSelected(true);
999 if (refocusSearchText) {
1000 searchText.requestFocus();
1002 //Log.d(LOG, "getSelectedItemPosition():" + getSelectedItemPosition());
1005 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1007 final class SearchOperation implements Runnable {
1009 final AtomicBoolean interrupted = new AtomicBoolean(false);
1011 final String searchText;
1013 List<String> searchTokens; // filled in for multiWord.
1017 long searchStartMillis;
1019 Index.IndexEntry searchResult;
1021 List<RowBase> multiWordSearchResult;
1023 boolean done = false;
1025 SearchOperation(final String searchText, final Index index) {
1026 this.searchText = StringUtil.normalizeWhitespace(searchText);
1030 public String toString() {
1031 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1037 searchStartMillis = System.currentTimeMillis();
1038 final String[] searchTokenArray = WHITESPACE.split(searchText);
1039 if (searchTokenArray.length == 1) {
1040 searchResult = index.findInsertionPoint(searchText, interrupted);
1042 searchTokens = Arrays.asList(searchTokenArray);
1043 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens, interrupted);
1046 "searchText=" + searchText + ", searchDuration="
1047 + (System.currentTimeMillis() - searchStartMillis)
1048 + ", interrupted=" + interrupted.get());
1049 if (!interrupted.get()) {
1050 uiHandler.post(new Runnable() {
1053 searchFinished(SearchOperation.this);
1057 Log.d(LOG, "interrupted, skipping searchFinished.");
1059 } catch (Exception e) {
1060 Log.e(LOG, "Failure during search (can happen during Activity close.");
1062 synchronized (this) {
1070 // --------------------------------------------------------------------------
1072 // --------------------------------------------------------------------------
1074 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1075 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1077 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1078 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1080 final class IndexAdapter extends BaseAdapter {
1082 private static final float PADDING_DEFAULT_DP = 8;
1084 private static final float PADDING_LARGE_DP = 16;
1088 final List<RowBase> rows;
1090 final Set<String> toHighlight;
1092 private int mPaddingDefault;
1094 private int mPaddingLarge;
1096 IndexAdapter(final Index index) {
1099 this.toHighlight = null;
1103 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1106 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1110 private void getMetrics() {
1111 // Get the screen's density scale
1112 final float scale = getResources().getDisplayMetrics().density;
1113 // Convert the dps to pixels, based on density scale
1114 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1115 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1119 public int getCount() {
1124 public RowBase getItem(int position) {
1125 return rows.get(position);
1129 public long getItemId(int position) {
1130 return getItem(position).index();
1134 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1135 final TableLayout result;
1136 if (convertView instanceof TableLayout) {
1137 result = (TableLayout) convertView;
1138 result.removeAllViews();
1140 result = new TableLayout(parent.getContext());
1142 final RowBase row = getItem(position);
1143 if (row instanceof PairEntry.Row) {
1144 return getView(position, (PairEntry.Row) row, parent, result);
1145 } else if (row instanceof TokenRow) {
1146 return getView((TokenRow) row, parent, result);
1147 } else if (row instanceof HtmlEntry.Row) {
1148 return getView((HtmlEntry.Row) row, parent, result);
1150 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1154 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1155 final TableLayout result) {
1156 final PairEntry entry = row.getEntry();
1157 final int rowCount = entry.pairs.size();
1159 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1160 layoutParams.weight = 0.5f;
1161 layoutParams.leftMargin = mPaddingLarge;
1163 for (int r = 0; r < rowCount; ++r) {
1164 final TableRow tableRow = new TableRow(result.getContext());
1166 final TextView col1 = new TextView(tableRow.getContext());
1167 final TextView col2 = new TextView(tableRow.getContext());
1169 // Set the columns in the table.
1171 final TextView bullet = new TextView(tableRow.getContext());
1172 bullet.setText(" • ");
1173 tableRow.addView(bullet);
1175 tableRow.addView(col1, layoutParams);
1176 final TextView margin = new TextView(tableRow.getContext());
1177 margin.setText(" ");
1178 tableRow.addView(margin);
1180 final TextView bullet = new TextView(tableRow.getContext());
1181 bullet.setText(" • ");
1182 tableRow.addView(bullet);
1184 tableRow.addView(col2, layoutParams);
1188 // Set what's in the columns.
1190 final Pair pair = entry.pairs.get(r);
1191 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1192 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1194 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1195 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1197 // Bold the token instances in col1.
1198 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1199 .singleton(row.getTokenRow(true).getToken());
1200 final Spannable col1Spannable = (Spannable) col1.getText();
1201 for (final String token : toBold) {
1203 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1204 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1205 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1206 startPos += token.length();
1210 createTokenLinkSpans(col1, col1Spannable, col1Text);
1211 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1213 col1.setTypeface(typeface);
1214 col2.setTypeface(typeface);
1215 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1216 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1217 // col2.setBackgroundResource(theme.otherLangBg);
1219 if (index.swapPairEntries) {
1220 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1221 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1223 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1224 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1227 result.addView(tableRow);
1230 // Because we have a Button inside a ListView row:
1231 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1232 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1233 result.setClickable(true);
1234 result.setFocusable(true);
1235 result.setLongClickable(true);
1236 result.setBackgroundResource(android.R.drawable.menuitem_background);
1237 result.setOnClickListener(new TextView.OnClickListener() {
1239 public void onClick(View v) {
1240 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1247 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1248 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1249 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1250 final Context context = parent.getContext();
1252 final TableRow tableRow = new TableRow(result.getContext());
1253 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1254 : theme.tokenRowOtherBg);
1256 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1258 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1260 result.addView(tableRow);
1262 // Make it so we can long-click on these token rows, too:
1263 final TextView textView = new TextView(context);
1264 textView.setText(text, BufferType.SPANNABLE);
1265 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1266 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1268 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1269 result.setLongClickable(true);
1272 // textView.setTextColor(android.R.color.secondary_text_light);
1273 textView.setTypeface(typeface);
1274 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1276 textView.setTextAppearance(context, theme.tokenRowFg);
1277 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1279 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1283 textView.setLayoutParams(lp);
1284 tableRow.addView(textView);
1286 if (!htmlEntries.isEmpty()) {
1287 final ClickableSpan clickableSpan = new ClickableSpan() {
1289 public void onClick(View widget) {
1292 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1293 result.setClickable(true);
1294 textView.setClickable(true);
1295 textView.setMovementMethod(LinkMovementMethod.getInstance());
1296 textView.setOnClickListener(new OnClickListener() {
1298 public void onClick(View v) {
1299 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1300 Log.d(LOG, "html=" + html);
1301 startActivityForResult(
1302 HtmlDisplayActivity.getHtmlIntent(String.format(
1303 "<html><head></head><body>%s</body></html>", html),
1304 htmlTextToHighlight, false),
1312 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1313 final IndexEntry indexEntry = row.getIndexEntry();
1314 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1315 indexEntry.htmlEntries, null, parent, result);
1318 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1319 final HtmlEntry htmlEntry = row.getEntry();
1320 final TokenRow tokenRow = row.getTokenRow(true);
1321 return getPossibleLinkToHtmlEntryView(false,
1322 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1323 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1329 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1331 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1332 final String text) {
1333 // Saw from the source code that LinkMovementMethod sets the selection!
1334 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1335 textView.setMovementMethod(LinkMovementMethod.getInstance());
1336 final Matcher matcher = CHAR_DASH.matcher(text);
1337 while (matcher.find()) {
1338 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
1339 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1343 String selectedSpannableText = null;
1345 int selectedSpannableIndex = -1;
1348 public boolean onTouchEvent(MotionEvent event) {
1349 selectedSpannableText = null;
1350 selectedSpannableIndex = -1;
1351 return super.onTouchEvent(event);
1354 private class TextViewLongClickListener implements OnLongClickListener {
1357 private TextViewLongClickListener(final int index) {
1362 public boolean onLongClick(final View v) {
1363 final TextView textView = (TextView) v;
1364 final int start = textView.getSelectionStart();
1365 final int end = textView.getSelectionEnd();
1366 if (start >= 0 && end >= 0) {
1367 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1368 selectedSpannableIndex = index;
1374 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1377 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1380 // --------------------------------------------------------------------------
1382 // --------------------------------------------------------------------------
1384 void onSearchTextChange(final String text) {
1385 if ("thadolina".equals(text)) {
1386 final Dialog dialog = new Dialog(getListView().getContext());
1387 dialog.setContentView(R.layout.thadolina_dialog);
1388 dialog.setTitle("Ti amo, amore mio!");
1389 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1390 imageView.setOnClickListener(new OnClickListener() {
1392 public void onClick(View v) {
1393 final Intent intent = new Intent(Intent.ACTION_VIEW);
1394 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1395 startActivity(intent);
1400 if (dictRaf == null) {
1401 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1404 if (!searchText.isFocused()) {
1405 Log.d(LOG, "searchText changed without focus, doing nothing.");
1408 Log.d(LOG, "onSearchTextChange: " + text);
1409 if (currentSearchOperation != null) {
1410 Log.d(LOG, "Interrupting currentSearchOperation.");
1411 currentSearchOperation.interrupted.set(true);
1413 currentSearchOperation = new SearchOperation(text, index);
1414 searchExecutor.execute(currentSearchOperation);
1417 private class SearchTextWatcher implements TextWatcher {
1418 public void afterTextChanged(final Editable searchTextEditable) {
1419 if (searchText.hasFocus()) {
1420 Log.d(LOG, "SearchTextWatcher: Search text changed with focus: " + searchText.getText());
1421 // If they were typing to cause the change, update the UI.
1422 onSearchTextChange(searchText.getText().toString());
1426 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1429 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1433 // --------------------------------------------------------------------------
1434 // Filtered results.
1435 // --------------------------------------------------------------------------
1437 boolean isFiltered() {
1438 return rowsToShow != null;
1441 void setFiltered(final SearchOperation searchOperation) {
1442 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(false);
1443 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(false);
1444 rowsToShow = searchOperation.multiWordSearchResult;
1445 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1448 void clearFiltered() {
1449 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(true);
1450 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(true);
1451 setListAdapter(new IndexAdapter(index));