1 // Copyright 2011 Google Inc. All Rights Reserved.
2 // Some Parts Copyright 2013 Dominik Köppl
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.annotation.SuppressLint;
18 import android.app.Dialog;
19 import android.app.SearchManager;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.SharedPreferences;
23 import android.graphics.Color;
24 import android.graphics.Typeface;
25 import android.net.Uri;
26 import android.os.Bundle;
27 import android.os.Handler;
28 import android.preference.PreferenceManager;
29 import android.speech.tts.TextToSpeech;
30 import android.speech.tts.TextToSpeech.OnInitListener;
31 import android.text.ClipboardManager;
32 import android.text.Spannable;
33 import android.text.method.LinkMovementMethod;
34 import android.text.style.ClickableSpan;
35 import android.text.style.StyleSpan;
36 import android.util.Log;
37 import android.util.TypedValue;
38 import android.view.ContextMenu;
39 import android.view.ContextMenu.ContextMenuInfo;
40 import android.view.Gravity;
41 import android.view.KeyEvent;
42 import android.view.MotionEvent;
43 import android.view.View;
44 import android.view.View.OnClickListener;
45 import android.view.View.OnLongClickListener;
46 import android.view.ViewGroup;
47 import android.view.WindowManager;
48 import android.view.inputmethod.EditorInfo;
49 import android.view.inputmethod.InputMethodManager;
50 import android.widget.AdapterView;
51 import android.widget.AdapterView.AdapterContextMenuInfo;
52 import android.widget.AdapterView.OnItemClickListener;
53 import android.widget.BaseAdapter;
54 import android.widget.Button;
55 import android.widget.FrameLayout;
56 import android.widget.ImageButton;
57 import android.widget.ImageView;
58 import android.widget.ImageView.ScaleType;
59 import android.widget.LinearLayout;
60 import android.widget.ListAdapter;
61 import android.widget.ListView;
62 import android.widget.TableLayout;
63 import android.widget.TableRow;
64 import android.widget.TextView;
65 import android.widget.TextView.BufferType;
66 import android.widget.Toast;
68 import android.support.v4.view.MenuItemCompat;
69 import android.support.v7.app.ActionBar;
70 import android.support.v7.app.ActionBarActivity;
71 import android.support.v7.widget.SearchView;
72 import android.support.v7.widget.SearchView.OnQueryTextListener;
73 import android.view.Menu;
74 import android.view.MenuItem;
75 import android.view.MenuItem.OnMenuItemClickListener;
76 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
77 import com.hughes.android.dictionary.engine.Dictionary;
78 import com.hughes.android.dictionary.engine.EntrySource;
79 import com.hughes.android.dictionary.engine.HtmlEntry;
80 import com.hughes.android.dictionary.engine.Index;
81 import com.hughes.android.dictionary.engine.Index.IndexEntry;
82 import com.hughes.android.dictionary.engine.Language;
83 import com.hughes.android.dictionary.engine.Language.LanguageResources;
84 import com.hughes.android.dictionary.engine.PairEntry;
85 import com.hughes.android.dictionary.engine.PairEntry.Pair;
86 import com.hughes.android.dictionary.engine.RowBase;
87 import com.hughes.android.dictionary.engine.TokenRow;
88 import com.hughes.android.dictionary.engine.TransliteratorManager;
89 import com.hughes.android.util.IntentLauncher;
90 import com.hughes.android.util.NonLinkClickableSpan;
91 import com.hughes.util.StringUtil;
94 import java.io.FileWriter;
95 import java.io.IOException;
96 import java.io.PrintWriter;
97 import java.io.RandomAccessFile;
98 import java.text.SimpleDateFormat;
99 import java.util.Arrays;
100 import java.util.Collections;
101 import java.util.Date;
102 import java.util.HashMap;
103 import java.util.LinkedHashSet;
104 import java.util.List;
105 import java.util.Locale;
106 import java.util.Random;
107 import java.util.Set;
108 import java.util.concurrent.Executor;
109 import java.util.concurrent.Executors;
110 import java.util.concurrent.ThreadFactory;
111 import java.util.concurrent.atomic.AtomicBoolean;
112 import java.util.regex.Matcher;
113 import java.util.regex.Pattern;
115 public class DictionaryActivity extends ActionBarActivity {
117 static final String LOG = "QuickDic";
119 DictionaryApplication application;
121 File dictFile = null;
122 RandomAccessFile dictRaf = null;
124 Dictionary dictionary = null;
130 List<RowBase> rowsToShow = null; // if not null, just show these rows.
132 final Handler uiHandler = new Handler();
134 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
136 public Thread newThread(Runnable r) {
137 return new Thread(r, "searchExecutor");
141 private SearchOperation currentSearchOperation = null;
143 TextToSpeech textToSpeech;
144 volatile boolean ttsReady;
147 C.Theme theme = C.Theme.LIGHT;
148 int textColorFg = Color.BLACK;
151 private ListView listView;
152 private ListView getListView() {
153 if (listView == null) {
154 listView = (ListView)findViewById(android.R.id.list);
159 private void setListAdapter(ListAdapter adapter) {
160 getListView().setAdapter(adapter);
163 private ListAdapter getListAdapter() {
164 return getListView().getAdapter();
167 SearchView searchView;
168 ImageButton languageButton;
169 SearchView.OnQueryTextListener onQueryTextListener;
171 MenuItem nextWordMenuItem, previousWordMenuItem;
174 private File wordList = null;
175 private boolean saveOnlyFirstSubentry = false;
176 private boolean clickOpensContextMenu = false;
178 // Visible for testing.
179 ListAdapter indexAdapter = null;
182 * For some languages, loading the transliterators used in this search takes
183 * a long time, so we fire it up on a different thread, and don't invoke it
184 * from the main thread until it's already finished once.
186 private volatile boolean indexPrepFinished = false;
188 public DictionaryActivity() {
191 public static Intent getLaunchIntent(final File dictFile, final String indexShortName,
192 final String searchToken) {
193 final Intent intent = new Intent();
194 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
195 DictionaryActivity.class.getName());
196 intent.putExtra(C.DICT_FILE, dictFile.getPath());
197 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
198 intent.putExtra(C.SEARCH_TOKEN, searchToken);
203 protected void onSaveInstanceState(final Bundle outState) {
204 super.onSaveInstanceState(outState);
205 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
206 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
207 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
211 protected void onRestoreInstanceState(final Bundle savedInstanceState) {
212 super.onRestoreInstanceState(savedInstanceState);
213 Log.d(LOG, "onRestoreInstanceState: " + savedInstanceState.getString(C.SEARCH_TOKEN));
214 onCreate(savedInstanceState);
218 public void onCreate(Bundle savedInstanceState) {
219 // This needs to be before super.onCreate, otherwise ActionbarSherlock
220 // doesn't makes the background of the actionbar white when you're
221 // in the dark theme.
222 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
224 Log.d(LOG, "onCreate:" + this);
225 super.onCreate(savedInstanceState);
227 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
229 // Don't auto-launch if this fails.
230 prefs.edit().remove(C.DICT_FILE).commit();
233 application = (DictionaryApplication) getApplication();
234 theme = application.getSelectedTheme();
235 textColorFg = getResources().getColor(theme.tokenRowFgColor);
237 final Intent intent = getIntent();
238 String intentAction = intent.getAction();
240 * @author Dominik Köppl Querying the Intent
241 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
242 * Arguments: SearchManager.QUERY -> the phrase to search from
243 * -> language in which the phrase is written to -> to which
244 * language shall be translated
246 if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
248 String query = intent.getStringExtra(SearchManager.QUERY);
249 String from = intent.getStringExtra("from");
251 from = from.toLowerCase(Locale.US);
252 String to = intent.getStringExtra("to");
254 to = to.toLowerCase(Locale.US);
257 getIntent().putExtra(C.SEARCH_TOKEN, query);
259 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
261 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
262 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
263 for (DictionaryInfo info : dicts)
265 boolean hasFrom = from == null;
266 boolean hasTo = to == null;
267 for (IndexInfo index : info.indexInfos)
269 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
271 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
274 if (hasFrom && hasTo)
279 for (; which_index < info.indexInfos.size(); ++which_index)
281 if (info.indexInfos.get(which_index).shortName.toLowerCase(
282 Locale.US).equals(from))
285 intent.putExtra(C.INDEX_SHORT_NAME,
286 info.indexInfos.get(which_index).shortName);
289 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
298 * @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
299 * simple query Arguments follow from android standard (see
302 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
304 String query = intent.getStringExtra(SearchManager.QUERY);
306 getIntent().putExtra(C.SEARCH_TOKEN, query);
309 * @author Dominik Köppl If no dictionary is chosen, use the default
310 * dictionary specified in the preferences If this step does
311 * fail (no default directory specified), show a toast and
314 if (intent.getStringExtra(C.DICT_FILE) == null)
316 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
317 if (dictfile != null)
318 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
320 String dictFilename = intent.getStringExtra(C.DICT_FILE);
322 if (dictFilename == null)
324 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
325 startActivity(DictionaryManagerActivity.getLaunchIntent());
329 if (dictFilename != null)
330 dictFile = new File(dictFilename);
333 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
335 public void onInit(int status) {
342 final String name = application.getDictionaryName(dictFile.getName());
343 this.setTitle("QuickDic: " + name);
344 dictRaf = new RandomAccessFile(dictFile, "r");
345 dictionary = new Dictionary(dictRaf);
346 } catch (Exception e) {
347 Log.e(LOG, "Unable to load dictionary.", e);
348 if (dictRaf != null) {
351 } catch (IOException e1) {
352 Log.e(LOG, "Unable to close dictRaf.", e1);
356 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
357 Toast.LENGTH_LONG).show();
358 startActivity(DictionaryManagerActivity.getLaunchIntent());
362 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
363 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
364 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
367 for (int i = 0; i < dictionary.indices.size(); ++i) {
368 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
373 Log.d(LOG, "Loading index " + indexIndex);
374 index = dictionary.indices.get(indexIndex);
375 setListAdapter(new IndexAdapter(index));
377 // Pre-load the collators.
378 new Thread(new Runnable() {
380 final long startMillis = System.currentTimeMillis();
382 TransliteratorManager.init(new TransliteratorManager.Callback() {
384 public void onTransliteratorReady() {
385 uiHandler.post(new Runnable() {
388 onSearchTextChange(searchView.getQuery().toString());
394 for (final Index index : dictionary.indices) {
395 final String searchToken = index.sortedIndexEntries.get(0).token;
396 final IndexEntry entry = index.findExact(searchToken);
397 if (!searchToken.equals(entry.token)) {
398 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
401 indexPrepFinished = true;
402 } catch (Exception e) {
404 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
406 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
410 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
411 if ("SYSTEM".equals(fontName)) {
412 typeface = Typeface.DEFAULT;
415 typeface = Typeface.createFromAsset(getAssets(), fontName);
416 } catch (Exception e) {
417 Log.w(LOG, "Exception trying to use typeface, using default.", e);
418 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
419 Toast.LENGTH_LONG).show();
422 if (typeface == null) {
423 Log.w(LOG, "Unable to create typeface, using default.");
424 typeface = Typeface.DEFAULT;
426 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
428 fontSizeSp = Integer.parseInt(fontSize.trim());
429 } catch (NumberFormatException e) {
433 setContentView(R.layout.dictionary_activity);
436 registerForContextMenu(getListView());
439 wordList = application.getWordListFile();
440 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
442 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
444 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
446 onCreateSetupActionBarAndSearchView();
448 // Set the search text from the intent, then the saved state.
449 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
450 if (savedInstanceState != null) {
451 text = savedInstanceState.getString(C.SEARCH_TOKEN);
456 setSearchText(text, true);
457 Log.d(LOG, "Trying to restore searchText=" + text);
459 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
462 searchView.requestFocus();
464 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
465 // getListView().setCacheColorHint(0);
468 private void onCreateSetupActionBarAndSearchView() {
469 ActionBar actionBar = getSupportActionBar();
470 actionBar.setDisplayShowTitleEnabled(false);
471 actionBar.setDisplayShowHomeEnabled(false);
472 actionBar.setDisplayHomeAsUpEnabled(false);
474 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
476 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
477 getResources().getDisplayMetrics());
478 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
479 width, ViewGroup.LayoutParams.WRAP_CONTENT);
480 customSearchView.setLayoutParams(layoutParams);
482 listView.setOnItemClickListener(new OnItemClickListener() {
484 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
485 onListItemClick(getListView(), view, row, id);
489 languageButton = new ImageButton(customSearchView.getContext());
490 languageButton.setMinimumWidth(application.languageButtonPixels);
491 languageButton.setMinimumHeight(application.languageButtonPixels * 2 / 3);
492 languageButton.setScaleType(ScaleType.FIT_CENTER);
493 languageButton.setOnClickListener(new OnClickListener() {
495 public void onClick(View arg0) {
496 onLanguageButtonClick();
499 languageButton.setOnLongClickListener(new OnLongClickListener() {
501 public boolean onLongClick(View v) {
502 onLanguageButtonLongClick(v.getContext());
506 customSearchView.addView(languageButton);
508 searchView = new SearchView(getSupportActionBar().getThemedContext());
509 searchView.setIconifiedByDefault(false);
510 // searchView.setIconified(false); // puts the magnifying glass in the
512 searchView.setQueryHint(getString(R.string.searchText));
513 searchView.setSubmitButtonEnabled(false);
514 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
515 FrameLayout.LayoutParams.WRAP_CONTENT);
517 searchView.setLayoutParams(lp);
518 searchView.setImeOptions(
519 EditorInfo.IME_ACTION_SEARCH |
520 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
521 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
522 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
524 EditorInfo.IME_MASK_ACTION |
525 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
526 onQueryTextListener = new OnQueryTextListener() {
528 public boolean onQueryTextSubmit(String query) {
529 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
534 public boolean onQueryTextChange(String newText) {
535 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
536 onSearchTextChange(searchView.getQuery().toString());
540 searchView.setOnQueryTextListener(onQueryTextListener);
541 searchView.setFocusable(true);
542 customSearchView.addView(searchView);
544 actionBar.setCustomView(customSearchView);
545 actionBar.setDisplayShowCustomEnabled(true);
549 protected void onResume() {
550 Log.d(LOG, "onResume");
552 if (PreferenceActivity.prefsMightHaveChanged) {
553 PreferenceActivity.prefsMightHaveChanged = false;
555 startActivity(getIntent());
561 protected void onPause() {
567 * Invoked when MyWebView returns, since the user might have clicked some
568 * hypertext in the MyWebView.
570 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
571 super.onActivityResult(requestCode, resultCode, result);
572 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
573 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
574 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
578 private static void setDictionaryPrefs(final Context context, final File dictFile,
579 final String indexShortName, final String searchToken) {
580 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
582 prefs.putString(C.DICT_FILE, dictFile.getPath());
583 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
584 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
589 protected void onDestroy() {
591 if (dictRaf == null) {
595 final SearchOperation searchOperation = currentSearchOperation;
596 currentSearchOperation = null;
598 // Before we close the RAF, we have to wind the current search down.
599 if (searchOperation != null) {
600 Log.d(LOG, "Interrupting search to shut down.");
601 currentSearchOperation = null;
602 searchOperation.interrupted.set(true);
606 Log.d(LOG, "Closing RAF.");
608 } catch (IOException e) {
609 Log.e(LOG, "Failed to close dictionary", e);
614 // --------------------------------------------------------------------------
616 // --------------------------------------------------------------------------
618 private void showKeyboard() {
619 // For some reason, this doesn't always work the first time.
620 // One way to replicate the problem:
621 // Press the "task switch" button repeatedly to pause and resume
622 for (int delay = 1; delay <= 101; delay += 100) {
623 searchView.postDelayed(new Runnable() {
626 Log.d(LOG, "Trying to show soft keyboard.");
627 final boolean searchTextHadFocus = searchView.hasFocus();
628 searchView.requestFocusFromTouch();
629 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
630 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
631 if (!searchTextHadFocus) {
639 void updateLangButton() {
640 final LanguageResources languageResources =
641 DictionaryApplication.isoCodeToResources.get(index.shortName);
642 if (languageResources != null && languageResources.flagId != 0) {
643 languageButton.setImageResource(languageResources.flagId);
645 if (indexIndex % 2 == 0) {
646 languageButton.setImageResource(android.R.drawable.ic_media_next);
648 languageButton.setImageResource(android.R.drawable.ic_media_previous);
654 private void updateTTSLanguage() {
655 if (!ttsReady || index == null || textToSpeech == null) {
656 Log.d(LOG, "Can't updateTTSLanguage.");
659 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
660 Log.d(LOG, "Setting TTS locale to: " + locale);
661 final int ttsResult = textToSpeech.setLanguage(locale);
662 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
663 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
664 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
668 void onLanguageButtonClick() {
669 if (dictionary.indices.size() == 1) {
670 // No need to work to switch indices.
673 if (currentSearchOperation != null) {
674 currentSearchOperation.interrupted.set(true);
675 currentSearchOperation = null;
677 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
678 searchView.getQuery().toString());
681 void onLanguageButtonLongClick(final Context context) {
682 final Dialog dialog = new Dialog(context);
683 dialog.setContentView(R.layout.select_dictionary_dialog);
684 dialog.setTitle(R.string.selectDictionary);
686 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
688 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
689 final Button button = new Button(listView.getContext());
690 final String name = getString(R.string.dictionaryManager);
691 button.setText(name);
692 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
693 DictionaryManagerActivity.getLaunchIntent()) {
695 protected void onGo() {
697 DictionaryActivity.this.finish();
700 button.setOnClickListener(intentLauncher);
701 listView.addHeaderView(button);
703 listView.setAdapter(new BaseAdapter() {
705 public View getView(int position, View convertView, ViewGroup parent) {
706 final DictionaryInfo dictionaryInfo = getItem(position);
708 final LinearLayout result = new LinearLayout(parent.getContext());
710 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
711 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
712 final View button = application.createButton(parent.getContext(),
713 dictionaryInfo, indexInfo);
714 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
716 application.getPath(dictionaryInfo.uncompressedFilename),
717 indexInfo.shortName, searchView.getQuery().toString())) {
719 protected void onGo() {
721 DictionaryActivity.this.finish();
724 button.setOnClickListener(intentLauncher);
725 result.addView(button);
728 final TextView nameView = new TextView(parent.getContext());
729 final String name = application
730 .getDictionaryName(dictionaryInfo.uncompressedFilename);
731 nameView.setText(name);
732 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
733 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
734 layoutParams.width = 0;
735 layoutParams.weight = 1.0f;
736 nameView.setLayoutParams(layoutParams);
737 nameView.setGravity(Gravity.CENTER_VERTICAL);
738 result.addView(nameView);
743 public long getItemId(int position) {
748 public DictionaryInfo getItem(int position) {
749 return installedDicts.get(position);
753 public int getCount() {
754 return installedDicts.size();
760 void onUpDownButton(final boolean up) {
764 final int firstVisibleRow = getListView().getFirstVisiblePosition();
765 final RowBase row = index.rows.get(firstVisibleRow);
766 final TokenRow tokenRow = row.getTokenRow(true);
767 final int destIndexEntry;
769 if (row != tokenRow) {
770 destIndexEntry = tokenRow.referenceIndex;
772 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
776 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
778 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
779 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
780 setSearchText(dest.token, false);
781 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
785 // --------------------------------------------------------------------------
787 // --------------------------------------------------------------------------
789 final Random random = new Random();
792 public boolean onCreateOptionsMenu(final Menu menu) {
794 if (PreferenceManager.getDefaultSharedPreferences(this)
795 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
797 nextWordMenuItem = menu.add(getString(R.string.nextWord))
798 .setIcon(R.drawable.arrow_down_float);
799 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
800 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
802 public boolean onMenuItemClick(MenuItem item) {
803 onUpDownButton(false);
809 previousWordMenuItem = menu.add(getString(R.string.previousWord))
810 .setIcon(R.drawable.arrow_up_float);
811 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
812 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
814 public boolean onMenuItemClick(MenuItem item) {
815 onUpDownButton(true);
821 application.onCreateGlobalOptionsMenu(this, menu);
824 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
825 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
826 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
827 public boolean onMenuItemClick(final MenuItem menuItem) {
828 startActivity(DictionaryManagerActivity.getLaunchIntent());
836 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
837 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
838 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
839 public boolean onMenuItemClick(final MenuItem menuItem) {
840 final Context context = getListView().getContext();
841 final Dialog dialog = new Dialog(context);
842 dialog.setContentView(R.layout.about_dictionary_dialog);
843 final TextView textView = (TextView) dialog.findViewById(R.id.text);
845 final String name = application.getDictionaryName(dictFile.getName());
846 dialog.setTitle(name);
848 final StringBuilder builder = new StringBuilder();
849 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
850 dictionaryInfo.uncompressedBytes = dictFile.length();
851 if (dictionaryInfo != null) {
852 builder.append(dictionaryInfo.dictInfo).append("\n\n");
853 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
856 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
859 getString(R.string.dictionaryCreationTime,
860 dictionaryInfo.creationMillis)).append("\n");
861 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
862 builder.append("\n");
863 builder.append(getString(R.string.indexName, indexInfo.shortName))
866 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
869 builder.append("\n");
870 builder.append(getString(R.string.sources)).append("\n");
871 for (final EntrySource source : dictionary.sources) {
873 getString(R.string.sourceInfo, source.getName(),
874 source.getNumEntries())).append("\n");
877 textView.setText(builder.toString());
880 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
881 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
882 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
883 dialog.getWindow().setAttributes(layoutParams);
892 // --------------------------------------------------------------------------
893 // Context Menu + clicks
894 // --------------------------------------------------------------------------
897 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
898 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
899 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
901 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
902 wordList.getName()));
904 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
905 public boolean onMenuItemClick(android.view.MenuItem item) {
906 onAppendToWordList(row);
911 final android.view.MenuItem share = menu.add("Share");
912 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
913 public boolean onMenuItemClick(android.view.MenuItem item) {
914 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
915 shareIntent.setType("text/plain");
916 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
918 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
919 row.getRawText(saveOnlyFirstSubentry));
920 startActivity(shareIntent);
925 final android.view.MenuItem copy = menu.add(android.R.string.copy);
926 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
927 public boolean onMenuItemClick(android.view.MenuItem item) {
933 if (selectedSpannableText != null) {
934 final String selectedText = selectedSpannableText;
935 final android.view.MenuItem searchForSelection = menu.add(getString(
936 R.string.searchForSelection,
937 selectedSpannableText));
939 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
940 public boolean onMenuItemClick(android.view.MenuItem item) {
941 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
945 // Rats, this won't be shown:
946 //searchForSelection.setIcon(R.drawable.abs__ic_search);
949 if (row instanceof TokenRow && ttsReady) {
950 final android.view.MenuItem speak = menu.add(R.string.speak);
951 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
953 public boolean onMenuItemClick(android.view.MenuItem item) {
954 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
955 new HashMap<String, String>());
962 private void jumpToTextFromHyperLink(
963 final String selectedText, final int defaultIndexToUse) {
965 for (int i = 0; i < dictionary.indices.size(); ++i) {
966 final Index index = dictionary.indices.get(i);
967 if (indexPrepFinished) {
968 System.out.println("Doing index lookup: on " + selectedText);
969 final IndexEntry indexEntry = index.findExact(selectedText);
970 if (indexEntry != null) {
971 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
973 if (tokenRow != null && tokenRow.hasMainEntry) {
979 Log.w(LOG, "Skipping findExact on index " + index.shortName);
982 if (indexToUse == -1) {
983 indexToUse = defaultIndexToUse;
985 // Without this extra delay, the call to jumpToRow that this
986 // invokes doesn't always actually have any effect.
987 final int actualIndexToUse = indexToUse;
988 getListView().postDelayed(new Runnable() {
991 setIndexAndSearchText(actualIndexToUse, selectedText);
997 * Called when user clicks outside of search text, so that they can start
998 * typing again immediately.
1000 void defocusSearchText() {
1001 // Log.d(LOG, "defocusSearchText");
1002 // Request focus so that if we start typing again, it clears the text
1004 getListView().requestFocus();
1006 // Visual indication that a new keystroke will clear the search text.
1007 // Doesn't seem to work unless earchText has focus.
1008 // searchView.selectAll();
1011 protected void onListItemClick(ListView l, View v, int row, long id) {
1012 defocusSearchText();
1013 if (clickOpensContextMenu && dictRaf != null) {
1018 @SuppressLint("SimpleDateFormat")
1019 void onAppendToWordList(final RowBase row) {
1020 defocusSearchText();
1022 final StringBuilder rawText = new StringBuilder();
1023 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1024 rawText.append(index.longName).append("\t");
1025 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1026 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1027 Log.d(LOG, "Writing : " + rawText);
1030 wordList.getParentFile().mkdirs();
1031 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1032 out.println(rawText.toString());
1034 } catch (Exception e) {
1035 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1036 Toast.makeText(this,
1037 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1038 Toast.LENGTH_LONG).show();
1043 @SuppressWarnings("deprecation")
1044 void onCopy(final RowBase row) {
1045 defocusSearchText();
1047 Log.d(LOG, "Copy, row=" + row);
1048 final StringBuilder result = new StringBuilder();
1049 result.append(row.getRawText(false));
1050 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1051 clipboardManager.setText(result.toString());
1052 Log.d(LOG, "Copied: " + result);
1056 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1057 if (event.getUnicodeChar() != 0) {
1058 if (!searchView.hasFocus()) {
1059 setSearchText("" + (char) event.getUnicodeChar(), true);
1060 searchView.requestFocus();
1064 if (keyCode == KeyEvent.KEYCODE_BACK) {
1065 // Log.d(LOG, "Clearing dictionary prefs.");
1066 // Pretend that we just autolaunched so that we won't do it again.
1067 // DictionaryManagerActivity.lastAutoLaunchMillis =
1068 // System.currentTimeMillis();
1070 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1071 Log.d(LOG, "Trying to hide soft keyboard.");
1072 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1073 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
1074 InputMethodManager.HIDE_NOT_ALWAYS);
1077 return super.onKeyDown(keyCode, event);
1080 private void setIndexAndSearchText(int newIndex, String newSearchText) {
1081 Log.d(LOG, "Changing index to: " + newIndex);
1082 if (newIndex == -1) {
1083 Log.e(LOG, "Invalid index.");
1086 if (newIndex != indexIndex) {
1087 indexIndex = newIndex;
1088 index = dictionary.indices.get(indexIndex);
1089 indexAdapter = new IndexAdapter(index);
1090 setListAdapter(indexAdapter);
1091 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1092 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1095 setSearchText(newSearchText, true);
1098 private void setSearchText(final String text, final boolean triggerSearch) {
1099 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1100 // Disable the listener, because sometimes it doesn't work.
1101 searchView.setOnQueryTextListener(null);
1102 searchView.setQuery(text, false);
1103 moveCursorToRight();
1104 searchView.setOnQueryTextListener(onQueryTextListener);
1105 if (triggerSearch) {
1106 onQueryTextListener.onQueryTextChange(text);
1110 // private long cursorDelayMillis = 100;
1111 private void moveCursorToRight() {
1112 // if (searchText.getLayout() != null) {
1113 // cursorDelayMillis = 100;
1114 // // Surprising, but this can crash when you rotate...
1115 // Selection.moveToRightEdge(searchView.getQuery(),
1116 // searchText.getLayout());
1118 // uiHandler.postDelayed(new Runnable() {
1120 // public void run() {
1121 // moveCursorToRight();
1123 // }, cursorDelayMillis);
1124 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1128 // --------------------------------------------------------------------------
1130 // --------------------------------------------------------------------------
1132 private void searchFinished(final SearchOperation searchOperation) {
1133 if (searchOperation.interrupted.get()) {
1134 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1137 if (searchOperation != this.currentSearchOperation) {
1138 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1142 final Index.IndexEntry searchResult = searchOperation.searchResult;
1143 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1145 currentSearchOperation = null;
1146 uiHandler.postDelayed(new Runnable() {
1149 if (currentSearchOperation == null) {
1150 if (searchResult != null) {
1154 jumpToRow(searchResult.startRow);
1155 } else if (searchOperation.multiWordSearchResult != null) {
1156 // Multi-row search....
1157 setFiltered(searchOperation);
1159 throw new IllegalStateException("This should never happen.");
1162 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1168 private final void jumpToRow(final int row) {
1169 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1170 // getListView().requestFocusFromTouch();
1171 getListView().setSelectionFromTop(row, 0);
1172 getListView().setSelected(true);
1175 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1177 final class SearchOperation implements Runnable {
1179 final AtomicBoolean interrupted = new AtomicBoolean(false);
1181 final String searchText;
1183 List<String> searchTokens; // filled in for multiWord.
1187 long searchStartMillis;
1189 Index.IndexEntry searchResult;
1191 List<RowBase> multiWordSearchResult;
1193 boolean done = false;
1195 SearchOperation(final String searchText, final Index index) {
1196 this.searchText = StringUtil.normalizeWhitespace(searchText);
1200 public String toString() {
1201 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1207 searchStartMillis = System.currentTimeMillis();
1208 final String[] searchTokenArray = WHITESPACE.split(searchText);
1209 if (searchTokenArray.length == 1) {
1210 searchResult = index.findInsertionPoint(searchText, interrupted);
1212 searchTokens = Arrays.asList(searchTokenArray);
1213 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1217 "searchText=" + searchText + ", searchDuration="
1218 + (System.currentTimeMillis() - searchStartMillis)
1219 + ", interrupted=" + interrupted.get());
1220 if (!interrupted.get()) {
1221 uiHandler.post(new Runnable() {
1224 searchFinished(SearchOperation.this);
1228 Log.d(LOG, "interrupted, skipping searchFinished.");
1230 } catch (Exception e) {
1231 Log.e(LOG, "Failure during search (can happen during Activity close.");
1233 synchronized (this) {
1241 // --------------------------------------------------------------------------
1243 // --------------------------------------------------------------------------
1245 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1246 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1248 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1249 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1251 final class IndexAdapter extends BaseAdapter {
1253 private static final float PADDING_DEFAULT_DP = 8;
1255 private static final float PADDING_LARGE_DP = 16;
1259 final List<RowBase> rows;
1261 final Set<String> toHighlight;
1263 private int mPaddingDefault;
1265 private int mPaddingLarge;
1267 IndexAdapter(final Index index) {
1270 this.toHighlight = null;
1274 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1277 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1281 private void getMetrics() {
1282 // Get the screen's density scale
1283 final float scale = getResources().getDisplayMetrics().density;
1284 // Convert the dps to pixels, based on density scale
1285 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1286 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1290 public int getCount() {
1295 public RowBase getItem(int position) {
1296 return rows.get(position);
1300 public long getItemId(int position) {
1301 return getItem(position).index();
1305 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1306 final TableLayout result;
1307 if (convertView instanceof TableLayout) {
1308 result = (TableLayout) convertView;
1309 result.removeAllViews();
1311 result = new TableLayout(parent.getContext());
1313 final RowBase row = getItem(position);
1314 if (row instanceof PairEntry.Row) {
1315 return getView(position, (PairEntry.Row) row, parent, result);
1316 } else if (row instanceof TokenRow) {
1317 return getView((TokenRow) row, parent, result);
1318 } else if (row instanceof HtmlEntry.Row) {
1319 return getView((HtmlEntry.Row) row, parent, result);
1321 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1325 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1326 final TableLayout result) {
1327 final PairEntry entry = row.getEntry();
1328 final int rowCount = entry.pairs.size();
1330 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1331 layoutParams.weight = 0.5f;
1332 layoutParams.leftMargin = mPaddingLarge;
1334 for (int r = 0; r < rowCount; ++r) {
1335 final TableRow tableRow = new TableRow(result.getContext());
1337 final TextView col1 = new TextView(tableRow.getContext());
1338 final TextView col2 = new TextView(tableRow.getContext());
1340 // Set the columns in the table.
1342 final TextView bullet = new TextView(tableRow.getContext());
1343 bullet.setText(" • ");
1344 tableRow.addView(bullet);
1346 tableRow.addView(col1, layoutParams);
1347 final TextView margin = new TextView(tableRow.getContext());
1348 margin.setText(" ");
1349 tableRow.addView(margin);
1351 final TextView bullet = new TextView(tableRow.getContext());
1352 bullet.setText(" • ");
1353 tableRow.addView(bullet);
1355 tableRow.addView(col2, layoutParams);
1359 // Set what's in the columns.
1361 final Pair pair = entry.pairs.get(r);
1362 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1363 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1365 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1366 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1368 // Bold the token instances in col1.
1369 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1370 .singleton(row.getTokenRow(true).getToken());
1371 final Spannable col1Spannable = (Spannable) col1.getText();
1372 for (final String token : toBold) {
1374 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1375 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1376 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1377 startPos += token.length();
1381 createTokenLinkSpans(col1, col1Spannable, col1Text);
1382 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1384 col1.setTypeface(typeface);
1385 col2.setTypeface(typeface);
1386 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1387 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1388 // col2.setBackgroundResource(theme.otherLangBg);
1390 if (index.swapPairEntries) {
1391 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1392 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1394 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1395 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1398 result.addView(tableRow);
1401 // Because we have a Button inside a ListView row:
1402 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1403 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1404 result.setClickable(true);
1405 result.setFocusable(true);
1406 result.setLongClickable(true);
1407 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1409 result.setBackgroundResource(theme.normalRowBg);
1411 result.setOnClickListener(new TextView.OnClickListener() {
1413 public void onClick(View v) {
1414 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1421 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1422 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1423 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1424 final Context context = parent.getContext();
1426 final TableRow tableRow = new TableRow(result.getContext());
1427 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1428 : theme.tokenRowOtherBg);
1430 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1432 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1434 result.addView(tableRow);
1436 // Make it so we can long-click on these token rows, too:
1437 final TextView textView = new TextView(context);
1438 textView.setText(text, BufferType.SPANNABLE);
1439 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1440 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1442 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1443 result.setLongClickable(true);
1446 // textView.setTextColor(android.R.color.secondary_text_light);
1447 textView.setTypeface(typeface);
1448 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1450 textView.setTextAppearance(context, theme.tokenRowFg);
1451 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1453 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1457 textView.setLayoutParams(lp);
1458 tableRow.addView(textView);
1460 if (!htmlEntries.isEmpty()) {
1461 final ClickableSpan clickableSpan = new ClickableSpan() {
1463 public void onClick(View widget) {
1466 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1467 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1468 result.setClickable(true);
1469 textView.setClickable(true);
1470 textView.setMovementMethod(LinkMovementMethod.getInstance());
1471 textView.setOnClickListener(new OnClickListener() {
1473 public void onClick(View v) {
1474 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1475 // Log.d(LOG, "html=" + html);
1476 startActivityForResult(
1477 HtmlDisplayActivity.getHtmlIntent(String.format(
1478 "<html><head></head><body>%s</body></html>", html),
1479 htmlTextToHighlight, false),
1487 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1488 final IndexEntry indexEntry = row.getIndexEntry();
1489 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1490 indexEntry.htmlEntries, null, parent, result);
1493 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1494 final HtmlEntry htmlEntry = row.getEntry();
1495 final TokenRow tokenRow = row.getTokenRow(true);
1496 return getPossibleLinkToHtmlEntryView(false,
1497 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1498 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1504 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1506 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1507 final String text) {
1508 // Saw from the source code that LinkMovementMethod sets the selection!
1509 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1510 textView.setMovementMethod(LinkMovementMethod.getInstance());
1511 final Matcher matcher = CHAR_DASH.matcher(text);
1512 while (matcher.find()) {
1513 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1515 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1519 String selectedSpannableText = null;
1521 int selectedSpannableIndex = -1;
1524 public boolean onTouchEvent(MotionEvent event) {
1525 selectedSpannableText = null;
1526 selectedSpannableIndex = -1;
1527 return super.onTouchEvent(event);
1530 private class TextViewLongClickListener implements OnLongClickListener {
1533 private TextViewLongClickListener(final int index) {
1538 public boolean onLongClick(final View v) {
1539 final TextView textView = (TextView) v;
1540 final int start = textView.getSelectionStart();
1541 final int end = textView.getSelectionEnd();
1542 if (start >= 0 && end >= 0) {
1543 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1544 selectedSpannableIndex = index;
1550 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1553 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1556 // --------------------------------------------------------------------------
1558 // --------------------------------------------------------------------------
1560 void onSearchTextChange(final String text) {
1561 if ("thadolina".equals(text)) {
1562 final Dialog dialog = new Dialog(getListView().getContext());
1563 dialog.setContentView(R.layout.thadolina_dialog);
1564 dialog.setTitle("Ti amo, amore mio!");
1565 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1566 imageView.setOnClickListener(new OnClickListener() {
1568 public void onClick(View v) {
1569 final Intent intent = new Intent(Intent.ACTION_VIEW);
1570 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1571 startActivity(intent);
1576 if (dictRaf == null) {
1577 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1580 // if (!searchView.hasFocus()) {
1581 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1584 Log.d(LOG, "onSearchTextChange: " + text);
1585 if (currentSearchOperation != null) {
1586 Log.d(LOG, "Interrupting currentSearchOperation.");
1587 currentSearchOperation.interrupted.set(true);
1589 currentSearchOperation = new SearchOperation(text, index);
1590 searchExecutor.execute(currentSearchOperation);
1593 // --------------------------------------------------------------------------
1594 // Filtered results.
1595 // --------------------------------------------------------------------------
1597 boolean isFiltered() {
1598 return rowsToShow != null;
1601 void setFiltered(final SearchOperation searchOperation) {
1602 if (nextWordMenuItem != null) {
1603 nextWordMenuItem.setEnabled(false);
1604 previousWordMenuItem.setEnabled(false);
1606 rowsToShow = searchOperation.multiWordSearchResult;
1607 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1610 void clearFiltered() {
1611 if (nextWordMenuItem != null) {
1612 nextWordMenuItem.setEnabled(true);
1613 previousWordMenuItem.setEnabled(true);
1615 setListAdapter(new IndexAdapter(index));