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.ClickableSpan;
36 import android.text.style.StyleSpan;
37 import android.util.Log;
38 import android.util.TypedValue;
39 import android.view.ContextMenu;
40 import android.view.ContextMenu.ContextMenuInfo;
41 import android.view.KeyEvent;
42 import android.view.Menu;
43 import android.view.MenuItem;
44 import android.view.MenuItem.OnMenuItemClickListener;
45 import android.view.MotionEvent;
46 import android.view.View;
47 import android.view.View.OnClickListener;
48 import android.view.View.OnFocusChangeListener;
49 import android.view.View.OnLongClickListener;
50 import android.view.ViewGroup;
51 import android.view.WindowManager;
52 import android.view.inputmethod.InputMethodManager;
53 import android.widget.AdapterView;
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;
84 import java.io.FileWriter;
85 import java.io.IOException;
86 import java.io.PrintWriter;
87 import java.io.RandomAccessFile;
88 import java.text.SimpleDateFormat;
89 import java.util.Arrays;
90 import java.util.Collections;
91 import java.util.Date;
92 import java.util.HashMap;
93 import java.util.LinkedHashSet;
94 import java.util.List;
95 import java.util.Locale;
96 import java.util.Random;
98 import java.util.concurrent.Executor;
99 import java.util.concurrent.Executors;
100 import java.util.concurrent.ThreadFactory;
101 import java.util.concurrent.atomic.AtomicBoolean;
102 import java.util.regex.Matcher;
103 import java.util.regex.Pattern;
105 public class DictionaryActivity extends ListActivity {
107 static final String LOG = "QuickDic";
109 DictionaryApplication application;
111 File dictFile = null;
113 RandomAccessFile dictRaf = null;
115 Dictionary dictionary = null;
121 List<RowBase> rowsToShow = null; // if not null, just show these rows.
124 final Handler uiHandler = new Handler();
126 TextToSpeech textToSpeech;
127 volatile boolean ttsReady;
129 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
131 public Thread newThread(Runnable r) {
132 return new Thread(r, "searchExecutor");
136 private SearchOperation currentSearchOperation = null;
138 C.Theme theme = C.Theme.LIGHT;
149 private File wordList = null;
151 private boolean saveOnlyFirstSubentry = false;
153 private boolean clickOpensContextMenu = false;
155 // Visible for testing.
156 ListAdapter indexAdapter = null;
158 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
161 * For some languages, loading the transliterators used in this search takes
162 * a long time, so we fire it up on a different thread, and don't invoke it
163 * from the main thread until it's already finished once.
165 private volatile boolean indexPrepFinished = false;
167 public DictionaryActivity() {
170 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
171 final String searchToken) {
172 final Intent intent = new Intent();
173 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
174 DictionaryActivity.class.getName());
175 intent.putExtra(C.DICT_FILE, dictFile.getPath());
176 intent.putExtra(C.INDEX_INDEX, indexIndex);
177 intent.putExtra(C.SEARCH_TOKEN, searchToken);
182 protected void onSaveInstanceState(final Bundle outState) {
183 super.onSaveInstanceState(outState);
184 Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
185 outState.putInt(C.INDEX_INDEX, indexIndex);
186 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
190 protected void onRestoreInstanceState(final Bundle outState) {
191 super.onRestoreInstanceState(outState);
192 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
197 public void onCreate(Bundle savedInstanceState) {
198 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
199 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
202 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
204 Log.d(LOG, "onCreate:" + this);
205 super.onCreate(savedInstanceState);
207 application = (DictionaryApplication) getApplication();
208 theme = application.getSelectedTheme();
210 final Intent intent = getIntent();
211 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
214 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
216 public void onInit(int status) {
223 final String name = application.getDictionaryName(dictFile.getName());
224 this.setTitle("QuickDic: " + name);
225 dictRaf = new RandomAccessFile(dictFile, "r");
226 dictionary = new Dictionary(dictRaf);
227 } catch (Exception e) {
228 Log.e(LOG, "Unable to load dictionary.", e);
229 if (dictRaf != null) {
232 } catch (IOException e1) {
233 Log.e(LOG, "Unable to close dictRaf.", e1);
237 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
238 Toast.LENGTH_LONG).show();
239 startActivity(DictionaryManagerActivity.getLaunchIntent());
243 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
244 if (savedInstanceState != null) {
245 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
247 indexIndex %= dictionary.indices.size();
248 Log.d(LOG, "Loading index " + indexIndex);
249 index = dictionary.indices.get(indexIndex);
250 setListAdapter(new IndexAdapter(index));
252 // Pre-load the collators.
253 new Thread(new Runnable() {
255 final long startMillis = System.currentTimeMillis();
257 TransliteratorManager.init(new TransliteratorManager.Callback() {
259 public void onTransliteratorReady() {
260 uiHandler.post(new Runnable() {
263 onSearchTextChange(searchText.getText().toString());
269 for (final Index index : dictionary.indices) {
270 final String searchToken = index.sortedIndexEntries.get(0).token;
271 final IndexEntry entry = index.findExact(searchToken);
272 if (!searchToken.equals(entry.token)) {
273 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
276 indexPrepFinished = true;
277 } catch (Exception e) {
279 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
281 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
285 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
286 if ("SYSTEM".equals(fontName)) {
287 typeface = Typeface.DEFAULT;
290 typeface = Typeface.createFromAsset(getAssets(), fontName);
291 } catch (Exception e) {
292 Log.w(LOG, "Exception trying to use typeface, using default.", e);
293 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
294 Toast.LENGTH_LONG).show();
297 // if (!"SYSTEM".equals(fontName)) {
298 // throw new RuntimeException("Test force using system font: " +
301 if (typeface == null) {
302 Log.w(LOG, "Unable to create typeface, using default.");
303 typeface = Typeface.DEFAULT;
305 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
307 fontSizeSp = Integer.parseInt(fontSize.trim());
308 } catch (NumberFormatException e) {
312 setContentView(R.layout.dictionary_activity);
313 searchText = (EditText) findViewById(R.id.SearchText);
314 searchText.requestFocus();
315 searchText.addTextChangedListener(searchTextWatcher);
316 searchText.setOnFocusChangeListener(new OnFocusChangeListener() {
318 public void onFocusChange(View v, boolean hasFocus) {
319 Log.d(LOG, "searchText onFocusChange hasFocus=" + hasFocus);
323 // Set the search text from the intent, then the saved state.
324 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
325 if (savedInstanceState != null) {
326 text = savedInstanceState.getString(C.SEARCH_TOKEN);
331 setSearchText(text, true);
332 Log.d(LOG, "Trying to restore searchText=" + text);
334 final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
335 clearSearchTextButton.setOnClickListener(new OnClickListener() {
336 public void onClick(View v) {
337 onClearSearchTextButton();
340 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
341 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
344 langButton = (Button) findViewById(R.id.LangButton);
345 langButton.setOnClickListener(new OnClickListener() {
346 public void onClick(View v) {
350 langButton.setOnLongClickListener(new OnLongClickListener() {
352 public boolean onLongClick(View v) {
353 onLanguageButtonLongClick(v.getContext());
359 final View upButton = findViewById(R.id.UpButton);
360 upButton.setOnClickListener(new OnClickListener() {
361 public void onClick(View v) {
362 onUpDownButton(true);
365 final View downButton = findViewById(R.id.DownButton);
366 downButton.setOnClickListener(new OnClickListener() {
367 public void onClick(View v) {
368 onUpDownButton(false);
372 // getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
374 // public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
376 // if (!searchText.isFocused()) {
377 // if (!isFiltered()) {
378 // final RowBase row = (RowBase) getListAdapter().getItem(position);
379 // Log.d(LOG, "onItemSelected: " + row.index());
380 // final TokenRow tokenRow = row.getTokenRow(true);
381 // searchText.setText(tokenRow.getToken());
387 // public void onNothingSelected(AdapterView<?> arg0) {
392 registerForContextMenu(getListView());
395 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
396 getString(R.string.wordListFileDefault)));
397 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
399 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
401 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
403 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
405 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
407 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
411 protected void onResume() {
412 Log.d(LOG, "onResume");
414 if (PreferenceActivity.prefsMightHaveChanged) {
415 PreferenceActivity.prefsMightHaveChanged = false;
417 startActivity(getIntent());
423 protected void onPause() {
428 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
429 super.onActivityResult(requestCode, resultCode, result);
430 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
431 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
432 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
436 private static void setDictionaryPrefs(final Context context, final File dictFile,
437 final int indexIndex, final String searchToken) {
438 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
440 prefs.putString(C.DICT_FILE, dictFile.getPath());
441 prefs.putInt(C.INDEX_INDEX, indexIndex);
442 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
447 protected void onDestroy() {
449 if (dictRaf == null) {
453 final SearchOperation searchOperation = currentSearchOperation;
454 currentSearchOperation = null;
456 // Before we close the RAF, we have to wind the current search down.
457 if (searchOperation != null) {
458 Log.d(LOG, "Interrupting search to shut down.");
459 currentSearchOperation = null;
460 searchOperation.interrupted.set(true);
464 Log.d(LOG, "Closing RAF.");
466 } catch (IOException e) {
467 Log.e(LOG, "Failed to close dictionary", e);
472 // --------------------------------------------------------------------------
474 // --------------------------------------------------------------------------
476 private void onClearSearchTextButton() {
477 setSearchText("", true);
481 private void showKeyboard() {
482 searchText.postDelayed(new Runnable() {
485 Log.d(LOG, "Trying to show soft keyboard.");
486 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
487 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
491 void updateLangButton() {
492 // final LanguageResources languageResources =
493 // Language.isoCodeToResources.get(index.shortName);
494 // if (languageResources != null && languageResources.flagId != 0) {
495 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
496 // languageResources.flagId, 0);
498 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
499 langButton.setText(index.shortName);
504 private void updateTTSLanuage() {
508 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
509 Log.d(LOG, "Setting TTS locale to: " + locale);
510 final int ttsResult = textToSpeech.setLanguage(locale);
511 if (ttsResult != TextToSpeech.LANG_AVAILABLE || ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
512 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
516 void onLanguageButton() {
517 if (currentSearchOperation != null) {
518 currentSearchOperation.interrupted.set(true);
519 currentSearchOperation = null;
521 changeIndexAndResearch((indexIndex + 1) % dictionary.indices.size());
524 void onLanguageButtonLongClick(final Context context) {
525 final Dialog dialog = new Dialog(context);
526 dialog.setContentView(R.layout.select_dictionary_dialog);
527 dialog.setTitle(R.string.selectDictionary);
529 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
532 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
534 // final LinearLayout.LayoutParams layoutParams = new
535 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
536 // ViewGroup.LayoutParams.WRAP_CONTENT);
537 // layoutParams.width = 0;
538 // layoutParams.weight = 1.0f;
540 final Button button = new Button(listView.getContext());
541 final String name = getString(R.string.dictionaryManager);
542 button.setText(name);
543 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
544 DictionaryManagerActivity.getLaunchIntent()) {
546 protected void onGo() {
548 DictionaryActivity.this.finish();
551 button.setOnClickListener(intentLauncher);
552 // button.setLayoutParams(layoutParams);
553 listView.addHeaderView(button);
554 // listView.setHeaderDividersEnabled(true);
556 listView.setAdapter(new BaseAdapter() {
558 public View getView(int position, View convertView, ViewGroup parent) {
559 final DictionaryInfo dictionaryInfo = getItem(position);
561 final LinearLayout result = new LinearLayout(parent.getContext());
563 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
565 final TextView dash = new TextView(parent.getContext());
567 result.addView(dash);
570 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
571 final Button button = new Button(parent.getContext());
572 button.setText(indexInfo.shortName);
573 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
575 application.getPath(dictionaryInfo.uncompressedFilename),
576 i, searchText.getText().toString())) {
578 protected void onGo() {
580 DictionaryActivity.this.finish();
583 button.setOnClickListener(intentLauncher);
584 result.addView(button);
588 final TextView nameView = new TextView(parent.getContext());
589 final String name = application
590 .getDictionaryName(dictionaryInfo.uncompressedFilename);
591 nameView.setText(name);
592 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
593 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
594 layoutParams.width = 0;
595 layoutParams.weight = 1.0f;
596 nameView.setLayoutParams(layoutParams);
597 result.addView(nameView);
603 public long getItemId(int position) {
608 public DictionaryInfo getItem(int position) {
609 return installedDicts.get(position);
613 public int getCount() {
614 return installedDicts.size();
621 private void changeIndexAndResearch(int newIndex) {
622 Log.d(LOG, "Changing index to: " + newIndex);
623 if (newIndex == -1) {
624 Log.e(LOG, "Invalid index.");
627 indexIndex = newIndex;
628 index = dictionary.indices.get(indexIndex);
629 indexAdapter = new IndexAdapter(index);
630 Log.d(LOG, "changingIndex, newLang=" + index.longName);
631 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
632 setListAdapter(indexAdapter);
634 setSearchText(searchText.getText().toString(), true);
637 void onUpDownButton(final boolean up) {
641 final int firstVisibleRow = getListView().getFirstVisiblePosition();
642 final RowBase row = index.rows.get(firstVisibleRow);
643 final TokenRow tokenRow = row.getTokenRow(true);
644 final int destIndexEntry;
646 if (row != tokenRow) {
647 destIndexEntry = tokenRow.referenceIndex;
649 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
653 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
655 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
656 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
657 setSearchText(dest.token, false);
658 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
662 // --------------------------------------------------------------------------
664 // --------------------------------------------------------------------------
666 final Random random = new Random();
669 public boolean onCreateOptionsMenu(final Menu menu) {
670 application.onCreateGlobalOptionsMenu(this, menu);
673 // final MenuItem randomWord = menu.add(getString(R.string.randomWord));
674 // randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
675 // public boolean onMenuItemClick(final MenuItem menuItem) {
676 // final String word = index.sortedIndexEntries.get(random
677 // .nextInt(index.sortedIndexEntries.size())).token;
678 // setSearchText(word, true);
685 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
686 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
687 public boolean onMenuItemClick(final MenuItem menuItem) {
688 startActivity(DictionaryManagerActivity.getLaunchIntent());
696 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
697 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
698 public boolean onMenuItemClick(final MenuItem menuItem) {
699 final Context context = getListView().getContext();
700 final Dialog dialog = new Dialog(context);
701 dialog.setContentView(R.layout.about_dictionary_dialog);
702 final TextView textView = (TextView) dialog.findViewById(R.id.text);
704 final String name = application.getDictionaryName(dictFile.getName());
705 dialog.setTitle(name);
707 final StringBuilder builder = new StringBuilder();
708 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
709 dictionaryInfo.uncompressedBytes = dictFile.length();
710 if (dictionaryInfo != null) {
711 builder.append(dictionaryInfo.dictInfo).append("\n\n");
712 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
715 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
718 getString(R.string.dictionaryCreationTime,
719 dictionaryInfo.creationMillis)).append("\n");
720 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
721 builder.append("\n");
722 builder.append(getString(R.string.indexName, indexInfo.shortName))
725 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
728 builder.append("\n");
729 builder.append(getString(R.string.sources)).append("\n");
730 for (final EntrySource source : dictionary.sources) {
732 getString(R.string.sourceInfo, source.getName(),
733 source.getNumEntries())).append("\n");
737 // builder.append(getString(R.string.invalidDictionary));
739 textView.setText(builder.toString());
742 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
743 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
744 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
745 dialog.getWindow().setAttributes(layoutParams);
754 // --------------------------------------------------------------------------
755 // Context Menu + clicks
756 // --------------------------------------------------------------------------
759 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
760 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
761 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
763 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
764 wordList.getName()));
765 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
766 public boolean onMenuItemClick(MenuItem item) {
767 onAppendToWordList(row);
772 final MenuItem copy = menu.add(android.R.string.copy);
773 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
774 public boolean onMenuItemClick(MenuItem item) {
780 if (selectedSpannableText != null) {
781 final String selectedText = selectedSpannableText;
782 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
783 selectedSpannableText));
784 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
785 public boolean onMenuItemClick(MenuItem item) {
786 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
792 if (row instanceof TokenRow && ttsReady) {
793 final MenuItem speak = menu.add(R.string.speak);
794 speak.setOnMenuItemClickListener(new OnMenuItemClickListener() {
796 public boolean onMenuItemClick(MenuItem item) {
797 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
798 new HashMap<String, String>());
805 private void jumpToTextFromHyperLink(final String selectedText, final int defaultIndexToUse) {
807 for (int i = 0; i < dictionary.indices.size(); ++i) {
808 final Index index = dictionary.indices.get(i);
809 if (indexPrepFinished) {
810 System.out.println("Doing index lookup: on " + selectedText);
811 final IndexEntry indexEntry = index.findExact(selectedText);
812 if (indexEntry != null) {
813 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
815 if (tokenRow != null && tokenRow.hasMainEntry) {
821 Log.w(LOG, "Skipping findExact on index " + index.shortName);
824 if (indexToUse == -1) {
825 indexToUse = defaultIndexToUse;
827 final boolean changeIndex = indexIndex != indexToUse;
829 setSearchText(selectedText, false);
830 changeIndexAndResearch(indexToUse);
832 setSearchText(selectedText, true);
837 protected void onListItemClick(ListView l, View v, int row, long id) {
839 if (clickOpensContextMenu && dictRaf != null) {
844 void onAppendToWordList(final RowBase row) {
847 final StringBuilder rawText = new StringBuilder();
848 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
849 rawText.append(index.longName).append("\t");
850 rawText.append(row.getTokenRow(true).getToken()).append("\t");
851 rawText.append(row.getRawText(saveOnlyFirstSubentry));
852 Log.d(LOG, "Writing : " + rawText);
855 wordList.getParentFile().mkdirs();
856 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
857 out.println(rawText.toString());
859 } catch (IOException e) {
860 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
862 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
863 Toast.LENGTH_LONG).show();
869 * Called when user clicks outside of search text, so that they can start
870 * typing again immediately.
872 void defocusSearchText() {
873 // Log.d(LOG, "defocusSearchText");
874 // Request focus so that if we start typing again, it clears the text
876 getListView().requestFocus();
878 // Visual indication that a new keystroke will clear the search text.
879 // Doesn't seem to work unless earchText has focus.
880 // searchText.selectAll();
883 @SuppressWarnings("deprecation")
884 void onCopy(final RowBase row) {
887 Log.d(LOG, "Copy, row=" + row);
888 final StringBuilder result = new StringBuilder();
889 result.append(row.getRawText(false));
890 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
891 clipboardManager.setText(result.toString());
892 Log.d(LOG, "Copied: " + result);
896 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
897 if (event.getUnicodeChar() != 0) {
898 if (!searchText.hasFocus()) {
899 setSearchText("" + (char) event.getUnicodeChar(), true);
903 if (keyCode == KeyEvent.KEYCODE_BACK) {
904 // Log.d(LOG, "Clearing dictionary prefs.");
905 // Pretend that we just autolaunched so that we won't do it again.
906 // DictionaryManagerActivity.lastAutoLaunchMillis =
907 // System.currentTimeMillis();
909 if (keyCode == KeyEvent.KEYCODE_ENTER) {
910 Log.d(LOG, "Trying to hide soft keyboard.");
911 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
912 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
913 InputMethodManager.HIDE_NOT_ALWAYS);
916 return super.onKeyDown(keyCode, event);
919 private void setSearchText(final String text, final boolean triggerSearch) {
920 if (!triggerSearch) {
921 getListView().requestFocus();
923 searchText.setText(text);
924 searchText.requestFocus();
927 onSearchTextChange(text);
931 private long cursorDelayMillis = 100;
933 private void moveCursorToRight() {
934 if (searchText.getLayout() != null) {
935 cursorDelayMillis = 100;
936 // Surprising, but this can crash when you rotate...
937 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
939 uiHandler.postDelayed(new Runnable() {
944 }, cursorDelayMillis);
945 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
949 // --------------------------------------------------------------------------
951 // --------------------------------------------------------------------------
953 private void searchFinished(final SearchOperation searchOperation) {
954 if (searchOperation.interrupted.get()) {
955 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
958 if (searchOperation != this.currentSearchOperation) {
959 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
963 final Index.IndexEntry searchResult = searchOperation.searchResult;
964 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
966 currentSearchOperation = null;
967 uiHandler.postDelayed(new Runnable() {
970 if (currentSearchOperation == null) {
971 if (searchResult != null) {
975 jumpToRow(searchResult.startRow);
976 } else if (searchOperation.multiWordSearchResult != null) {
977 // Multi-row search....
978 setFiltered(searchOperation);
980 throw new IllegalStateException("This should never happen.");
983 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
989 private final void jumpToRow(final int row) {
990 final boolean refocusSearchText = searchText.hasFocus();
991 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + refocusSearchText);
992 getListView().requestFocusFromTouch();
993 getListView().setSelectionFromTop(row, 0);
994 getListView().setSelected(true);
995 if (refocusSearchText) {
996 searchText.requestFocus();
998 //Log.d(LOG, "getSelectedItemPosition():" + getSelectedItemPosition());
1001 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1003 final class SearchOperation implements Runnable {
1005 final AtomicBoolean interrupted = new AtomicBoolean(false);
1007 final String searchText;
1009 List<String> searchTokens; // filled in for multiWord.
1013 long searchStartMillis;
1015 Index.IndexEntry searchResult;
1017 List<RowBase> multiWordSearchResult;
1019 boolean done = false;
1021 SearchOperation(final String searchText, final Index index) {
1022 this.searchText = searchText.trim();
1026 public String toString() {
1027 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1033 searchStartMillis = System.currentTimeMillis();
1034 final String[] searchTokenArray = WHITESPACE.split(searchText);
1035 if (searchTokenArray.length == 1) {
1036 searchResult = index.findInsertionPoint(searchText, interrupted);
1038 searchTokens = Arrays.asList(searchTokenArray);
1039 multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
1042 "searchText=" + searchText + ", searchDuration="
1043 + (System.currentTimeMillis() - searchStartMillis)
1044 + ", interrupted=" + interrupted.get());
1045 if (!interrupted.get()) {
1046 uiHandler.post(new Runnable() {
1049 searchFinished(SearchOperation.this);
1053 Log.d(LOG, "interrupted, skipping searchFinished.");
1055 } catch (Exception e) {
1056 Log.e(LOG, "Failure during search (can happen during Activity close.");
1058 synchronized (this) {
1066 // --------------------------------------------------------------------------
1068 // --------------------------------------------------------------------------
1070 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1071 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1073 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1074 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1076 final class IndexAdapter extends BaseAdapter {
1078 private static final float PADDING_DEFAULT_DP = 8;
1080 private static final float PADDING_LARGE_DP = 16;
1084 final List<RowBase> rows;
1086 final Set<String> toHighlight;
1088 private int mPaddingDefault;
1090 private int mPaddingLarge;
1092 IndexAdapter(final Index index) {
1095 this.toHighlight = null;
1099 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1102 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1106 private void getMetrics() {
1107 // Get the screen's density scale
1108 final float scale = getResources().getDisplayMetrics().density;
1109 // Convert the dps to pixels, based on density scale
1110 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1111 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1115 public int getCount() {
1120 public RowBase getItem(int position) {
1121 return rows.get(position);
1125 public long getItemId(int position) {
1126 return getItem(position).index();
1130 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1131 final TableLayout result;
1132 if (convertView instanceof TableLayout) {
1133 result = (TableLayout) convertView;
1134 result.removeAllViews();
1136 result = new TableLayout(parent.getContext());
1138 final RowBase row = getItem(position);
1139 if (row instanceof PairEntry.Row) {
1140 return getView(position, (PairEntry.Row) row, parent, result);
1141 } else if (row instanceof TokenRow) {
1142 return getView((TokenRow) row, parent, result);
1143 } else if (row instanceof HtmlEntry.Row) {
1144 return getView((HtmlEntry.Row) row, parent, result);
1146 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1150 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1151 final TableLayout result) {
1152 final PairEntry entry = row.getEntry();
1153 final int rowCount = entry.pairs.size();
1155 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1156 layoutParams.weight = 0.5f;
1157 layoutParams.leftMargin = mPaddingLarge;
1159 for (int r = 0; r < rowCount; ++r) {
1160 final TableRow tableRow = new TableRow(result.getContext());
1162 final TextView col1 = new TextView(tableRow.getContext());
1163 final TextView col2 = new TextView(tableRow.getContext());
1165 // Set the columns in the table.
1167 final TextView bullet = new TextView(tableRow.getContext());
1168 bullet.setText(" • ");
1169 tableRow.addView(bullet);
1171 tableRow.addView(col1, layoutParams);
1172 final TextView margin = new TextView(tableRow.getContext());
1173 margin.setText(" ");
1174 tableRow.addView(margin);
1176 final TextView bullet = new TextView(tableRow.getContext());
1177 bullet.setText(" • ");
1178 tableRow.addView(bullet);
1180 tableRow.addView(col2, layoutParams);
1184 // Set what's in the columns.
1186 final Pair pair = entry.pairs.get(r);
1187 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1188 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1190 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1191 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1193 // Bold the token instances in col1.
1194 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1195 .singleton(row.getTokenRow(true).getToken());
1196 final Spannable col1Spannable = (Spannable) col1.getText();
1197 for (final String token : toBold) {
1199 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1200 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1201 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1202 startPos += token.length();
1206 createTokenLinkSpans(col1, col1Spannable, col1Text);
1207 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1209 col1.setTypeface(typeface);
1210 col2.setTypeface(typeface);
1211 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1212 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1213 // col2.setBackgroundResource(theme.otherLangBg);
1215 if (index.swapPairEntries) {
1216 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1217 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1219 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1220 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1223 result.addView(tableRow);
1226 // Because we have a Button inside a ListView row:
1227 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1228 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1229 result.setClickable(true);
1230 result.setFocusable(true);
1231 result.setLongClickable(true);
1232 result.setBackgroundResource(android.R.drawable.menuitem_background);
1233 result.setOnClickListener(new TextView.OnClickListener() {
1235 public void onClick(View v) {
1236 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1243 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1244 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1245 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1246 final Context context = parent.getContext();
1248 final TableRow tableRow = new TableRow(result.getContext());
1249 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1250 : theme.tokenRowOtherBg);
1252 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1254 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1256 result.addView(tableRow);
1258 // Make it so we can long-click on these token rows, too:
1259 final TextView textView = new TextView(context);
1260 textView.setText(text, BufferType.SPANNABLE);
1261 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1262 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1264 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1265 result.setLongClickable(true);
1268 // textView.setTextColor(android.R.color.secondary_text_light);
1269 textView.setTypeface(typeface);
1270 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1272 textView.setTextAppearance(context, theme.tokenRowFg);
1273 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1275 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1279 textView.setLayoutParams(lp);
1280 tableRow.addView(textView);
1282 if (!htmlEntries.isEmpty()) {
1283 final ClickableSpan clickableSpan = new ClickableSpan() {
1285 public void onClick(View widget) {
1288 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1289 result.setClickable(true);
1290 textView.setClickable(true);
1291 textView.setMovementMethod(LinkMovementMethod.getInstance());
1292 textView.setOnClickListener(new OnClickListener() {
1294 public void onClick(View v) {
1295 final String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1296 startActivityForResult(
1297 HtmlDisplayActivity.getHtmlIntent(String.format(
1298 "<html><head></head><body>%s</body></html>", html),
1299 htmlTextToHighlight, false),
1307 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1308 final IndexEntry indexEntry = row.getIndexEntry();
1309 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1310 indexEntry.htmlEntries, null, parent, result);
1313 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1314 final HtmlEntry htmlEntry = row.getEntry();
1315 final TokenRow tokenRow = row.getTokenRow(true);
1316 return getPossibleLinkToHtmlEntryView(false,
1317 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1318 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1324 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1326 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1327 final String text) {
1328 // Saw from the source code that LinkMovementMethod sets the selection!
1329 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1330 textView.setMovementMethod(LinkMovementMethod.getInstance());
1331 final Matcher matcher = CHAR_DASH.matcher(text);
1332 while (matcher.find()) {
1333 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(),
1334 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1338 String selectedSpannableText = null;
1340 int selectedSpannableIndex = -1;
1343 public boolean onTouchEvent(MotionEvent event) {
1344 selectedSpannableText = null;
1345 selectedSpannableIndex = -1;
1346 return super.onTouchEvent(event);
1349 private class TextViewLongClickListener implements OnLongClickListener {
1352 private TextViewLongClickListener(final int index) {
1357 public boolean onLongClick(final View v) {
1358 final TextView textView = (TextView) v;
1359 final int start = textView.getSelectionStart();
1360 final int end = textView.getSelectionEnd();
1361 if (start >= 0 && end >= 0) {
1362 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1363 selectedSpannableIndex = index;
1369 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1372 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1375 // --------------------------------------------------------------------------
1377 // --------------------------------------------------------------------------
1379 void onSearchTextChange(final String text) {
1380 if ("thadolina".equals(text)) {
1381 final Dialog dialog = new Dialog(getListView().getContext());
1382 dialog.setContentView(R.layout.thadolina_dialog);
1383 dialog.setTitle("Ti amo, amore mio!");
1384 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1385 imageView.setOnClickListener(new OnClickListener() {
1387 public void onClick(View v) {
1388 final Intent intent = new Intent(Intent.ACTION_VIEW);
1389 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1390 startActivity(intent);
1395 if (dictRaf == null) {
1396 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1399 if (!searchText.isFocused()) {
1400 Log.d(LOG, "searchText changed without focus, doing nothing.");
1403 Log.d(LOG, "onSearchTextChange: " + text);
1404 if (currentSearchOperation != null) {
1405 Log.d(LOG, "Interrupting currentSearchOperation.");
1406 currentSearchOperation.interrupted.set(true);
1408 currentSearchOperation = new SearchOperation(text, index);
1409 searchExecutor.execute(currentSearchOperation);
1412 private class SearchTextWatcher implements TextWatcher {
1413 public void afterTextChanged(final Editable searchTextEditable) {
1414 if (searchText.hasFocus()) {
1415 Log.d(LOG, "SearchTextWatcher: Search text changed with focus: " + searchText.getText());
1416 // If they were typing to cause the change, update the UI.
1417 onSearchTextChange(searchText.getText().toString());
1421 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1424 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1428 // --------------------------------------------------------------------------
1429 // Filtered results.
1430 // --------------------------------------------------------------------------
1432 boolean isFiltered() {
1433 return rowsToShow != null;
1436 void setFiltered(final SearchOperation searchOperation) {
1437 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(false);
1438 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(false);
1439 rowsToShow = searchOperation.multiWordSearchResult;
1440 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1443 void clearFiltered() {
1444 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(true);
1445 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(true);
1446 setListAdapter(new IndexAdapter(index));