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.Typeface;
23 import android.net.Uri;
24 import android.os.Bundle;
25 import android.os.Handler;
26 import android.preference.PreferenceManager;
27 import android.speech.tts.TextToSpeech;
28 import android.speech.tts.TextToSpeech.OnInitListener;
29 import android.text.ClipboardManager;
30 import android.text.Editable;
31 import android.text.Selection;
32 import android.text.Spannable;
33 import android.text.TextWatcher;
34 import android.text.method.LinkMovementMethod;
35 import android.text.style.StyleSpan;
36 import android.util.Log;
37 import android.util.TypedValue;
38 import android.view.ContextMenu;
39 import android.view.ContextMenu.ContextMenuInfo;
40 import android.view.KeyEvent;
41 import android.view.Menu;
42 import android.view.MenuItem;
43 import android.view.MenuItem.OnMenuItemClickListener;
44 import android.view.MotionEvent;
45 import android.view.View;
46 import android.view.View.OnClickListener;
47 import android.view.View.OnFocusChangeListener;
48 import android.view.View.OnLongClickListener;
49 import android.view.ViewGroup;
50 import android.view.WindowManager;
51 import android.view.inputmethod.InputMethodManager;
52 import android.widget.AdapterView;
53 import android.widget.AdapterView.AdapterContextMenuInfo;
54 import android.widget.BaseAdapter;
55 import android.widget.Button;
56 import android.widget.EditText;
57 import android.widget.ImageButton;
58 import android.widget.ImageView;
59 import android.widget.LinearLayout;
60 import android.widget.ListAdapter;
61 import android.widget.ListView;
62 import android.widget.TableLayout;
63 import android.widget.TableRow;
64 import android.widget.TextView;
65 import android.widget.TextView.BufferType;
66 import android.widget.Toast;
68 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
69 import com.hughes.android.dictionary.engine.Dictionary;
70 import com.hughes.android.dictionary.engine.EntrySource;
71 import com.hughes.android.dictionary.engine.HtmlEntry;
72 import com.hughes.android.dictionary.engine.Index;
73 import com.hughes.android.dictionary.engine.Index.IndexEntry;
74 import com.hughes.android.dictionary.engine.PairEntry;
75 import com.hughes.android.dictionary.engine.PairEntry.Pair;
76 import com.hughes.android.dictionary.engine.RowBase;
77 import com.hughes.android.dictionary.engine.TokenRow;
78 import com.hughes.android.dictionary.engine.TransliteratorManager;
79 import com.hughes.android.util.IntentLauncher;
80 import com.hughes.android.util.NonLinkClickableSpan;
83 import java.io.FileWriter;
84 import java.io.IOException;
85 import java.io.PrintWriter;
86 import java.io.RandomAccessFile;
87 import java.text.SimpleDateFormat;
88 import java.util.Arrays;
89 import java.util.Collections;
90 import java.util.Date;
91 import java.util.HashMap;
92 import java.util.LinkedHashSet;
93 import java.util.List;
94 import java.util.Locale;
95 import java.util.Random;
97 import java.util.concurrent.Executor;
98 import java.util.concurrent.Executors;
99 import java.util.concurrent.ThreadFactory;
100 import java.util.concurrent.atomic.AtomicBoolean;
101 import java.util.regex.Matcher;
102 import java.util.regex.Pattern;
104 public class DictionaryActivity extends ListActivity {
106 static final String LOG = "QuickDic";
108 DictionaryApplication application;
110 File dictFile = null;
112 RandomAccessFile dictRaf = null;
114 Dictionary dictionary = null;
120 List<RowBase> rowsToShow = null; // if not null, just show these rows.
123 final Handler uiHandler = new Handler();
125 TextToSpeech textToSpeech;
126 volatile boolean ttsReady;
128 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
130 public Thread newThread(Runnable r) {
131 return new Thread(r, "searchExecutor");
135 private SearchOperation currentSearchOperation = null;
137 C.Theme theme = C.Theme.LIGHT;
148 private File wordList = null;
150 private boolean saveOnlyFirstSubentry = false;
152 private boolean clickOpensContextMenu = false;
154 // Visible for testing.
155 ListAdapter indexAdapter = null;
157 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
160 * For some languages, loading the transliterators used in this search takes
161 * a long time, so we fire it up on a different thread, and don't invoke it
162 * from the main thread until it's already finished once.
164 private volatile boolean indexPrepFinished = false;
166 public DictionaryActivity() {
169 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
170 final String searchToken) {
171 final Intent intent = new Intent();
172 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
173 DictionaryActivity.class.getName());
174 intent.putExtra(C.DICT_FILE, dictFile.getPath());
175 intent.putExtra(C.INDEX_INDEX, indexIndex);
176 intent.putExtra(C.SEARCH_TOKEN, searchToken);
181 protected void onSaveInstanceState(final Bundle outState) {
182 super.onSaveInstanceState(outState);
183 Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
184 outState.putInt(C.INDEX_INDEX, indexIndex);
185 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
189 protected void onRestoreInstanceState(final Bundle outState) {
190 super.onRestoreInstanceState(outState);
191 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
196 public void onCreate(Bundle savedInstanceState) {
197 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
198 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
201 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
203 Log.d(LOG, "onCreate:" + this);
204 super.onCreate(savedInstanceState);
206 application = (DictionaryApplication) getApplication();
207 theme = application.getSelectedTheme();
209 final Intent intent = getIntent();
210 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
213 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
215 public void onInit(int status) {
222 final String name = application.getDictionaryName(dictFile.getName());
223 this.setTitle("QuickDic: " + name);
224 dictRaf = new RandomAccessFile(dictFile, "r");
225 dictionary = new Dictionary(dictRaf);
226 } catch (Exception e) {
227 Log.e(LOG, "Unable to load dictionary.", e);
228 if (dictRaf != null) {
231 } catch (IOException e1) {
232 Log.e(LOG, "Unable to close dictRaf.", e1);
236 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
237 Toast.LENGTH_LONG).show();
238 startActivity(DictionaryManagerActivity.getLaunchIntent());
242 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
243 if (savedInstanceState != null) {
244 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
246 indexIndex %= dictionary.indices.size();
247 Log.d(LOG, "Loading index " + indexIndex);
248 index = dictionary.indices.get(indexIndex);
249 setListAdapter(new IndexAdapter(index));
251 // Pre-load the collators.
252 new Thread(new Runnable() {
254 final long startMillis = System.currentTimeMillis();
256 TransliteratorManager.init(new TransliteratorManager.Callback() {
258 public void onTransliteratorReady() {
259 uiHandler.post(new Runnable() {
262 onSearchTextChange(searchText.getText().toString());
268 for (final Index index : dictionary.indices) {
269 final String searchToken = index.sortedIndexEntries.get(0).token;
270 final IndexEntry entry = index.findExact(searchToken);
271 if (!searchToken.equals(entry.token)) {
272 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
275 indexPrepFinished = true;
276 } catch (Exception e) {
278 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
280 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
284 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
285 if ("SYSTEM".equals(fontName)) {
286 typeface = Typeface.DEFAULT;
289 typeface = Typeface.createFromAsset(getAssets(), fontName);
290 } catch (Exception e) {
291 Log.w(LOG, "Exception trying to use typeface, using default.", e);
292 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
293 Toast.LENGTH_LONG).show();
296 // if (!"SYSTEM".equals(fontName)) {
297 // throw new RuntimeException("Test force using system font: " +
300 if (typeface == null) {
301 Log.w(LOG, "Unable to create typeface, using default.");
302 typeface = Typeface.DEFAULT;
304 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
306 fontSizeSp = Integer.parseInt(fontSize.trim());
307 } catch (NumberFormatException e) {
311 setContentView(R.layout.dictionary_activity);
312 searchText = (EditText) findViewById(R.id.SearchText);
313 searchText.requestFocus();
314 searchText.addTextChangedListener(searchTextWatcher);
315 searchText.setOnFocusChangeListener(new OnFocusChangeListener() {
317 public void onFocusChange(View v, boolean hasFocus) {
318 Log.d(LOG, "searchText onFocusChange hasFocus=" + hasFocus);
322 // Set the search text from the intent, then the saved state.
323 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
324 if (savedInstanceState != null) {
325 text = savedInstanceState.getString(C.SEARCH_TOKEN);
330 setSearchText(text, true);
331 Log.d(LOG, "Trying to restore searchText=" + text);
333 final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
334 clearSearchTextButton.setOnClickListener(new OnClickListener() {
335 public void onClick(View v) {
336 onClearSearchTextButton();
339 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
340 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
343 langButton = (Button) findViewById(R.id.LangButton);
344 langButton.setOnClickListener(new OnClickListener() {
345 public void onClick(View v) {
349 langButton.setOnLongClickListener(new OnLongClickListener() {
351 public boolean onLongClick(View v) {
352 onLanguageButtonLongClick(v.getContext());
358 final View upButton = findViewById(R.id.UpButton);
359 upButton.setOnClickListener(new OnClickListener() {
360 public void onClick(View v) {
361 onUpDownButton(true);
364 final View downButton = findViewById(R.id.DownButton);
365 downButton.setOnClickListener(new OnClickListener() {
366 public void onClick(View v) {
367 onUpDownButton(false);
371 // getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
373 // public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
375 // if (!searchText.isFocused()) {
376 // if (!isFiltered()) {
377 // final RowBase row = (RowBase) getListAdapter().getItem(position);
378 // Log.d(LOG, "onItemSelected: " + row.index());
379 // final TokenRow tokenRow = row.getTokenRow(true);
380 // searchText.setText(tokenRow.getToken());
386 // public void onNothingSelected(AdapterView<?> arg0) {
391 registerForContextMenu(getListView());
394 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
395 getString(R.string.wordListFileDefault)));
396 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
398 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
400 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
402 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
404 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
406 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
410 protected void onResume() {
411 Log.d(LOG, "onResume");
413 if (PreferenceActivity.prefsMightHaveChanged) {
414 PreferenceActivity.prefsMightHaveChanged = false;
416 startActivity(getIntent());
422 protected void onPause() {
427 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
428 super.onActivityResult(requestCode, resultCode, result);
429 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
430 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
431 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
435 private static void setDictionaryPrefs(final Context context, final File dictFile,
436 final int indexIndex, final String searchToken) {
437 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
439 prefs.putString(C.DICT_FILE, dictFile.getPath());
440 prefs.putInt(C.INDEX_INDEX, indexIndex);
441 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
446 protected void onDestroy() {
448 if (dictRaf == null) {
452 final SearchOperation searchOperation = currentSearchOperation;
453 currentSearchOperation = null;
455 // Before we close the RAF, we have to wind the current search down.
456 if (searchOperation != null) {
457 Log.d(LOG, "Interrupting search to shut down.");
458 currentSearchOperation = null;
459 searchOperation.interrupted.set(true);
463 Log.d(LOG, "Closing RAF.");
465 } catch (IOException e) {
466 Log.e(LOG, "Failed to close dictionary", e);
471 // --------------------------------------------------------------------------
473 // --------------------------------------------------------------------------
475 private void onClearSearchTextButton() {
476 setSearchText("", true);
480 private void showKeyboard() {
481 searchText.postDelayed(new Runnable() {
484 Log.d(LOG, "Trying to show soft keyboard.");
485 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
486 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
490 void updateLangButton() {
491 // final LanguageResources languageResources =
492 // Language.isoCodeToResources.get(index.shortName);
493 // if (languageResources != null && languageResources.flagId != 0) {
494 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
495 // languageResources.flagId, 0);
497 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
498 langButton.setText(index.shortName);
503 private void updateTTSLanuage() {
507 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
508 Log.d(LOG, "Setting TTS locale to: " + locale);
509 final int ttsResult = textToSpeech.setLanguage(locale);
510 if (ttsResult != TextToSpeech.LANG_AVAILABLE || ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
511 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
515 void onLanguageButton() {
516 if (currentSearchOperation != null) {
517 currentSearchOperation.interrupted.set(true);
518 currentSearchOperation = null;
520 changeIndexAndResearch((indexIndex + 1) % dictionary.indices.size());
523 void onLanguageButtonLongClick(final Context context) {
524 final Dialog dialog = new Dialog(context);
525 dialog.setContentView(R.layout.select_dictionary_dialog);
526 dialog.setTitle(R.string.selectDictionary);
528 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
531 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
533 // final LinearLayout.LayoutParams layoutParams = new
534 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
535 // ViewGroup.LayoutParams.WRAP_CONTENT);
536 // layoutParams.width = 0;
537 // layoutParams.weight = 1.0f;
539 final Button button = new Button(listView.getContext());
540 final String name = getString(R.string.dictionaryManager);
541 button.setText(name);
542 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
543 DictionaryManagerActivity.getLaunchIntent()) {
545 protected void onGo() {
547 DictionaryActivity.this.finish();
550 button.setOnClickListener(intentLauncher);
551 // button.setLayoutParams(layoutParams);
552 listView.addHeaderView(button);
553 // listView.setHeaderDividersEnabled(true);
555 listView.setAdapter(new BaseAdapter() {
557 public View getView(int position, View convertView, ViewGroup parent) {
558 final DictionaryInfo dictionaryInfo = getItem(position);
560 final LinearLayout result = new LinearLayout(parent.getContext());
562 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
564 final TextView dash = new TextView(parent.getContext());
566 result.addView(dash);
569 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
570 final Button button = new Button(parent.getContext());
571 button.setText(indexInfo.shortName);
572 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
574 application.getPath(dictionaryInfo.uncompressedFilename),
575 i, searchText.getText().toString())) {
577 protected void onGo() {
579 DictionaryActivity.this.finish();
582 button.setOnClickListener(intentLauncher);
583 result.addView(button);
587 final TextView nameView = new TextView(parent.getContext());
588 final String name = application
589 .getDictionaryName(dictionaryInfo.uncompressedFilename);
590 nameView.setText(name);
591 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
592 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
593 layoutParams.width = 0;
594 layoutParams.weight = 1.0f;
595 nameView.setLayoutParams(layoutParams);
596 result.addView(nameView);
602 public long getItemId(int position) {
607 public DictionaryInfo getItem(int position) {
608 return installedDicts.get(position);
612 public int getCount() {
613 return installedDicts.size();
620 private void changeIndexAndResearch(int newIndex) {
621 Log.d(LOG, "Changing index to: " + newIndex);
622 if (newIndex == -1) {
623 Log.e(LOG, "Invalid index.");
626 indexIndex = newIndex;
627 index = dictionary.indices.get(indexIndex);
628 indexAdapter = new IndexAdapter(index);
629 Log.d(LOG, "changingIndex, newLang=" + index.longName);
630 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
631 setListAdapter(indexAdapter);
633 setSearchText(searchText.getText().toString(), true);
636 void onUpDownButton(final boolean up) {
640 final int firstVisibleRow = getListView().getFirstVisiblePosition();
641 final RowBase row = index.rows.get(firstVisibleRow);
642 final TokenRow tokenRow = row.getTokenRow(true);
643 final int destIndexEntry;
645 if (row != tokenRow) {
646 destIndexEntry = tokenRow.referenceIndex;
648 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
652 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
654 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
655 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
656 setSearchText(dest.token, false);
657 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
661 // --------------------------------------------------------------------------
663 // --------------------------------------------------------------------------
665 final Random random = new Random();
668 public boolean onCreateOptionsMenu(final Menu menu) {
669 application.onCreateGlobalOptionsMenu(this, menu);
672 // final MenuItem randomWord = menu.add(getString(R.string.randomWord));
673 // randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
674 // public boolean onMenuItemClick(final MenuItem menuItem) {
675 // final String word = index.sortedIndexEntries.get(random
676 // .nextInt(index.sortedIndexEntries.size())).token;
677 // setSearchText(word, true);
684 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
685 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
686 public boolean onMenuItemClick(final MenuItem menuItem) {
687 startActivity(DictionaryManagerActivity.getLaunchIntent());
695 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
696 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
697 public boolean onMenuItemClick(final MenuItem menuItem) {
698 final Context context = getListView().getContext();
699 final Dialog dialog = new Dialog(context);
700 dialog.setContentView(R.layout.about_dictionary_dialog);
701 final TextView textView = (TextView) dialog.findViewById(R.id.text);
703 final String name = application.getDictionaryName(dictFile.getName());
704 dialog.setTitle(name);
706 final StringBuilder builder = new StringBuilder();
707 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
708 dictionaryInfo.uncompressedBytes = dictFile.length();
709 if (dictionaryInfo != null) {
710 builder.append(dictionaryInfo.dictInfo).append("\n\n");
711 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
714 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
717 getString(R.string.dictionaryCreationTime,
718 dictionaryInfo.creationMillis)).append("\n");
719 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
720 builder.append("\n");
721 builder.append(getString(R.string.indexName, indexInfo.shortName))
724 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
727 builder.append("\n");
728 builder.append(getString(R.string.sources)).append("\n");
729 for (final EntrySource source : dictionary.sources) {
731 getString(R.string.sourceInfo, source.getName(),
732 source.getNumEntries())).append("\n");
736 // builder.append(getString(R.string.invalidDictionary));
738 textView.setText(builder.toString());
741 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
742 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
743 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
744 dialog.getWindow().setAttributes(layoutParams);
753 // --------------------------------------------------------------------------
754 // Context Menu + clicks
755 // --------------------------------------------------------------------------
758 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
759 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
760 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
762 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
763 wordList.getName()));
764 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
765 public boolean onMenuItemClick(MenuItem item) {
766 onAppendToWordList(row);
771 final MenuItem copy = menu.add(android.R.string.copy);
772 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
773 public boolean onMenuItemClick(MenuItem item) {
779 if (selectedSpannableText != null) {
780 final String selectedText = selectedSpannableText;
781 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
782 selectedSpannableText));
783 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
784 public boolean onMenuItemClick(MenuItem item) {
785 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
791 if (row instanceof TokenRow && ttsReady) {
792 final MenuItem speak = menu.add(R.string.speak);
793 speak.setOnMenuItemClickListener(new OnMenuItemClickListener() {
795 public boolean onMenuItemClick(MenuItem item) {
796 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
797 new HashMap<String, String>());
804 private void jumpToTextFromHyperLink(final String selectedText, final int defaultIndexToUse) {
806 for (int i = 0; i < dictionary.indices.size(); ++i) {
807 final Index index = dictionary.indices.get(i);
808 if (indexPrepFinished) {
809 System.out.println("Doing index lookup: on " + selectedText);
810 final IndexEntry indexEntry = index.findExact(selectedText);
811 if (indexEntry != null) {
812 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
814 if (tokenRow != null && tokenRow.hasMainEntry) {
820 Log.w(LOG, "Skipping findExact on index " + index.shortName);
823 if (indexToUse == -1) {
824 indexToUse = defaultIndexToUse;
826 final boolean changeIndex = indexIndex != indexToUse;
828 setSearchText(selectedText, false);
829 changeIndexAndResearch(indexToUse);
831 setSearchText(selectedText, true);
836 protected void onListItemClick(ListView l, View v, int row, long id) {
838 if (clickOpensContextMenu && dictRaf != null) {
843 void onAppendToWordList(final RowBase row) {
846 final StringBuilder rawText = new StringBuilder();
847 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
848 rawText.append(index.longName).append("\t");
849 rawText.append(row.getTokenRow(true).getToken()).append("\t");
850 rawText.append(row.getRawText(saveOnlyFirstSubentry));
851 Log.d(LOG, "Writing : " + rawText);
854 wordList.getParentFile().mkdirs();
855 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
856 out.println(rawText.toString());
858 } catch (IOException e) {
859 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
861 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
862 Toast.LENGTH_LONG).show();
868 * Called when user clicks outside of search text, so that they can start
869 * typing again immediately.
871 void defocusSearchText() {
872 // Log.d(LOG, "defocusSearchText");
873 // Request focus so that if we start typing again, it clears the text
875 getListView().requestFocus();
877 // Visual indication that a new keystroke will clear the search text.
878 // Doesn't seem to work unless earchText has focus.
879 // searchText.selectAll();
882 @SuppressWarnings("deprecation")
883 void onCopy(final RowBase row) {
886 Log.d(LOG, "Copy, row=" + row);
887 final StringBuilder result = new StringBuilder();
888 result.append(row.getRawText(false));
889 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
890 clipboardManager.setText(result.toString());
891 Log.d(LOG, "Copied: " + result);
895 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
896 if (event.getUnicodeChar() != 0) {
897 if (!searchText.hasFocus()) {
898 setSearchText("" + (char) event.getUnicodeChar(), true);
902 if (keyCode == KeyEvent.KEYCODE_BACK) {
903 // Log.d(LOG, "Clearing dictionary prefs.");
904 // Pretend that we just autolaunched so that we won't do it again.
905 // DictionaryManagerActivity.lastAutoLaunchMillis =
906 // System.currentTimeMillis();
908 if (keyCode == KeyEvent.KEYCODE_ENTER) {
909 Log.d(LOG, "Trying to hide soft keyboard.");
910 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
911 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
912 InputMethodManager.HIDE_NOT_ALWAYS);
915 return super.onKeyDown(keyCode, event);
918 private void setSearchText(final String text, final boolean triggerSearch) {
919 if (!triggerSearch) {
920 getListView().requestFocus();
922 searchText.setText(text);
923 searchText.requestFocus();
926 onSearchTextChange(text);
930 private long cursorDelayMillis = 100;
932 private void moveCursorToRight() {
933 if (searchText.getLayout() != null) {
934 cursorDelayMillis = 100;
935 // Surprising, but this can crash when you rotate...
936 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
938 uiHandler.postDelayed(new Runnable() {
943 }, cursorDelayMillis);
944 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
948 // --------------------------------------------------------------------------
950 // --------------------------------------------------------------------------
952 private void searchFinished(final SearchOperation searchOperation) {
953 if (searchOperation.interrupted.get()) {
954 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
957 if (searchOperation != this.currentSearchOperation) {
958 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
962 final Index.IndexEntry searchResult = searchOperation.searchResult;
963 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
965 currentSearchOperation = null;
966 uiHandler.postDelayed(new Runnable() {
969 if (currentSearchOperation == null) {
970 if (searchResult != null) {
974 jumpToRow(searchResult.startRow);
975 } else if (searchOperation.multiWordSearchResult != null) {
976 // Multi-row search....
977 setFiltered(searchOperation);
979 throw new IllegalStateException("This should never happen.");
982 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
988 private final void jumpToRow(final int row) {
989 final boolean refocusSearchText = searchText.hasFocus();
990 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + refocusSearchText);
991 getListView().requestFocusFromTouch();
992 getListView().setSelectionFromTop(row, 0);
993 getListView().setSelected(true);
994 if (refocusSearchText) {
995 searchText.requestFocus();
997 //Log.d(LOG, "getSelectedItemPosition():" + getSelectedItemPosition());
1000 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1002 final class SearchOperation implements Runnable {
1004 final AtomicBoolean interrupted = new AtomicBoolean(false);
1006 final String searchText;
1008 List<String> searchTokens; // filled in for multiWord.
1012 long searchStartMillis;
1014 Index.IndexEntry searchResult;
1016 List<RowBase> multiWordSearchResult;
1018 boolean done = false;
1020 SearchOperation(final String searchText, final Index index) {
1021 this.searchText = searchText.trim();
1025 public String toString() {
1026 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1032 searchStartMillis = System.currentTimeMillis();
1033 final String[] searchTokenArray = WHITESPACE.split(searchText);
1034 if (searchTokenArray.length == 1) {
1035 searchResult = index.findInsertionPoint(searchText, interrupted);
1037 searchTokens = Arrays.asList(searchTokenArray);
1038 multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
1041 "searchText=" + searchText + ", searchDuration="
1042 + (System.currentTimeMillis() - searchStartMillis)
1043 + ", interrupted=" + interrupted.get());
1044 if (!interrupted.get()) {
1045 uiHandler.post(new Runnable() {
1048 searchFinished(SearchOperation.this);
1052 Log.d(LOG, "interrupted, skipping searchFinished.");
1054 } catch (Exception e) {
1055 Log.e(LOG, "Failure during search (can happen during Activity close.");
1057 synchronized (this) {
1065 // --------------------------------------------------------------------------
1067 // --------------------------------------------------------------------------
1069 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1070 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1072 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1073 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1075 final class IndexAdapter extends BaseAdapter {
1077 private static final float PADDING_DEFAULT_DP = 8;
1079 private static final float PADDING_LARGE_DP = 16;
1083 final List<RowBase> rows;
1085 final Set<String> toHighlight;
1087 private int mPaddingDefault;
1089 private int mPaddingLarge;
1091 IndexAdapter(final Index index) {
1094 this.toHighlight = null;
1098 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1101 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1105 private void getMetrics() {
1106 // Get the screen's density scale
1107 final float scale = getResources().getDisplayMetrics().density;
1108 // Convert the dps to pixels, based on density scale
1109 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1110 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1114 public int getCount() {
1119 public RowBase getItem(int position) {
1120 return rows.get(position);
1124 public long getItemId(int position) {
1125 return getItem(position).index();
1129 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1130 final TableLayout result;
1131 if (convertView instanceof TableLayout) {
1132 result = (TableLayout) convertView;
1133 result.removeAllViews();
1135 result = new TableLayout(parent.getContext());
1137 final RowBase row = getItem(position);
1138 if (row instanceof PairEntry.Row) {
1139 return getView(position, (PairEntry.Row) row, parent, result);
1140 } else if (row instanceof TokenRow) {
1141 return getView((TokenRow) row, parent, result);
1142 } else if (row instanceof HtmlEntry.Row) {
1143 return getView((HtmlEntry.Row) row, parent, result);
1145 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1149 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1150 final TableLayout result) {
1151 final PairEntry entry = row.getEntry();
1152 final int rowCount = entry.pairs.size();
1154 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1155 layoutParams.weight = 0.5f;
1156 layoutParams.leftMargin = mPaddingLarge;
1158 for (int r = 0; r < rowCount; ++r) {
1159 final TableRow tableRow = new TableRow(result.getContext());
1161 final TextView col1 = new TextView(tableRow.getContext());
1162 final TextView col2 = new TextView(tableRow.getContext());
1164 // Set the columns in the table.
1166 final TextView bullet = new TextView(tableRow.getContext());
1167 bullet.setText(" • ");
1168 tableRow.addView(bullet);
1170 tableRow.addView(col1, layoutParams);
1171 final TextView margin = new TextView(tableRow.getContext());
1172 margin.setText(" ");
1173 tableRow.addView(margin);
1175 final TextView bullet = new TextView(tableRow.getContext());
1176 bullet.setText(" • ");
1177 tableRow.addView(bullet);
1179 tableRow.addView(col2, layoutParams);
1183 // Set what's in the columns.
1185 final Pair pair = entry.pairs.get(r);
1186 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1187 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1189 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1190 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1192 // Bold the token instances in col1.
1193 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1194 .singleton(row.getTokenRow(true).getToken());
1195 final Spannable col1Spannable = (Spannable) col1.getText();
1196 for (final String token : toBold) {
1198 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1199 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1200 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1201 startPos += token.length();
1205 createTokenLinkSpans(col1, col1Spannable, col1Text);
1206 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1208 col1.setTypeface(typeface);
1209 col2.setTypeface(typeface);
1210 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1211 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1212 // col2.setBackgroundResource(theme.otherLangBg);
1214 if (index.swapPairEntries) {
1215 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1216 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1218 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1219 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1222 result.addView(tableRow);
1225 // Because we have a Button inside a ListView row:
1226 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1227 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1228 result.setClickable(true);
1229 result.setFocusable(true);
1230 result.setLongClickable(true);
1231 result.setBackgroundResource(android.R.drawable.menuitem_background);
1232 result.setOnClickListener(new TextView.OnClickListener() {
1234 public void onClick(View v) {
1235 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1242 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1243 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1244 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1245 final Context context = parent.getContext();
1247 final TableRow tableRow = new TableRow(result.getContext());
1248 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1249 : theme.tokenRowOtherBg);
1251 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1253 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1255 result.addView(tableRow);
1257 // Make it so we can long-click on these token rows, too:
1258 final TextView textView = new TextView(context);
1259 textView.setText(text, BufferType.SPANNABLE);
1260 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1261 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1263 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1266 // textView.setTextColor(android.R.color.secondary_text_light);
1267 textView.setTypeface(typeface);
1268 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1270 textView.setTextAppearance(context, theme.tokenRowFg);
1271 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1273 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1277 textView.setLayoutParams(lp);
1278 tableRow.addView(textView);
1280 if (!htmlEntries.isEmpty()) {
1281 final ImageButton button = new ImageButton(context);
1282 button.setImageResource(R.drawable.ic_menu_forward);
1283 button.setOnClickListener(new OnClickListener() {
1285 public void onClick(View v) {
1286 final String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1287 startActivityForResult(
1288 HtmlDisplayActivity.getHtmlIntent(String.format(
1289 "<html><head></head><body>%s</body></html>", html),
1290 htmlTextToHighlight, false),
1294 tableRow.addView(button);
1295 lp = new TableRow.LayoutParams(1);
1297 button.setLayoutParams(lp);
1298 // result.setColumnStretchable(0, true);
1299 // result.setColumnStretchable(1, false);
1301 result.setLongClickable(true);
1305 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1306 final IndexEntry indexEntry = row.getIndexEntry();
1307 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1308 indexEntry.htmlEntries, null, parent, result);
1311 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1312 final HtmlEntry htmlEntry = row.getEntry();
1313 final TokenRow tokenRow = row.getTokenRow(true);
1314 return getPossibleLinkToHtmlEntryView(false,
1315 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1316 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1322 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1324 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1325 final String text) {
1326 // Saw from the source code that LinkMovementMethod sets the selection!
1327 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1328 textView.setMovementMethod(LinkMovementMethod.getInstance());
1329 final Matcher matcher = CHAR_DASH.matcher(text);
1330 while (matcher.find()) {
1331 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(),
1332 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1336 String selectedSpannableText = null;
1338 int selectedSpannableIndex = -1;
1341 public boolean onTouchEvent(MotionEvent event) {
1342 selectedSpannableText = null;
1343 selectedSpannableIndex = -1;
1344 return super.onTouchEvent(event);
1347 private class TextViewLongClickListener implements OnLongClickListener {
1350 private TextViewLongClickListener(final int index) {
1355 public boolean onLongClick(final View v) {
1356 final TextView textView = (TextView) v;
1357 final int start = textView.getSelectionStart();
1358 final int end = textView.getSelectionEnd();
1359 if (start >= 0 && end >= 0) {
1360 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1361 selectedSpannableIndex = index;
1367 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1370 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1373 // --------------------------------------------------------------------------
1375 // --------------------------------------------------------------------------
1377 void onSearchTextChange(final String text) {
1378 if ("thadolina".equals(text)) {
1379 final Dialog dialog = new Dialog(getListView().getContext());
1380 dialog.setContentView(R.layout.thadolina_dialog);
1381 dialog.setTitle("Ti amo, amore mio!");
1382 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1383 imageView.setOnClickListener(new OnClickListener() {
1385 public void onClick(View v) {
1386 final Intent intent = new Intent(Intent.ACTION_VIEW);
1387 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1388 startActivity(intent);
1393 if (dictRaf == null) {
1394 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1397 if (!searchText.isFocused()) {
1398 Log.d(LOG, "searchText changed without focus, doing nothing.");
1401 Log.d(LOG, "onSearchTextChange: " + text);
1402 if (currentSearchOperation != null) {
1403 Log.d(LOG, "Interrupting currentSearchOperation.");
1404 currentSearchOperation.interrupted.set(true);
1406 currentSearchOperation = new SearchOperation(text, index);
1407 searchExecutor.execute(currentSearchOperation);
1410 private class SearchTextWatcher implements TextWatcher {
1411 public void afterTextChanged(final Editable searchTextEditable) {
1412 if (searchText.hasFocus()) {
1413 Log.d(LOG, "SearchTextWatcher: Search text changed with focus: " + searchText.getText());
1414 // If they were typing to cause the change, update the UI.
1415 onSearchTextChange(searchText.getText().toString());
1419 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1422 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1426 // --------------------------------------------------------------------------
1427 // Filtered results.
1428 // --------------------------------------------------------------------------
1430 boolean isFiltered() {
1431 return rowsToShow != null;
1434 void setFiltered(final SearchOperation searchOperation) {
1435 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(false);
1436 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(false);
1437 rowsToShow = searchOperation.multiWordSearchResult;
1438 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1441 void clearFiltered() {
1442 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(true);
1443 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(true);
1444 setListAdapter(new IndexAdapter(index));