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;
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 int textColorFg = Color.BLACK;
131 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
133 public Thread newThread(Runnable r) {
134 return new Thread(r, "searchExecutor");
138 private SearchOperation currentSearchOperation = null;
140 C.Theme theme = C.Theme.LIGHT;
151 private File wordList = null;
153 private boolean saveOnlyFirstSubentry = false;
155 private boolean clickOpensContextMenu = false;
157 // Visible for testing.
158 ListAdapter indexAdapter = null;
160 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
163 * For some languages, loading the transliterators used in this search takes
164 * a long time, so we fire it up on a different thread, and don't invoke it
165 * from the main thread until it's already finished once.
167 private volatile boolean indexPrepFinished = false;
169 public DictionaryActivity() {
172 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
173 final String searchToken) {
174 final Intent intent = new Intent();
175 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
176 DictionaryActivity.class.getName());
177 intent.putExtra(C.DICT_FILE, dictFile.getPath());
178 intent.putExtra(C.INDEX_INDEX, indexIndex);
179 intent.putExtra(C.SEARCH_TOKEN, searchToken);
184 protected void onSaveInstanceState(final Bundle outState) {
185 super.onSaveInstanceState(outState);
186 Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
187 outState.putInt(C.INDEX_INDEX, indexIndex);
188 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
192 protected void onRestoreInstanceState(final Bundle outState) {
193 super.onRestoreInstanceState(outState);
194 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
199 public void onCreate(Bundle savedInstanceState) {
200 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
201 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
204 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
206 Log.d(LOG, "onCreate:" + this);
207 super.onCreate(savedInstanceState);
209 application = (DictionaryApplication) getApplication();
210 theme = application.getSelectedTheme();
211 textColorFg = getResources().getColor(theme.tokenRowFgColor);
213 final Intent intent = getIntent();
214 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
217 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
219 public void onInit(int status) {
226 final String name = application.getDictionaryName(dictFile.getName());
227 this.setTitle("QuickDic: " + name);
228 dictRaf = new RandomAccessFile(dictFile, "r");
229 dictionary = new Dictionary(dictRaf);
230 } catch (Exception e) {
231 Log.e(LOG, "Unable to load dictionary.", e);
232 if (dictRaf != null) {
235 } catch (IOException e1) {
236 Log.e(LOG, "Unable to close dictRaf.", e1);
240 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
241 Toast.LENGTH_LONG).show();
242 startActivity(DictionaryManagerActivity.getLaunchIntent());
246 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
247 if (savedInstanceState != null) {
248 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
250 indexIndex %= dictionary.indices.size();
251 Log.d(LOG, "Loading index " + indexIndex);
252 index = dictionary.indices.get(indexIndex);
253 setListAdapter(new IndexAdapter(index));
255 // Pre-load the collators.
256 new Thread(new Runnable() {
258 final long startMillis = System.currentTimeMillis();
260 TransliteratorManager.init(new TransliteratorManager.Callback() {
262 public void onTransliteratorReady() {
263 uiHandler.post(new Runnable() {
266 onSearchTextChange(searchText.getText().toString());
272 for (final Index index : dictionary.indices) {
273 final String searchToken = index.sortedIndexEntries.get(0).token;
274 final IndexEntry entry = index.findExact(searchToken);
275 if (!searchToken.equals(entry.token)) {
276 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
279 indexPrepFinished = true;
280 } catch (Exception e) {
282 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
284 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
288 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
289 if ("SYSTEM".equals(fontName)) {
290 typeface = Typeface.DEFAULT;
293 typeface = Typeface.createFromAsset(getAssets(), fontName);
294 } catch (Exception e) {
295 Log.w(LOG, "Exception trying to use typeface, using default.", e);
296 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
297 Toast.LENGTH_LONG).show();
300 // if (!"SYSTEM".equals(fontName)) {
301 // throw new RuntimeException("Test force using system font: " +
304 if (typeface == null) {
305 Log.w(LOG, "Unable to create typeface, using default.");
306 typeface = Typeface.DEFAULT;
308 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
310 fontSizeSp = Integer.parseInt(fontSize.trim());
311 } catch (NumberFormatException e) {
315 setContentView(R.layout.dictionary_activity);
316 searchText = (EditText) findViewById(R.id.SearchText);
317 searchText.requestFocus();
318 searchText.addTextChangedListener(searchTextWatcher);
319 searchText.setOnFocusChangeListener(new OnFocusChangeListener() {
321 public void onFocusChange(View v, boolean hasFocus) {
322 Log.d(LOG, "searchText onFocusChange hasFocus=" + hasFocus);
326 // Set the search text from the intent, then the saved state.
327 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
328 if (savedInstanceState != null) {
329 text = savedInstanceState.getString(C.SEARCH_TOKEN);
334 setSearchText(text, true);
335 Log.d(LOG, "Trying to restore searchText=" + text);
337 final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
338 clearSearchTextButton.setOnClickListener(new OnClickListener() {
339 public void onClick(View v) {
340 onClearSearchTextButton();
343 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
344 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
347 langButton = (Button) findViewById(R.id.LangButton);
348 langButton.setOnClickListener(new OnClickListener() {
349 public void onClick(View v) {
353 langButton.setOnLongClickListener(new OnLongClickListener() {
355 public boolean onLongClick(View v) {
356 onLanguageButtonLongClick(v.getContext());
362 final View upButton = findViewById(R.id.UpButton);
363 upButton.setOnClickListener(new OnClickListener() {
364 public void onClick(View v) {
365 onUpDownButton(true);
368 final View downButton = findViewById(R.id.DownButton);
369 downButton.setOnClickListener(new OnClickListener() {
370 public void onClick(View v) {
371 onUpDownButton(false);
375 // getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
377 // public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
379 // if (!searchText.isFocused()) {
380 // if (!isFiltered()) {
381 // final RowBase row = (RowBase) getListAdapter().getItem(position);
382 // Log.d(LOG, "onItemSelected: " + row.index());
383 // final TokenRow tokenRow = row.getTokenRow(true);
384 // searchText.setText(tokenRow.getToken());
390 // public void onNothingSelected(AdapterView<?> arg0) {
395 registerForContextMenu(getListView());
398 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
399 getString(R.string.wordListFileDefault)));
400 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
402 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
404 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
406 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
408 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
410 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
414 protected void onResume() {
415 Log.d(LOG, "onResume");
417 if (PreferenceActivity.prefsMightHaveChanged) {
418 PreferenceActivity.prefsMightHaveChanged = false;
420 startActivity(getIntent());
426 protected void onPause() {
431 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
432 super.onActivityResult(requestCode, resultCode, result);
433 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
434 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
435 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
439 private static void setDictionaryPrefs(final Context context, final File dictFile,
440 final int indexIndex, final String searchToken) {
441 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
443 prefs.putString(C.DICT_FILE, dictFile.getPath());
444 prefs.putInt(C.INDEX_INDEX, indexIndex);
445 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
450 protected void onDestroy() {
452 if (dictRaf == null) {
456 final SearchOperation searchOperation = currentSearchOperation;
457 currentSearchOperation = null;
459 // Before we close the RAF, we have to wind the current search down.
460 if (searchOperation != null) {
461 Log.d(LOG, "Interrupting search to shut down.");
462 currentSearchOperation = null;
463 searchOperation.interrupted.set(true);
467 Log.d(LOG, "Closing RAF.");
469 } catch (IOException e) {
470 Log.e(LOG, "Failed to close dictionary", e);
475 // --------------------------------------------------------------------------
477 // --------------------------------------------------------------------------
479 private void onClearSearchTextButton() {
480 setSearchText("", true);
484 private void showKeyboard() {
485 searchText.postDelayed(new Runnable() {
488 Log.d(LOG, "Trying to show soft keyboard.");
489 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
490 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
494 void updateLangButton() {
495 // final LanguageResources languageResources =
496 // Language.isoCodeToResources.get(index.shortName);
497 // if (languageResources != null && languageResources.flagId != 0) {
498 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
499 // languageResources.flagId, 0);
501 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
502 langButton.setText(index.shortName);
507 private void updateTTSLanuage() {
511 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
512 Log.d(LOG, "Setting TTS locale to: " + locale);
513 final int ttsResult = textToSpeech.setLanguage(locale);
514 if (ttsResult != TextToSpeech.LANG_AVAILABLE || ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
515 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
519 void onLanguageButton() {
520 if (currentSearchOperation != null) {
521 currentSearchOperation.interrupted.set(true);
522 currentSearchOperation = null;
524 changeIndexAndResearch((indexIndex + 1) % dictionary.indices.size());
527 void onLanguageButtonLongClick(final Context context) {
528 final Dialog dialog = new Dialog(context);
529 dialog.setContentView(R.layout.select_dictionary_dialog);
530 dialog.setTitle(R.string.selectDictionary);
532 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
535 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
537 // final LinearLayout.LayoutParams layoutParams = new
538 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
539 // ViewGroup.LayoutParams.WRAP_CONTENT);
540 // layoutParams.width = 0;
541 // layoutParams.weight = 1.0f;
543 final Button button = new Button(listView.getContext());
544 final String name = getString(R.string.dictionaryManager);
545 button.setText(name);
546 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
547 DictionaryManagerActivity.getLaunchIntent()) {
549 protected void onGo() {
551 DictionaryActivity.this.finish();
554 button.setOnClickListener(intentLauncher);
555 // button.setLayoutParams(layoutParams);
556 listView.addHeaderView(button);
557 // listView.setHeaderDividersEnabled(true);
559 listView.setAdapter(new BaseAdapter() {
561 public View getView(int position, View convertView, ViewGroup parent) {
562 final DictionaryInfo dictionaryInfo = getItem(position);
564 final LinearLayout result = new LinearLayout(parent.getContext());
566 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
568 final TextView dash = new TextView(parent.getContext());
570 result.addView(dash);
573 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
574 final Button button = new Button(parent.getContext());
575 button.setText(indexInfo.shortName);
576 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
578 application.getPath(dictionaryInfo.uncompressedFilename),
579 i, searchText.getText().toString())) {
581 protected void onGo() {
583 DictionaryActivity.this.finish();
586 button.setOnClickListener(intentLauncher);
587 result.addView(button);
591 final TextView nameView = new TextView(parent.getContext());
592 final String name = application
593 .getDictionaryName(dictionaryInfo.uncompressedFilename);
594 nameView.setText(name);
595 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
596 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
597 layoutParams.width = 0;
598 layoutParams.weight = 1.0f;
599 nameView.setLayoutParams(layoutParams);
600 result.addView(nameView);
606 public long getItemId(int position) {
611 public DictionaryInfo getItem(int position) {
612 return installedDicts.get(position);
616 public int getCount() {
617 return installedDicts.size();
624 private void changeIndexAndResearch(int newIndex) {
625 Log.d(LOG, "Changing index to: " + newIndex);
626 if (newIndex == -1) {
627 Log.e(LOG, "Invalid index.");
630 indexIndex = newIndex;
631 index = dictionary.indices.get(indexIndex);
632 indexAdapter = new IndexAdapter(index);
633 Log.d(LOG, "changingIndex, newLang=" + index.longName);
634 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
635 setListAdapter(indexAdapter);
637 setSearchText(searchText.getText().toString(), true);
640 void onUpDownButton(final boolean up) {
644 final int firstVisibleRow = getListView().getFirstVisiblePosition();
645 final RowBase row = index.rows.get(firstVisibleRow);
646 final TokenRow tokenRow = row.getTokenRow(true);
647 final int destIndexEntry;
649 if (row != tokenRow) {
650 destIndexEntry = tokenRow.referenceIndex;
652 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
656 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
658 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
659 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
660 setSearchText(dest.token, false);
661 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
665 // --------------------------------------------------------------------------
667 // --------------------------------------------------------------------------
669 final Random random = new Random();
672 public boolean onCreateOptionsMenu(final Menu menu) {
673 application.onCreateGlobalOptionsMenu(this, menu);
676 // final MenuItem randomWord = menu.add(getString(R.string.randomWord));
677 // randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
678 // public boolean onMenuItemClick(final MenuItem menuItem) {
679 // final String word = index.sortedIndexEntries.get(random
680 // .nextInt(index.sortedIndexEntries.size())).token;
681 // setSearchText(word, true);
688 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
689 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
690 public boolean onMenuItemClick(final MenuItem menuItem) {
691 startActivity(DictionaryManagerActivity.getLaunchIntent());
699 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
700 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
701 public boolean onMenuItemClick(final MenuItem menuItem) {
702 final Context context = getListView().getContext();
703 final Dialog dialog = new Dialog(context);
704 dialog.setContentView(R.layout.about_dictionary_dialog);
705 final TextView textView = (TextView) dialog.findViewById(R.id.text);
707 final String name = application.getDictionaryName(dictFile.getName());
708 dialog.setTitle(name);
710 final StringBuilder builder = new StringBuilder();
711 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
712 dictionaryInfo.uncompressedBytes = dictFile.length();
713 if (dictionaryInfo != null) {
714 builder.append(dictionaryInfo.dictInfo).append("\n\n");
715 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
718 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
721 getString(R.string.dictionaryCreationTime,
722 dictionaryInfo.creationMillis)).append("\n");
723 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
724 builder.append("\n");
725 builder.append(getString(R.string.indexName, indexInfo.shortName))
728 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
731 builder.append("\n");
732 builder.append(getString(R.string.sources)).append("\n");
733 for (final EntrySource source : dictionary.sources) {
735 getString(R.string.sourceInfo, source.getName(),
736 source.getNumEntries())).append("\n");
740 // builder.append(getString(R.string.invalidDictionary));
742 textView.setText(builder.toString());
745 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
746 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
747 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
748 dialog.getWindow().setAttributes(layoutParams);
757 // --------------------------------------------------------------------------
758 // Context Menu + clicks
759 // --------------------------------------------------------------------------
762 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
763 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
764 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
766 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
767 wordList.getName()));
768 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
769 public boolean onMenuItemClick(MenuItem item) {
770 onAppendToWordList(row);
775 final MenuItem copy = menu.add(android.R.string.copy);
776 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
777 public boolean onMenuItemClick(MenuItem item) {
783 if (selectedSpannableText != null) {
784 final String selectedText = selectedSpannableText;
785 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
786 selectedSpannableText));
787 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
788 public boolean onMenuItemClick(MenuItem item) {
789 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
795 if (row instanceof TokenRow && ttsReady) {
796 final MenuItem speak = menu.add(R.string.speak);
797 speak.setOnMenuItemClickListener(new OnMenuItemClickListener() {
799 public boolean onMenuItemClick(MenuItem item) {
800 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
801 new HashMap<String, String>());
808 private void jumpToTextFromHyperLink(final String selectedText, final int defaultIndexToUse) {
810 for (int i = 0; i < dictionary.indices.size(); ++i) {
811 final Index index = dictionary.indices.get(i);
812 if (indexPrepFinished) {
813 System.out.println("Doing index lookup: on " + selectedText);
814 final IndexEntry indexEntry = index.findExact(selectedText);
815 if (indexEntry != null) {
816 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
818 if (tokenRow != null && tokenRow.hasMainEntry) {
824 Log.w(LOG, "Skipping findExact on index " + index.shortName);
827 if (indexToUse == -1) {
828 indexToUse = defaultIndexToUse;
830 final boolean changeIndex = indexIndex != indexToUse;
832 setSearchText(selectedText, false);
833 changeIndexAndResearch(indexToUse);
835 setSearchText(selectedText, true);
840 protected void onListItemClick(ListView l, View v, int row, long id) {
842 if (clickOpensContextMenu && dictRaf != null) {
847 void onAppendToWordList(final RowBase row) {
850 final StringBuilder rawText = new StringBuilder();
851 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
852 rawText.append(index.longName).append("\t");
853 rawText.append(row.getTokenRow(true).getToken()).append("\t");
854 rawText.append(row.getRawText(saveOnlyFirstSubentry));
855 Log.d(LOG, "Writing : " + rawText);
858 wordList.getParentFile().mkdirs();
859 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
860 out.println(rawText.toString());
862 } catch (IOException e) {
863 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
865 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
866 Toast.LENGTH_LONG).show();
872 * Called when user clicks outside of search text, so that they can start
873 * typing again immediately.
875 void defocusSearchText() {
876 // Log.d(LOG, "defocusSearchText");
877 // Request focus so that if we start typing again, it clears the text
879 getListView().requestFocus();
881 // Visual indication that a new keystroke will clear the search text.
882 // Doesn't seem to work unless earchText has focus.
883 // searchText.selectAll();
886 @SuppressWarnings("deprecation")
887 void onCopy(final RowBase row) {
890 Log.d(LOG, "Copy, row=" + row);
891 final StringBuilder result = new StringBuilder();
892 result.append(row.getRawText(false));
893 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
894 clipboardManager.setText(result.toString());
895 Log.d(LOG, "Copied: " + result);
899 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
900 if (event.getUnicodeChar() != 0) {
901 if (!searchText.hasFocus()) {
902 setSearchText("" + (char) event.getUnicodeChar(), true);
906 if (keyCode == KeyEvent.KEYCODE_BACK) {
907 // Log.d(LOG, "Clearing dictionary prefs.");
908 // Pretend that we just autolaunched so that we won't do it again.
909 // DictionaryManagerActivity.lastAutoLaunchMillis =
910 // System.currentTimeMillis();
912 if (keyCode == KeyEvent.KEYCODE_ENTER) {
913 Log.d(LOG, "Trying to hide soft keyboard.");
914 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
915 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
916 InputMethodManager.HIDE_NOT_ALWAYS);
919 return super.onKeyDown(keyCode, event);
922 private void setSearchText(final String text, final boolean triggerSearch) {
923 if (!triggerSearch) {
924 getListView().requestFocus();
926 searchText.setText(text);
927 searchText.requestFocus();
930 onSearchTextChange(text);
934 private long cursorDelayMillis = 100;
936 private void moveCursorToRight() {
937 if (searchText.getLayout() != null) {
938 cursorDelayMillis = 100;
939 // Surprising, but this can crash when you rotate...
940 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
942 uiHandler.postDelayed(new Runnable() {
947 }, cursorDelayMillis);
948 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
952 // --------------------------------------------------------------------------
954 // --------------------------------------------------------------------------
956 private void searchFinished(final SearchOperation searchOperation) {
957 if (searchOperation.interrupted.get()) {
958 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
961 if (searchOperation != this.currentSearchOperation) {
962 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
966 final Index.IndexEntry searchResult = searchOperation.searchResult;
967 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
969 currentSearchOperation = null;
970 uiHandler.postDelayed(new Runnable() {
973 if (currentSearchOperation == null) {
974 if (searchResult != null) {
978 jumpToRow(searchResult.startRow);
979 } else if (searchOperation.multiWordSearchResult != null) {
980 // Multi-row search....
981 setFiltered(searchOperation);
983 throw new IllegalStateException("This should never happen.");
986 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
992 private final void jumpToRow(final int row) {
993 final boolean refocusSearchText = searchText.hasFocus();
994 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + refocusSearchText);
995 getListView().requestFocusFromTouch();
996 getListView().setSelectionFromTop(row, 0);
997 getListView().setSelected(true);
998 if (refocusSearchText) {
999 searchText.requestFocus();
1001 //Log.d(LOG, "getSelectedItemPosition():" + getSelectedItemPosition());
1004 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1006 final class SearchOperation implements Runnable {
1008 final AtomicBoolean interrupted = new AtomicBoolean(false);
1010 final String searchText;
1012 List<String> searchTokens; // filled in for multiWord.
1016 long searchStartMillis;
1018 Index.IndexEntry searchResult;
1020 List<RowBase> multiWordSearchResult;
1022 boolean done = false;
1024 SearchOperation(final String searchText, final Index index) {
1025 this.searchText = searchText.trim();
1029 public String toString() {
1030 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1036 searchStartMillis = System.currentTimeMillis();
1037 final String[] searchTokenArray = WHITESPACE.split(searchText);
1038 if (searchTokenArray.length == 1) {
1039 searchResult = index.findInsertionPoint(searchText, interrupted);
1041 searchTokens = Arrays.asList(searchTokenArray);
1042 multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
1045 "searchText=" + searchText + ", searchDuration="
1046 + (System.currentTimeMillis() - searchStartMillis)
1047 + ", interrupted=" + interrupted.get());
1048 if (!interrupted.get()) {
1049 uiHandler.post(new Runnable() {
1052 searchFinished(SearchOperation.this);
1056 Log.d(LOG, "interrupted, skipping searchFinished.");
1058 } catch (Exception e) {
1059 Log.e(LOG, "Failure during search (can happen during Activity close.");
1061 synchronized (this) {
1069 // --------------------------------------------------------------------------
1071 // --------------------------------------------------------------------------
1073 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1074 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1076 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1077 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1079 final class IndexAdapter extends BaseAdapter {
1081 private static final float PADDING_DEFAULT_DP = 8;
1083 private static final float PADDING_LARGE_DP = 16;
1087 final List<RowBase> rows;
1089 final Set<String> toHighlight;
1091 private int mPaddingDefault;
1093 private int mPaddingLarge;
1095 IndexAdapter(final Index index) {
1098 this.toHighlight = null;
1102 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1105 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1109 private void getMetrics() {
1110 // Get the screen's density scale
1111 final float scale = getResources().getDisplayMetrics().density;
1112 // Convert the dps to pixels, based on density scale
1113 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1114 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1118 public int getCount() {
1123 public RowBase getItem(int position) {
1124 return rows.get(position);
1128 public long getItemId(int position) {
1129 return getItem(position).index();
1133 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1134 final TableLayout result;
1135 if (convertView instanceof TableLayout) {
1136 result = (TableLayout) convertView;
1137 result.removeAllViews();
1139 result = new TableLayout(parent.getContext());
1141 final RowBase row = getItem(position);
1142 if (row instanceof PairEntry.Row) {
1143 return getView(position, (PairEntry.Row) row, parent, result);
1144 } else if (row instanceof TokenRow) {
1145 return getView((TokenRow) row, parent, result);
1146 } else if (row instanceof HtmlEntry.Row) {
1147 return getView((HtmlEntry.Row) row, parent, result);
1149 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1153 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1154 final TableLayout result) {
1155 final PairEntry entry = row.getEntry();
1156 final int rowCount = entry.pairs.size();
1158 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1159 layoutParams.weight = 0.5f;
1160 layoutParams.leftMargin = mPaddingLarge;
1162 for (int r = 0; r < rowCount; ++r) {
1163 final TableRow tableRow = new TableRow(result.getContext());
1165 final TextView col1 = new TextView(tableRow.getContext());
1166 final TextView col2 = new TextView(tableRow.getContext());
1168 // Set the columns in the table.
1170 final TextView bullet = new TextView(tableRow.getContext());
1171 bullet.setText(" • ");
1172 tableRow.addView(bullet);
1174 tableRow.addView(col1, layoutParams);
1175 final TextView margin = new TextView(tableRow.getContext());
1176 margin.setText(" ");
1177 tableRow.addView(margin);
1179 final TextView bullet = new TextView(tableRow.getContext());
1180 bullet.setText(" • ");
1181 tableRow.addView(bullet);
1183 tableRow.addView(col2, layoutParams);
1187 // Set what's in the columns.
1189 final Pair pair = entry.pairs.get(r);
1190 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1191 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1193 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1194 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1196 // Bold the token instances in col1.
1197 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1198 .singleton(row.getTokenRow(true).getToken());
1199 final Spannable col1Spannable = (Spannable) col1.getText();
1200 for (final String token : toBold) {
1202 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1203 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1204 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1205 startPos += token.length();
1209 createTokenLinkSpans(col1, col1Spannable, col1Text);
1210 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1212 col1.setTypeface(typeface);
1213 col2.setTypeface(typeface);
1214 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1215 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1216 // col2.setBackgroundResource(theme.otherLangBg);
1218 if (index.swapPairEntries) {
1219 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1220 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1222 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1223 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1226 result.addView(tableRow);
1229 // Because we have a Button inside a ListView row:
1230 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1231 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1232 result.setClickable(true);
1233 result.setFocusable(true);
1234 result.setLongClickable(true);
1235 result.setBackgroundResource(android.R.drawable.menuitem_background);
1236 result.setOnClickListener(new TextView.OnClickListener() {
1238 public void onClick(View v) {
1239 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1246 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1247 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1248 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1249 final Context context = parent.getContext();
1251 final TableRow tableRow = new TableRow(result.getContext());
1252 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1253 : theme.tokenRowOtherBg);
1255 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1257 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1259 result.addView(tableRow);
1261 // Make it so we can long-click on these token rows, too:
1262 final TextView textView = new TextView(context);
1263 textView.setText(text, BufferType.SPANNABLE);
1264 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1265 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1267 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1268 result.setLongClickable(true);
1271 // textView.setTextColor(android.R.color.secondary_text_light);
1272 textView.setTypeface(typeface);
1273 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1275 textView.setTextAppearance(context, theme.tokenRowFg);
1276 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1278 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1282 textView.setLayoutParams(lp);
1283 tableRow.addView(textView);
1285 if (!htmlEntries.isEmpty()) {
1286 final ClickableSpan clickableSpan = new ClickableSpan() {
1288 public void onClick(View widget) {
1291 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1292 result.setClickable(true);
1293 textView.setClickable(true);
1294 textView.setMovementMethod(LinkMovementMethod.getInstance());
1295 textView.setOnClickListener(new OnClickListener() {
1297 public void onClick(View v) {
1298 final String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1299 startActivityForResult(
1300 HtmlDisplayActivity.getHtmlIntent(String.format(
1301 "<html><head></head><body>%s</body></html>", html),
1302 htmlTextToHighlight, false),
1310 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1311 final IndexEntry indexEntry = row.getIndexEntry();
1312 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1313 indexEntry.htmlEntries, null, parent, result);
1316 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1317 final HtmlEntry htmlEntry = row.getEntry();
1318 final TokenRow tokenRow = row.getTokenRow(true);
1319 return getPossibleLinkToHtmlEntryView(false,
1320 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1321 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1327 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1329 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1330 final String text) {
1331 // Saw from the source code that LinkMovementMethod sets the selection!
1332 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1333 textView.setMovementMethod(LinkMovementMethod.getInstance());
1334 final Matcher matcher = CHAR_DASH.matcher(text);
1335 while (matcher.find()) {
1336 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
1337 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1341 String selectedSpannableText = null;
1343 int selectedSpannableIndex = -1;
1346 public boolean onTouchEvent(MotionEvent event) {
1347 selectedSpannableText = null;
1348 selectedSpannableIndex = -1;
1349 return super.onTouchEvent(event);
1352 private class TextViewLongClickListener implements OnLongClickListener {
1355 private TextViewLongClickListener(final int index) {
1360 public boolean onLongClick(final View v) {
1361 final TextView textView = (TextView) v;
1362 final int start = textView.getSelectionStart();
1363 final int end = textView.getSelectionEnd();
1364 if (start >= 0 && end >= 0) {
1365 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1366 selectedSpannableIndex = index;
1372 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1375 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1378 // --------------------------------------------------------------------------
1380 // --------------------------------------------------------------------------
1382 void onSearchTextChange(final String text) {
1383 if ("thadolina".equals(text)) {
1384 final Dialog dialog = new Dialog(getListView().getContext());
1385 dialog.setContentView(R.layout.thadolina_dialog);
1386 dialog.setTitle("Ti amo, amore mio!");
1387 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1388 imageView.setOnClickListener(new OnClickListener() {
1390 public void onClick(View v) {
1391 final Intent intent = new Intent(Intent.ACTION_VIEW);
1392 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1393 startActivity(intent);
1398 if (dictRaf == null) {
1399 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1402 if (!searchText.isFocused()) {
1403 Log.d(LOG, "searchText changed without focus, doing nothing.");
1406 Log.d(LOG, "onSearchTextChange: " + text);
1407 if (currentSearchOperation != null) {
1408 Log.d(LOG, "Interrupting currentSearchOperation.");
1409 currentSearchOperation.interrupted.set(true);
1411 currentSearchOperation = new SearchOperation(text, index);
1412 searchExecutor.execute(currentSearchOperation);
1415 private class SearchTextWatcher implements TextWatcher {
1416 public void afterTextChanged(final Editable searchTextEditable) {
1417 if (searchText.hasFocus()) {
1418 Log.d(LOG, "SearchTextWatcher: Search text changed with focus: " + searchText.getText());
1419 // If they were typing to cause the change, update the UI.
1420 onSearchTextChange(searchText.getText().toString());
1424 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1427 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1431 // --------------------------------------------------------------------------
1432 // Filtered results.
1433 // --------------------------------------------------------------------------
1435 boolean isFiltered() {
1436 return rowsToShow != null;
1439 void setFiltered(final SearchOperation searchOperation) {
1440 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(false);
1441 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(false);
1442 rowsToShow = searchOperation.multiWordSearchResult;
1443 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1446 void clearFiltered() {
1447 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(true);
1448 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(true);
1449 setListAdapter(new IndexAdapter(index));