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 (PreferenceActivity.prefsMightHaveChanged) {
426 PreferenceActivity.prefsMightHaveChanged = 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 copy = menu.add(android.R.string.copy);
791 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
792 public boolean onMenuItemClick(MenuItem item) {
798 if (selectedSpannableText != null) {
799 final String selectedText = selectedSpannableText;
800 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
801 selectedSpannableText));
802 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
803 public boolean onMenuItemClick(MenuItem item) {
804 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
810 if (row instanceof TokenRow && ttsReady) {
811 final MenuItem speak = menu.add(R.string.speak);
812 speak.setOnMenuItemClickListener(new OnMenuItemClickListener() {
814 public boolean onMenuItemClick(MenuItem item) {
815 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
816 new HashMap<String, String>());
823 private void jumpToTextFromHyperLink(final String selectedText, final int defaultIndexToUse) {
825 for (int i = 0; i < dictionary.indices.size(); ++i) {
826 final Index index = dictionary.indices.get(i);
827 if (indexPrepFinished) {
828 System.out.println("Doing index lookup: on " + selectedText);
829 final IndexEntry indexEntry = index.findExact(selectedText);
830 if (indexEntry != null) {
831 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
833 if (tokenRow != null && tokenRow.hasMainEntry) {
839 Log.w(LOG, "Skipping findExact on index " + index.shortName);
842 if (indexToUse == -1) {
843 indexToUse = defaultIndexToUse;
845 final boolean changeIndex = indexIndex != indexToUse;
847 setSearchText(selectedText, false);
848 changeIndexAndResearch(indexToUse);
850 setSearchText(selectedText, true);
855 protected void onListItemClick(ListView l, View v, int row, long id) {
857 if (clickOpensContextMenu && dictRaf != null) {
862 void onAppendToWordList(final RowBase row) {
865 final StringBuilder rawText = new StringBuilder();
866 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
867 rawText.append(index.longName).append("\t");
868 rawText.append(row.getTokenRow(true).getToken()).append("\t");
869 rawText.append(row.getRawText(saveOnlyFirstSubentry));
870 Log.d(LOG, "Writing : " + rawText);
873 wordList.getParentFile().mkdirs();
874 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
875 out.println(rawText.toString());
877 } catch (IOException e) {
878 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
880 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
881 Toast.LENGTH_LONG).show();
887 * Called when user clicks outside of search text, so that they can start
888 * typing again immediately.
890 void defocusSearchText() {
891 // Log.d(LOG, "defocusSearchText");
892 // Request focus so that if we start typing again, it clears the text
894 getListView().requestFocus();
896 // Visual indication that a new keystroke will clear the search text.
897 // Doesn't seem to work unless earchText has focus.
898 // searchText.selectAll();
901 @SuppressWarnings("deprecation")
902 void onCopy(final RowBase row) {
905 Log.d(LOG, "Copy, row=" + row);
906 final StringBuilder result = new StringBuilder();
907 result.append(row.getRawText(false));
908 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
909 clipboardManager.setText(result.toString());
910 Log.d(LOG, "Copied: " + result);
914 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
915 if (event.getUnicodeChar() != 0) {
916 if (!searchText.hasFocus()) {
917 setSearchText("" + (char) event.getUnicodeChar(), true);
921 if (keyCode == KeyEvent.KEYCODE_BACK) {
922 // Log.d(LOG, "Clearing dictionary prefs.");
923 // Pretend that we just autolaunched so that we won't do it again.
924 // DictionaryManagerActivity.lastAutoLaunchMillis =
925 // System.currentTimeMillis();
927 if (keyCode == KeyEvent.KEYCODE_ENTER) {
928 Log.d(LOG, "Trying to hide soft keyboard.");
929 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
930 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
931 InputMethodManager.HIDE_NOT_ALWAYS);
934 return super.onKeyDown(keyCode, event);
937 private void setSearchText(final String text, final boolean triggerSearch) {
938 if (!triggerSearch) {
939 getListView().requestFocus();
941 searchText.setText(text);
942 searchText.requestFocus();
945 onSearchTextChange(text);
949 private long cursorDelayMillis = 100;
951 private void moveCursorToRight() {
952 if (searchText.getLayout() != null) {
953 cursorDelayMillis = 100;
954 // Surprising, but this can crash when you rotate...
955 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
957 uiHandler.postDelayed(new Runnable() {
962 }, cursorDelayMillis);
963 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
967 // --------------------------------------------------------------------------
969 // --------------------------------------------------------------------------
971 private void searchFinished(final SearchOperation searchOperation) {
972 if (searchOperation.interrupted.get()) {
973 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
976 if (searchOperation != this.currentSearchOperation) {
977 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
981 final Index.IndexEntry searchResult = searchOperation.searchResult;
982 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
984 currentSearchOperation = null;
985 uiHandler.postDelayed(new Runnable() {
988 if (currentSearchOperation == null) {
989 if (searchResult != null) {
993 jumpToRow(searchResult.startRow);
994 } else if (searchOperation.multiWordSearchResult != null) {
995 // Multi-row search....
996 setFiltered(searchOperation);
998 throw new IllegalStateException("This should never happen.");
1001 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1007 private final void jumpToRow(final int row) {
1008 final boolean refocusSearchText = searchText.hasFocus();
1009 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + refocusSearchText);
1010 getListView().requestFocusFromTouch();
1011 getListView().setSelectionFromTop(row, 0);
1012 getListView().setSelected(true);
1013 if (refocusSearchText) {
1014 searchText.requestFocus();
1016 //Log.d(LOG, "getSelectedItemPosition():" + getSelectedItemPosition());
1019 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1021 final class SearchOperation implements Runnable {
1023 final AtomicBoolean interrupted = new AtomicBoolean(false);
1025 final String searchText;
1027 List<String> searchTokens; // filled in for multiWord.
1031 long searchStartMillis;
1033 Index.IndexEntry searchResult;
1035 List<RowBase> multiWordSearchResult;
1037 boolean done = false;
1039 SearchOperation(final String searchText, final Index index) {
1040 this.searchText = StringUtil.normalizeWhitespace(searchText);
1044 public String toString() {
1045 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1051 searchStartMillis = System.currentTimeMillis();
1052 final String[] searchTokenArray = WHITESPACE.split(searchText);
1053 if (searchTokenArray.length == 1) {
1054 searchResult = index.findInsertionPoint(searchText, interrupted);
1056 searchTokens = Arrays.asList(searchTokenArray);
1057 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens, interrupted);
1060 "searchText=" + searchText + ", searchDuration="
1061 + (System.currentTimeMillis() - searchStartMillis)
1062 + ", interrupted=" + interrupted.get());
1063 if (!interrupted.get()) {
1064 uiHandler.post(new Runnable() {
1067 searchFinished(SearchOperation.this);
1071 Log.d(LOG, "interrupted, skipping searchFinished.");
1073 } catch (Exception e) {
1074 Log.e(LOG, "Failure during search (can happen during Activity close.");
1076 synchronized (this) {
1084 // --------------------------------------------------------------------------
1086 // --------------------------------------------------------------------------
1088 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1089 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1091 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1092 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1094 final class IndexAdapter extends BaseAdapter {
1096 private static final float PADDING_DEFAULT_DP = 8;
1098 private static final float PADDING_LARGE_DP = 16;
1102 final List<RowBase> rows;
1104 final Set<String> toHighlight;
1106 private int mPaddingDefault;
1108 private int mPaddingLarge;
1110 IndexAdapter(final Index index) {
1113 this.toHighlight = null;
1117 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1120 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1124 private void getMetrics() {
1125 // Get the screen's density scale
1126 final float scale = getResources().getDisplayMetrics().density;
1127 // Convert the dps to pixels, based on density scale
1128 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1129 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1133 public int getCount() {
1138 public RowBase getItem(int position) {
1139 return rows.get(position);
1143 public long getItemId(int position) {
1144 return getItem(position).index();
1148 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1149 final TableLayout result;
1150 if (convertView instanceof TableLayout) {
1151 result = (TableLayout) convertView;
1152 result.removeAllViews();
1154 result = new TableLayout(parent.getContext());
1156 final RowBase row = getItem(position);
1157 if (row instanceof PairEntry.Row) {
1158 return getView(position, (PairEntry.Row) row, parent, result);
1159 } else if (row instanceof TokenRow) {
1160 return getView((TokenRow) row, parent, result);
1161 } else if (row instanceof HtmlEntry.Row) {
1162 return getView((HtmlEntry.Row) row, parent, result);
1164 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1168 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1169 final TableLayout result) {
1170 final PairEntry entry = row.getEntry();
1171 final int rowCount = entry.pairs.size();
1173 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1174 layoutParams.weight = 0.5f;
1175 layoutParams.leftMargin = mPaddingLarge;
1177 for (int r = 0; r < rowCount; ++r) {
1178 final TableRow tableRow = new TableRow(result.getContext());
1180 final TextView col1 = new TextView(tableRow.getContext());
1181 final TextView col2 = new TextView(tableRow.getContext());
1183 // Set the columns in the table.
1185 final TextView bullet = new TextView(tableRow.getContext());
1186 bullet.setText(" • ");
1187 tableRow.addView(bullet);
1189 tableRow.addView(col1, layoutParams);
1190 final TextView margin = new TextView(tableRow.getContext());
1191 margin.setText(" ");
1192 tableRow.addView(margin);
1194 final TextView bullet = new TextView(tableRow.getContext());
1195 bullet.setText(" • ");
1196 tableRow.addView(bullet);
1198 tableRow.addView(col2, layoutParams);
1202 // Set what's in the columns.
1204 final Pair pair = entry.pairs.get(r);
1205 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1206 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1208 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1209 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1211 // Bold the token instances in col1.
1212 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1213 .singleton(row.getTokenRow(true).getToken());
1214 final Spannable col1Spannable = (Spannable) col1.getText();
1215 for (final String token : toBold) {
1217 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1218 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1219 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1220 startPos += token.length();
1224 createTokenLinkSpans(col1, col1Spannable, col1Text);
1225 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1227 col1.setTypeface(typeface);
1228 col2.setTypeface(typeface);
1229 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1230 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1231 // col2.setBackgroundResource(theme.otherLangBg);
1233 if (index.swapPairEntries) {
1234 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1235 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1237 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1238 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1241 result.addView(tableRow);
1244 // Because we have a Button inside a ListView row:
1245 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1246 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1247 result.setClickable(true);
1248 result.setFocusable(true);
1249 result.setLongClickable(true);
1250 result.setBackgroundResource(android.R.drawable.menuitem_background);
1251 result.setOnClickListener(new TextView.OnClickListener() {
1253 public void onClick(View v) {
1254 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1261 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1262 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1263 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1264 final Context context = parent.getContext();
1266 final TableRow tableRow = new TableRow(result.getContext());
1267 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1268 : theme.tokenRowOtherBg);
1270 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1272 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1274 result.addView(tableRow);
1276 // Make it so we can long-click on these token rows, too:
1277 final TextView textView = new TextView(context);
1278 textView.setText(text, BufferType.SPANNABLE);
1279 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1280 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1282 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1283 result.setLongClickable(true);
1286 // textView.setTextColor(android.R.color.secondary_text_light);
1287 textView.setTypeface(typeface);
1288 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1290 textView.setTextAppearance(context, theme.tokenRowFg);
1291 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1293 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1297 textView.setLayoutParams(lp);
1298 tableRow.addView(textView);
1300 if (!htmlEntries.isEmpty()) {
1301 final ClickableSpan clickableSpan = new ClickableSpan() {
1303 public void onClick(View widget) {
1306 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1307 result.setClickable(true);
1308 textView.setClickable(true);
1309 textView.setMovementMethod(LinkMovementMethod.getInstance());
1310 textView.setOnClickListener(new OnClickListener() {
1312 public void onClick(View v) {
1313 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1314 //Log.d(LOG, "html=" + html);
1315 startActivityForResult(
1316 HtmlDisplayActivity.getHtmlIntent(String.format(
1317 "<html><head></head><body>%s</body></html>", html),
1318 htmlTextToHighlight, false),
1326 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1327 final IndexEntry indexEntry = row.getIndexEntry();
1328 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1329 indexEntry.htmlEntries, null, parent, result);
1332 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1333 final HtmlEntry htmlEntry = row.getEntry();
1334 final TokenRow tokenRow = row.getTokenRow(true);
1335 return getPossibleLinkToHtmlEntryView(false,
1336 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1337 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1343 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1345 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1346 final String text) {
1347 // Saw from the source code that LinkMovementMethod sets the selection!
1348 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1349 textView.setMovementMethod(LinkMovementMethod.getInstance());
1350 final Matcher matcher = CHAR_DASH.matcher(text);
1351 while (matcher.find()) {
1352 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
1353 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1357 String selectedSpannableText = null;
1359 int selectedSpannableIndex = -1;
1362 public boolean onTouchEvent(MotionEvent event) {
1363 selectedSpannableText = null;
1364 selectedSpannableIndex = -1;
1365 return super.onTouchEvent(event);
1368 private class TextViewLongClickListener implements OnLongClickListener {
1371 private TextViewLongClickListener(final int index) {
1376 public boolean onLongClick(final View v) {
1377 final TextView textView = (TextView) v;
1378 final int start = textView.getSelectionStart();
1379 final int end = textView.getSelectionEnd();
1380 if (start >= 0 && end >= 0) {
1381 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1382 selectedSpannableIndex = index;
1388 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1391 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1394 // --------------------------------------------------------------------------
1396 // --------------------------------------------------------------------------
1398 void onSearchTextChange(final String text) {
1399 if ("thadolina".equals(text)) {
1400 final Dialog dialog = new Dialog(getListView().getContext());
1401 dialog.setContentView(R.layout.thadolina_dialog);
1402 dialog.setTitle("Ti amo, amore mio!");
1403 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1404 imageView.setOnClickListener(new OnClickListener() {
1406 public void onClick(View v) {
1407 final Intent intent = new Intent(Intent.ACTION_VIEW);
1408 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1409 startActivity(intent);
1414 if (dictRaf == null) {
1415 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1418 if (!searchText.isFocused()) {
1419 Log.d(LOG, "searchText changed without focus, doing nothing.");
1422 Log.d(LOG, "onSearchTextChange: " + text);
1423 if (currentSearchOperation != null) {
1424 Log.d(LOG, "Interrupting currentSearchOperation.");
1425 currentSearchOperation.interrupted.set(true);
1427 currentSearchOperation = new SearchOperation(text, index);
1428 searchExecutor.execute(currentSearchOperation);
1431 private class SearchTextWatcher implements TextWatcher {
1432 public void afterTextChanged(final Editable searchTextEditable) {
1433 if (searchText.hasFocus()) {
1434 Log.d(LOG, "SearchTextWatcher: Search text changed with focus: " + searchText.getText());
1435 // If they were typing to cause the change, update the UI.
1436 onSearchTextChange(searchText.getText().toString());
1440 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1443 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1447 // --------------------------------------------------------------------------
1448 // Filtered results.
1449 // --------------------------------------------------------------------------
1451 boolean isFiltered() {
1452 return rowsToShow != null;
1455 void setFiltered(final SearchOperation searchOperation) {
1456 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(false);
1457 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(false);
1458 rowsToShow = searchOperation.multiWordSearchResult;
1459 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1462 void clearFiltered() {
1463 ((ImageButton) findViewById(R.id.UpButton)).setEnabled(true);
1464 ((ImageButton) findViewById(R.id.DownButton)).setEnabled(true);
1465 setListAdapter(new IndexAdapter(index));