1 // Copyright 2011 Google Inc. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 package com.hughes.android.dictionary;
17 import android.app.Dialog;
18 import android.app.ListActivity;
19 import android.content.Context;
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.graphics.Color;
23 import android.graphics.Typeface;
24 import android.net.Uri;
25 import android.os.Bundle;
26 import android.os.Handler;
27 import android.preference.PreferenceManager;
28 import android.speech.tts.TextToSpeech;
29 import android.speech.tts.TextToSpeech.OnInitListener;
30 import android.text.ClipboardManager;
31 import android.text.Editable;
32 import android.text.Selection;
33 import android.text.Spannable;
34 import android.text.TextWatcher;
35 import android.text.method.LinkMovementMethod;
36 import android.text.style.ClickableSpan;
37 import android.text.style.StyleSpan;
38 import android.util.Log;
39 import android.util.TypedValue;
40 import android.view.ContextMenu;
41 import android.view.ContextMenu.ContextMenuInfo;
42 import android.view.KeyEvent;
43 import android.view.Menu;
44 import android.view.MenuItem;
45 import android.view.MenuItem.OnMenuItemClickListener;
46 import android.view.MotionEvent;
47 import android.view.View;
48 import android.view.View.OnClickListener;
49 import android.view.View.OnFocusChangeListener;
50 import android.view.View.OnLongClickListener;
51 import android.view.ViewGroup;
52 import android.view.WindowManager;
53 import android.view.inputmethod.InputMethodManager;
54 import android.widget.AdapterView.AdapterContextMenuInfo;
55 import android.widget.BaseAdapter;
56 import android.widget.Button;
57 import android.widget.EditText;
58 import android.widget.ImageButton;
59 import android.widget.ImageView;
60 import android.widget.LinearLayout;
61 import android.widget.ListAdapter;
62 import android.widget.ListView;
63 import android.widget.TableLayout;
64 import android.widget.TableRow;
65 import android.widget.TextView;
66 import android.widget.TextView.BufferType;
67 import android.widget.Toast;
69 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
70 import com.hughes.android.dictionary.engine.Dictionary;
71 import com.hughes.android.dictionary.engine.EntrySource;
72 import com.hughes.android.dictionary.engine.HtmlEntry;
73 import com.hughes.android.dictionary.engine.Index;
74 import com.hughes.android.dictionary.engine.Index.IndexEntry;
75 import com.hughes.android.dictionary.engine.PairEntry;
76 import com.hughes.android.dictionary.engine.PairEntry.Pair;
77 import com.hughes.android.dictionary.engine.RowBase;
78 import com.hughes.android.dictionary.engine.TokenRow;
79 import com.hughes.android.dictionary.engine.TransliteratorManager;
80 import com.hughes.android.util.IntentLauncher;
81 import com.hughes.android.util.NonLinkClickableSpan;
82 import com.hughes.util.StringUtil;
85 import java.io.FileWriter;
86 import java.io.IOException;
87 import java.io.PrintWriter;
88 import java.io.RandomAccessFile;
89 import java.text.SimpleDateFormat;
90 import java.util.Arrays;
91 import java.util.Collections;
92 import java.util.Date;
93 import java.util.HashMap;
94 import java.util.LinkedHashSet;
95 import java.util.List;
96 import java.util.Locale;
97 import java.util.Random;
99 import java.util.concurrent.Executor;
100 import java.util.concurrent.Executors;
101 import java.util.concurrent.ThreadFactory;
102 import java.util.concurrent.atomic.AtomicBoolean;
103 import java.util.regex.Matcher;
104 import java.util.regex.Pattern;
106 public class DictionaryActivity extends ListActivity {
108 static final String LOG = "QuickDic";
110 DictionaryApplication application;
112 File dictFile = null;
114 RandomAccessFile dictRaf = null;
116 Dictionary dictionary = null;
122 List<RowBase> rowsToShow = null; // if not null, just show these rows.
125 final Handler uiHandler = new Handler();
127 TextToSpeech textToSpeech;
128 volatile boolean ttsReady;
130 int textColorFg = Color.BLACK;
133 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
135 public Thread newThread(Runnable r) {
136 return new Thread(r, "searchExecutor");
140 private SearchOperation currentSearchOperation = null;
142 C.Theme theme = C.Theme.LIGHT;
153 private File wordList = null;
155 private boolean saveOnlyFirstSubentry = false;
157 private boolean clickOpensContextMenu = false;
159 // Visible for testing.
160 ListAdapter indexAdapter = null;
162 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
165 * For some languages, loading the transliterators used in this search takes
166 * a long time, so we fire it up on a different thread, and don't invoke it
167 * from the main thread until it's already finished once.
169 private volatile boolean indexPrepFinished = false;
171 public DictionaryActivity() {
174 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
175 final String searchToken) {
176 final Intent intent = new Intent();
177 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
178 DictionaryActivity.class.getName());
179 intent.putExtra(C.DICT_FILE, dictFile.getPath());
180 intent.putExtra(C.INDEX_INDEX, indexIndex);
181 intent.putExtra(C.SEARCH_TOKEN, searchToken);
186 protected void onSaveInstanceState(final Bundle outState) {
187 super.onSaveInstanceState(outState);
188 Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
189 outState.putInt(C.INDEX_INDEX, indexIndex);
190 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
194 protected void onRestoreInstanceState(final Bundle outState) {
195 super.onRestoreInstanceState(outState);
196 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
201 public void onCreate(Bundle savedInstanceState) {
202 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
203 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
206 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
208 Log.d(LOG, "onCreate:" + this);
209 super.onCreate(savedInstanceState);
211 application = (DictionaryApplication) getApplication();
212 theme = application.getSelectedTheme();
213 textColorFg = getResources().getColor(theme.tokenRowFgColor);
215 final Intent intent = getIntent();
216 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
219 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
221 public void onInit(int status) {
228 final String name = application.getDictionaryName(dictFile.getName());
229 this.setTitle("QuickDic: " + name);
230 dictRaf = new RandomAccessFile(dictFile, "r");
231 dictionary = new Dictionary(dictRaf);
232 } catch (Exception e) {
233 Log.e(LOG, "Unable to load dictionary.", e);
234 if (dictRaf != null) {
237 } catch (IOException e1) {
238 Log.e(LOG, "Unable to close dictRaf.", e1);
242 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
243 Toast.LENGTH_LONG).show();
244 startActivity(DictionaryManagerActivity.getLaunchIntent());
248 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
249 if (savedInstanceState != null) {
250 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
252 indexIndex %= dictionary.indices.size();
253 Log.d(LOG, "Loading index " + indexIndex);
254 index = dictionary.indices.get(indexIndex);
255 setListAdapter(new IndexAdapter(index));
257 // Pre-load the collators.
258 new Thread(new Runnable() {
260 final long startMillis = System.currentTimeMillis();
262 TransliteratorManager.init(new TransliteratorManager.Callback() {
264 public void onTransliteratorReady() {
265 uiHandler.post(new Runnable() {
268 onSearchTextChange(searchText.getText().toString());
274 for (final Index index : dictionary.indices) {
275 final String searchToken = index.sortedIndexEntries.get(0).token;
276 final IndexEntry entry = index.findExact(searchToken);
277 if (!searchToken.equals(entry.token)) {
278 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
281 indexPrepFinished = true;
282 } catch (Exception e) {
284 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
286 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
290 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
291 if ("SYSTEM".equals(fontName)) {
292 typeface = Typeface.DEFAULT;
295 typeface = Typeface.createFromAsset(getAssets(), fontName);
296 } catch (Exception e) {
297 Log.w(LOG, "Exception trying to use typeface, using default.", e);
298 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
299 Toast.LENGTH_LONG).show();
302 // if (!"SYSTEM".equals(fontName)) {
303 // throw new RuntimeException("Test force using system font: " +
306 if (typeface == null) {
307 Log.w(LOG, "Unable to create typeface, using default.");
308 typeface = Typeface.DEFAULT;
310 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
312 fontSizeSp = Integer.parseInt(fontSize.trim());
313 } catch (NumberFormatException e) {
317 setContentView(R.layout.dictionary_activity);
318 searchText = (EditText) findViewById(R.id.SearchText);
319 searchText.requestFocus();
320 searchText.addTextChangedListener(searchTextWatcher);
321 searchText.setOnFocusChangeListener(new OnFocusChangeListener() {
323 public void onFocusChange(View v, boolean hasFocus) {
324 Log.d(LOG, "searchText onFocusChange hasFocus=" + hasFocus);
328 // Set the search text from the intent, then the saved state.
329 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
330 if (savedInstanceState != null) {
331 text = savedInstanceState.getString(C.SEARCH_TOKEN);
336 setSearchText(text, true);
337 Log.d(LOG, "Trying to restore searchText=" + text);
339 final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
340 clearSearchTextButton.setOnClickListener(new OnClickListener() {
341 public void onClick(View v) {
342 onClearSearchTextButton();
345 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
346 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
349 langButton = (Button) findViewById(R.id.LangButton);
350 langButton.setOnClickListener(new OnClickListener() {
351 public void onClick(View v) {
355 langButton.setOnLongClickListener(new OnLongClickListener() {
357 public boolean onLongClick(View v) {
358 onLanguageButtonLongClick(v.getContext());
364 final View upButton = findViewById(R.id.UpButton);
365 upButton.setOnClickListener(new OnClickListener() {
366 public void onClick(View v) {
367 onUpDownButton(true);
370 final View downButton = findViewById(R.id.DownButton);
371 downButton.setOnClickListener(new OnClickListener() {
372 public void onClick(View v) {
373 onUpDownButton(false);
376 upButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
377 .getBoolean(getString(R.string.showPrevNextButtonsKey), true) ? View.VISIBLE
379 downButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
380 .getBoolean(getString(R.string.showPrevNextButtonsKey), true) ? View.VISIBLE
383 // getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
385 // public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
387 // if (!searchText.isFocused()) {
388 // if (!isFiltered()) {
389 // final RowBase row = (RowBase) getListAdapter().getItem(position);
390 // Log.d(LOG, "onItemSelected: " + row.index());
391 // final TokenRow tokenRow = row.getTokenRow(true);
392 // searchText.setText(tokenRow.getToken());
398 // public void onNothingSelected(AdapterView<?> arg0) {
403 registerForContextMenu(getListView());
406 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
407 getString(R.string.wordListFileDefault)));
408 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
410 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
412 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
414 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
416 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
418 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
422 protected void onResume() {
423 Log.d(LOG, "onResume");
425 if (SettingsActivity.settingsMightHaveChanged) {
426 SettingsActivity.settingsMightHaveChanged = false;
428 startActivity(getIntent());
434 protected void onPause() {
439 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
440 super.onActivityResult(requestCode, resultCode, result);
441 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
442 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
443 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
447 private static void setDictionaryPrefs(final Context context, final File dictFile,
448 final int indexIndex, final String searchToken) {
449 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
451 prefs.putString(C.DICT_FILE, dictFile.getPath());
452 prefs.putInt(C.INDEX_INDEX, indexIndex);
453 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
458 protected void onDestroy() {
460 if (dictRaf == null) {
464 final SearchOperation searchOperation = currentSearchOperation;
465 currentSearchOperation = null;
467 // Before we close the RAF, we have to wind the current search down.
468 if (searchOperation != null) {
469 Log.d(LOG, "Interrupting search to shut down.");
470 currentSearchOperation = null;
471 searchOperation.interrupted.set(true);
475 Log.d(LOG, "Closing RAF.");
477 } catch (IOException e) {
478 Log.e(LOG, "Failed to close dictionary", e);
483 // --------------------------------------------------------------------------
485 // --------------------------------------------------------------------------
487 private void onClearSearchTextButton() {
488 setSearchText("", true);
492 private void showKeyboard() {
493 searchText.postDelayed(new Runnable() {
496 Log.d(LOG, "Trying to show soft keyboard.");
497 final boolean searchTextHadFocus = searchText.hasFocus();
498 searchText.requestFocus();
499 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
500 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
501 if (!searchTextHadFocus) {
507 void updateLangButton() {
508 // final LanguageResources languageResources =
509 // Language.isoCodeToResources.get(index.shortName);
510 // if (languageResources != null && languageResources.flagId != 0) {
511 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
512 // languageResources.flagId, 0);
514 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
515 langButton.setText(index.shortName);
520 private void updateTTSLanuage() {
521 if (!ttsReady || index == null || textToSpeech == null) {
522 Log.d(LOG, "Can't updateTTSLanguage.");
525 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
526 Log.d(LOG, "Setting TTS locale to: " + locale);
527 final int ttsResult = textToSpeech.setLanguage(locale);
528 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
529 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
530 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
534 void onLanguageButton() {
535 if (currentSearchOperation != null) {
536 currentSearchOperation.interrupted.set(true);
537 currentSearchOperation = null;
539 changeIndexAndResearch((indexIndex + 1) % dictionary.indices.size());
542 void onLanguageButtonLongClick(final Context context) {
543 final Dialog dialog = new Dialog(context);
544 dialog.setContentView(R.layout.select_dictionary_dialog);
545 dialog.setTitle(R.string.selectDictionary);
547 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
550 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
552 // final LinearLayout.LayoutParams layoutParams = new
553 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
554 // ViewGroup.LayoutParams.WRAP_CONTENT);
555 // layoutParams.width = 0;
556 // layoutParams.weight = 1.0f;
558 final Button button = new Button(listView.getContext());
559 final String name = getString(R.string.dictionaryManager);
560 button.setText(name);
561 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
562 DictionaryManagerActivity.getLaunchIntent()) {
564 protected void onGo() {
566 DictionaryActivity.this.finish();
569 button.setOnClickListener(intentLauncher);
570 // button.setLayoutParams(layoutParams);
571 listView.addHeaderView(button);
572 // listView.setHeaderDividersEnabled(true);
574 listView.setAdapter(new BaseAdapter() {
576 public View getView(int position, View convertView, ViewGroup parent) {
577 final DictionaryInfo dictionaryInfo = getItem(position);
579 final LinearLayout result = new LinearLayout(parent.getContext());
581 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
583 final TextView dash = new TextView(parent.getContext());
585 result.addView(dash);
588 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
589 final Button button = new Button(parent.getContext());
590 button.setText(indexInfo.shortName);
591 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
593 application.getPath(dictionaryInfo.uncompressedFilename),
594 i, searchText.getText().toString())) {
596 protected void onGo() {
598 DictionaryActivity.this.finish();
601 button.setOnClickListener(intentLauncher);
602 result.addView(button);
606 final TextView nameView = new TextView(parent.getContext());
607 final String name = application
608 .getDictionaryName(dictionaryInfo.uncompressedFilename);
609 nameView.setText(name);
610 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
611 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
612 layoutParams.width = 0;
613 layoutParams.weight = 1.0f;
614 nameView.setLayoutParams(layoutParams);
615 result.addView(nameView);
621 public long getItemId(int position) {
626 public DictionaryInfo getItem(int position) {
627 return installedDicts.get(position);
631 public int getCount() {
632 return installedDicts.size();
639 private void changeIndexAndResearch(int newIndex) {
640 Log.d(LOG, "Changing index to: " + newIndex);
641 if (newIndex == -1) {
642 Log.e(LOG, "Invalid index.");
645 indexIndex = newIndex;
646 index = dictionary.indices.get(indexIndex);
647 indexAdapter = new IndexAdapter(index);
648 Log.d(LOG, "changingIndex, newLang=" + index.longName);
649 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
650 setListAdapter(indexAdapter);
652 setSearchText(searchText.getText().toString(), true);
655 void onUpDownButton(final boolean up) {
659 final int firstVisibleRow = getListView().getFirstVisiblePosition();
660 final RowBase row = index.rows.get(firstVisibleRow);
661 final TokenRow tokenRow = row.getTokenRow(true);
662 final int destIndexEntry;
664 if (row != tokenRow) {
665 destIndexEntry = tokenRow.referenceIndex;
667 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
671 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
673 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
674 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
675 setSearchText(dest.token, false);
676 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
680 // --------------------------------------------------------------------------
682 // --------------------------------------------------------------------------
684 final Random random = new Random();
687 public boolean onCreateOptionsMenu(final Menu menu) {
688 application.onCreateGlobalOptionsMenu(this, menu);
691 // final MenuItem randomWord = menu.add(getString(R.string.randomWord));
692 // randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
693 // public boolean onMenuItemClick(final MenuItem menuItem) {
694 // final String word = index.sortedIndexEntries.get(random
695 // .nextInt(index.sortedIndexEntries.size())).token;
696 // setSearchText(word, true);
703 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
704 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
705 public boolean onMenuItemClick(final MenuItem menuItem) {
706 startActivity(DictionaryManagerActivity.getLaunchIntent());
714 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
715 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
716 public boolean onMenuItemClick(final MenuItem menuItem) {
717 final Context context = getListView().getContext();
718 final Dialog dialog = new Dialog(context);
719 dialog.setContentView(R.layout.about_dictionary_dialog);
720 final TextView textView = (TextView) dialog.findViewById(R.id.text);
722 final String name = application.getDictionaryName(dictFile.getName());
723 dialog.setTitle(name);
725 final StringBuilder builder = new StringBuilder();
726 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
727 dictionaryInfo.uncompressedBytes = dictFile.length();
728 if (dictionaryInfo != null) {
729 builder.append(dictionaryInfo.dictInfo).append("\n\n");
730 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
733 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
736 getString(R.string.dictionaryCreationTime,
737 dictionaryInfo.creationMillis)).append("\n");
738 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
739 builder.append("\n");
740 builder.append(getString(R.string.indexName, indexInfo.shortName))
743 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
746 builder.append("\n");
747 builder.append(getString(R.string.sources)).append("\n");
748 for (final EntrySource source : dictionary.sources) {
750 getString(R.string.sourceInfo, source.getName(),
751 source.getNumEntries())).append("\n");
755 // builder.append(getString(R.string.invalidDictionary));
757 textView.setText(builder.toString());
760 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
761 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
762 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
763 dialog.getWindow().setAttributes(layoutParams);
772 // --------------------------------------------------------------------------
773 // Context Menu + clicks
774 // --------------------------------------------------------------------------
777 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
778 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
779 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
781 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
782 wordList.getName()));
783 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
784 public boolean onMenuItemClick(MenuItem item) {
785 onAppendToWordList(row);
790 final MenuItem share = menu.add("Share");
791 share.setOnMenuItemClickListener(new OnMenuItemClickListener() {
792 public boolean onMenuItemClick(MenuItem item) {
793 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
794 shareIntent.setType("text/plain");
795 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true).getToken());
796 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, row.getRawText(saveOnlyFirstSubentry));
797 startActivity(shareIntent);
802 final MenuItem copy = menu.add(android.R.string.copy);
803 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
804 public boolean onMenuItemClick(MenuItem item) {
810 if (selectedSpannableText != null) {
811 final String selectedText = selectedSpannableText;
812 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
813 selectedSpannableText));
814 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
815 public boolean onMenuItemClick(MenuItem item) {
816 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
822 if (row instanceof TokenRow && ttsReady) {
823 final MenuItem speak = menu.add(R.string.speak);
824 speak.setOnMenuItemClickListener(new OnMenuItemClickListener() {
826 public boolean onMenuItemClick(MenuItem item) {
827 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
828 new HashMap<String, String>());
835 private void jumpToTextFromHyperLink(final String selectedText, final int defaultIndexToUse) {
837 for (int i = 0; i < dictionary.indices.size(); ++i) {
838 final Index index = dictionary.indices.get(i);
839 if (indexPrepFinished) {
840 System.out.println("Doing index lookup: on " + selectedText);
841 final IndexEntry indexEntry = index.findExact(selectedText);
842 if (indexEntry != null) {
843 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
845 if (tokenRow != null && tokenRow.hasMainEntry) {
851 Log.w(LOG, "Skipping findExact on index " + index.shortName);
854 if (indexToUse == -1) {
855 indexToUse = defaultIndexToUse;
857 final boolean changeIndex = indexIndex != indexToUse;
859 setSearchText(selectedText, false);
860 changeIndexAndResearch(indexToUse);
862 setSearchText(selectedText, true);
867 protected void onListItemClick(ListView l, View v, int row, long id) {
869 if (clickOpensContextMenu && dictRaf != null) {
874 void onAppendToWordList(final RowBase row) {
877 final StringBuilder rawText = new StringBuilder();
878 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
879 rawText.append(index.longName).append("\t");
880 rawText.append(row.getTokenRow(true).getToken()).append("\t");
881 rawText.append(row.getRawText(saveOnlyFirstSubentry));
882 Log.d(LOG, "Writing : " + rawText);
885 wordList.getParentFile().mkdirs();
886 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
887 out.println(rawText.toString());
889 } catch (IOException e) {
890 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
892 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
893 Toast.LENGTH_LONG).show();
899 * Called when user clicks outside of search text, so that they can start
900 * typing again immediately.
902 void defocusSearchText() {
903 // Log.d(LOG, "defocusSearchText");
904 // Request focus so that if we start typing again, it clears the text
906 getListView().requestFocus();
908 // Visual indication that a new keystroke will clear the search text.
909 // Doesn't seem to work unless earchText has focus.
910 // searchText.selectAll();
913 @SuppressWarnings("deprecation")
914 void onCopy(final RowBase row) {
917 Log.d(LOG, "Copy, row=" + row);
918 final StringBuilder result = new StringBuilder();
919 result.append(row.getRawText(false));
920 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
921 clipboardManager.setText(result.toString());
922 Log.d(LOG, "Copied: " + result);
926 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
927 if (event.getUnicodeChar() != 0) {
928 if (!searchText.hasFocus()) {
929 setSearchText("" + (char) event.getUnicodeChar(), true);
933 if (keyCode == KeyEvent.KEYCODE_BACK) {
934 // Log.d(LOG, "Clearing dictionary prefs.");
935 // Pretend that we just autolaunched so that we won't do it again.
936 // DictionaryManagerActivity.lastAutoLaunchMillis =
937 // System.currentTimeMillis();
939 if (keyCode == KeyEvent.KEYCODE_ENTER) {
940 Log.d(LOG, "Trying to hide soft keyboard.");
941 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
942 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
943 InputMethodManager.HIDE_NOT_ALWAYS);
946 return super.onKeyDown(keyCode, event);
949 private void setSearchText(final String text, final boolean triggerSearch) {
950 if (!triggerSearch) {
951 getListView().requestFocus();
953 searchText.setText(text);
954 searchText.requestFocus();
957 onSearchTextChange(text);
961 private long cursorDelayMillis = 100;
963 private void moveCursorToRight() {
964 if (searchText.getLayout() != null) {
965 cursorDelayMillis = 100;
966 // Surprising, but this can crash when you rotate...
967 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
969 uiHandler.postDelayed(new Runnable() {
974 }, cursorDelayMillis);
975 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
979 // --------------------------------------------------------------------------
981 // --------------------------------------------------------------------------
983 private void searchFinished(final SearchOperation searchOperation) {
984 if (searchOperation.interrupted.get()) {
985 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
988 if (searchOperation != this.currentSearchOperation) {
989 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
993 final Index.IndexEntry searchResult = searchOperation.searchResult;
994 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
996 currentSearchOperation = null;
997 uiHandler.postDelayed(new Runnable() {
1000 if (currentSearchOperation == null) {
1001 if (searchResult != null) {
1005 jumpToRow(searchResult.startRow);
1006 } else if (searchOperation.multiWordSearchResult != null) {
1007 // Multi-row search....
1008 setFiltered(searchOperation);
1010 throw new IllegalStateException("This should never happen.");
1013 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1019 private final void jumpToRow(final int row) {
1020 final boolean refocusSearchText = searchText.hasFocus();
1021 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + refocusSearchText);
1022 getListView().requestFocusFromTouch();
1023 getListView().setSelectionFromTop(row, 0);
1024 getListView().setSelected(true);
1025 if (refocusSearchText) {
1026 searchText.requestFocus();
1028 //Log.d(LOG, "getSelectedItemPosition():" + getSelectedItemPosition());
1031 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1033 final class SearchOperation implements Runnable {
1035 final AtomicBoolean interrupted = new AtomicBoolean(false);
1037 final String searchText;
1039 List<String> searchTokens; // filled in for multiWord.
1043 long searchStartMillis;
1045 Index.IndexEntry searchResult;
1047 List<RowBase> multiWordSearchResult;
1049 boolean done = false;
1051 SearchOperation(final String searchText, final Index index) {
1052 this.searchText = StringUtil.normalizeWhitespace(searchText);
1056 public String toString() {
1057 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1063 searchStartMillis = System.currentTimeMillis();
1064 final String[] searchTokenArray = WHITESPACE.split(searchText);
1065 if (searchTokenArray.length == 1) {
1066 searchResult = index.findInsertionPoint(searchText, interrupted);
1068 searchTokens = Arrays.asList(searchTokenArray);
1069 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens, interrupted);
1072 "searchText=" + searchText + ", searchDuration="
1073 + (System.currentTimeMillis() - searchStartMillis)
1074 + ", interrupted=" + interrupted.get());
1075 if (!interrupted.get()) {
1076 uiHandler.post(new Runnable() {
1079 searchFinished(SearchOperation.this);
1083 Log.d(LOG, "interrupted, skipping searchFinished.");
1085 } catch (Exception e) {
1086 Log.e(LOG, "Failure during search (can happen during Activity close.");
1088 synchronized (this) {
1096 // --------------------------------------------------------------------------
1098 // --------------------------------------------------------------------------
1100 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1101 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1103 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1104 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1106 final class IndexAdapter extends BaseAdapter {
1108 private static final float PADDING_DEFAULT_DP = 8;
1110 private static final float PADDING_LARGE_DP = 16;
1114 final List<RowBase> rows;
1116 final Set<String> toHighlight;
1118 private int mPaddingDefault;
1120 private int mPaddingLarge;
1122 IndexAdapter(final Index index) {
1125 this.toHighlight = null;
1129 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1132 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1136 private void getMetrics() {
1137 // Get the screen's density scale
1138 final float scale = getResources().getDisplayMetrics().density;
1139 // Convert the dps to pixels, based on density scale
1140 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1141 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1145 public int getCount() {
1150 public RowBase getItem(int position) {
1151 return rows.get(position);
1155 public long getItemId(int position) {
1156 return getItem(position).index();
1160 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1161 final TableLayout result;
1162 if (convertView instanceof TableLayout) {
1163 result = (TableLayout) convertView;
1164 result.removeAllViews();
1166 result = new TableLayout(parent.getContext());
1168 final RowBase row = getItem(position);
1169 if (row instanceof PairEntry.Row) {
1170 return getView(position, (PairEntry.Row) row, parent, result);
1171 } else if (row instanceof TokenRow) {
1172 return getView((TokenRow) row, parent, result);
1173 } else if (row instanceof HtmlEntry.Row) {
1174 return getView((HtmlEntry.Row) row, parent, result);
1176 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1180 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1181 final TableLayout result) {
1182 final PairEntry entry = row.getEntry();
1183 final int rowCount = entry.pairs.size();
1185 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1186 layoutParams.weight = 0.5f;
1187 layoutParams.leftMargin = mPaddingLarge;
1189 for (int r = 0; r < rowCount; ++r) {
1190 final TableRow tableRow = new TableRow(result.getContext());
1192 final TextView col1 = new TextView(tableRow.getContext());
1193 final TextView col2 = new TextView(tableRow.getContext());
1195 // Set the columns in the table.
1197 final TextView bullet = new TextView(tableRow.getContext());
1198 bullet.setText(" • ");
1199 tableRow.addView(bullet);
1201 tableRow.addView(col1, layoutParams);
1202 final TextView margin = new TextView(tableRow.getContext());
1203 margin.setText(" ");
1204 tableRow.addView(margin);
1206 final TextView bullet = new TextView(tableRow.getContext());
1207 bullet.setText(" • ");
1208 tableRow.addView(bullet);
1210 tableRow.addView(col2, layoutParams);
1214 // Set what's in the columns.
1216 final Pair pair = entry.pairs.get(r);
1217 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1218 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1220 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1221 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1223 // Bold the token instances in col1.
1224 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1225 .singleton(row.getTokenRow(true).getToken());
1226 final Spannable col1Spannable = (Spannable) col1.getText();
1227 for (final String token : toBold) {
1229 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1230 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1231 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1232 startPos += token.length();
1236 createTokenLinkSpans(col1, col1Spannable, col1Text);
1237 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1239 col1.setTypeface(typeface);
1240 col2.setTypeface(typeface);
1241 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1242 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1243 // col2.setBackgroundResource(theme.otherLangBg);
1245 if (index.swapPairEntries) {
1246 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1247 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1249 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1250 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1253 result.addView(tableRow);
1256 // Because we have a Button inside a ListView row:
1257 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1258 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1259 result.setClickable(true);
1260 result.setFocusable(true);
1261 result.setLongClickable(true);
1262 result.setBackgroundResource(android.R.drawable.menuitem_background);
1263 result.setOnClickListener(new TextView.OnClickListener() {
1265 public void onClick(View v) {
1266 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1273 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1274 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1275 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1276 final Context context = parent.getContext();
1278 final TableRow tableRow = new TableRow(result.getContext());
1279 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1280 : theme.tokenRowOtherBg);
1282 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1284 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1286 result.addView(tableRow);
1288 // Make it so we can long-click on these token rows, too:
1289 final TextView textView = new TextView(context);
1290 textView.setText(text, BufferType.SPANNABLE);
1291 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1292 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1294 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1295 result.setLongClickable(true);
1298 // textView.setTextColor(android.R.color.secondary_text_light);
1299 textView.setTypeface(typeface);
1300 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1302 textView.setTextAppearance(context, theme.tokenRowFg);
1303 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1305 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1309 textView.setLayoutParams(lp);
1310 tableRow.addView(textView);
1312 if (!htmlEntries.isEmpty()) {
1313 final ClickableSpan clickableSpan = new ClickableSpan() {
1315 public void onClick(View widget) {
1318 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1319 result.setClickable(true);
1320 textView.setClickable(true);
1321 textView.setMovementMethod(LinkMovementMethod.getInstance());
1322 textView.setOnClickListener(new OnClickListener() {
1324 public void onClick(View v) {
1325 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1326 //Log.d(LOG, "html=" + html);
1327 startActivityForResult(
1328 HtmlDisplayActivity.getHtmlIntent(String.format(
1329 "<html><head></head><body>%s</body></html>", html),
1330 htmlTextToHighlight, false),
1338 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1339 final IndexEntry indexEntry = row.getIndexEntry();
1340 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1341 indexEntry.htmlEntries, null, parent, result);
1344 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1345 final HtmlEntry htmlEntry = row.getEntry();
1346 final TokenRow tokenRow = row.getTokenRow(true);
1347 return getPossibleLinkToHtmlEntryView(false,
1348 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1349 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1355 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1357 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1358 final String text) {
1359 // Saw from the source code that LinkMovementMethod sets the selection!
1360 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1361 textView.setMovementMethod(LinkMovementMethod.getInstance());
1362 final Matcher matcher = CHAR_DASH.matcher(text);
1363 while (matcher.find()) {
1364 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
1365 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1369 String selectedSpannableText = null;
1371 int selectedSpannableIndex = -1;
1374 public boolean onTouchEvent(MotionEvent event) {
1375 selectedSpannableText = null;
1376 selectedSpannableIndex = -1;
1377 return super.onTouchEvent(event);
1380 private class TextViewLongClickListener implements OnLongClickListener {
1383 private TextViewLongClickListener(final int index) {
1388 public boolean onLongClick(final View v) {
1389 final TextView textView = (TextView) v;
1390 final int start = textView.getSelectionStart();
1391 final int end = textView.getSelectionEnd();
1392 if (start >= 0 && end >= 0) {
1393 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1394 selectedSpannableIndex = index;
1400 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1403 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1406 // --------------------------------------------------------------------------
1408 // --------------------------------------------------------------------------
1410 void onSearchTextChange(final String text) {
1411 if ("thadolina".equals(text)) {
1412 final Dialog dialog = new Dialog(getListView().getContext());
1413 dialog.setContentView(R.layout.thadolina_dialog);
1414 dialog.setTitle("Ti amo, amore mio!");
1415 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1416 imageView.setOnClickListener(new OnClickListener() {
1418 public void onClick(View v) {
1419 final Intent intent = new Intent(Intent.ACTION_VIEW);
1420 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1421 startActivity(intent);
1426 if (dictRaf == null) {
1427 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1430 if (!searchText.isFocused()) {
1431 Log.d(LOG, "searchText changed without focus, doing nothing.");
1434 Log.d(LOG, "onSearchTextChange: " + text);
1435 if (currentSearchOperation != null) {
1436 Log.d(LOG, "Interrupting currentSearchOperation.");
1437 currentSearchOperation.interrupted.set(true);
1439 currentSearchOperation = new SearchOperation(text, index);
1440 searchExecutor.execute(currentSearchOperation);
1443 private class SearchTextWatcher implements TextWatcher {
1444 public void afterTextChanged(final Editable searchTextEditable) {
1445 if (searchText.hasFocus()) {
1446 Log.d(LOG, "SearchTextWatcher: Search text changed with focus: " + searchText.getText());
1447 // If they were typing to cause the change, update the UI.
1448 onSearchTextChange(searchText.getText().toString());
1452 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1455 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1459 // --------------------------------------------------------------------------
1460 // Filtered results.
1461 // --------------------------------------------------------------------------
1463 boolean isFiltered() {
1464 return rowsToShow != null;
1467 void setFiltered(final SearchOperation searchOperation) {
1468 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(false);
1469 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(false);
1470 rowsToShow = searchOperation.multiWordSearchResult;
1471 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1474 void clearFiltered() {
1475 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(true);
1476 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(true);
1477 setListAdapter(new IndexAdapter(index));