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.support.v4.view.MenuItemCompat;
32 import android.support.v7.app.ActionBar;
33 import android.support.v7.app.ActionBarActivity;
34 import android.support.v7.widget.SearchView;
35 import android.support.v7.widget.SearchView.OnQueryTextListener;
36 import android.text.ClipboardManager;
37 import android.text.Spannable;
38 import android.text.method.LinkMovementMethod;
39 import android.text.style.ClickableSpan;
40 import android.text.style.StyleSpan;
41 import android.util.Log;
42 import android.util.TypedValue;
43 import android.view.ContextMenu;
44 import android.view.ContextMenu.ContextMenuInfo;
45 import android.view.Gravity;
46 import android.view.KeyEvent;
47 import android.view.Menu;
48 import android.view.MenuItem;
49 import android.view.MenuItem.OnMenuItemClickListener;
50 import android.view.MotionEvent;
51 import android.view.View;
52 import android.view.View.OnClickListener;
53 import android.view.View.OnLongClickListener;
54 import android.view.ViewGroup;
55 import android.view.WindowManager;
56 import android.view.inputmethod.EditorInfo;
57 import android.view.inputmethod.InputMethodManager;
58 import android.widget.AdapterView;
59 import android.widget.AdapterView.AdapterContextMenuInfo;
60 import android.widget.AdapterView.OnItemClickListener;
61 import android.widget.BaseAdapter;
62 import android.widget.Button;
63 import android.widget.FrameLayout;
64 import android.widget.ImageButton;
65 import android.widget.ImageView;
66 import android.widget.ImageView.ScaleType;
67 import android.widget.LinearLayout;
68 import android.widget.ListAdapter;
69 import android.widget.ListView;
70 import android.widget.TableLayout;
71 import android.widget.TableRow;
72 import android.widget.TextView;
73 import android.widget.TextView.BufferType;
74 import android.widget.Toast;
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.LanguageResources;
83 import com.hughes.android.dictionary.engine.PairEntry;
84 import com.hughes.android.dictionary.engine.PairEntry.Pair;
85 import com.hughes.android.dictionary.engine.RowBase;
86 import com.hughes.android.dictionary.engine.TokenRow;
87 import com.hughes.android.dictionary.engine.TransliteratorManager;
88 import com.hughes.android.util.IntentLauncher;
89 import com.hughes.android.util.NonLinkClickableSpan;
90 import com.hughes.util.StringUtil;
93 import java.io.FileWriter;
94 import java.io.IOException;
95 import java.io.PrintWriter;
96 import java.io.RandomAccessFile;
97 import java.text.SimpleDateFormat;
98 import java.util.Arrays;
99 import java.util.Collections;
100 import java.util.Date;
101 import java.util.HashMap;
102 import java.util.LinkedHashSet;
103 import java.util.List;
104 import java.util.Locale;
105 import java.util.Random;
106 import java.util.Set;
107 import java.util.concurrent.Executor;
108 import java.util.concurrent.Executors;
109 import java.util.concurrent.ThreadFactory;
110 import java.util.concurrent.atomic.AtomicBoolean;
111 import java.util.regex.Matcher;
112 import java.util.regex.Pattern;
114 public class DictionaryActivity extends ActionBarActivity {
116 static final String LOG = "QuickDic";
118 DictionaryApplication application;
120 File dictFile = null;
121 RandomAccessFile dictRaf = null;
123 Dictionary dictionary = null;
129 List<RowBase> rowsToShow = null; // if not null, just show these rows.
131 final Handler uiHandler = new Handler();
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 TextToSpeech textToSpeech;
143 volatile boolean ttsReady;
146 DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
147 int textColorFg = Color.BLACK;
150 private ListView listView;
151 private ListView getListView() {
152 if (listView == null) {
153 listView = (ListView)findViewById(android.R.id.list);
158 private void setListAdapter(ListAdapter adapter) {
159 getListView().setAdapter(adapter);
162 private ListAdapter getListAdapter() {
163 return getListView().getAdapter();
166 SearchView searchView;
167 ImageButton languageButton;
168 SearchView.OnQueryTextListener onQueryTextListener;
170 MenuItem nextWordMenuItem, previousWordMenuItem;
173 private File wordList = null;
174 private boolean saveOnlyFirstSubentry = false;
175 private boolean clickOpensContextMenu = false;
177 // Visible for testing.
178 ListAdapter indexAdapter = null;
181 * For some languages, loading the transliterators used in this search takes
182 * a long time, so we fire it up on a different thread, and don't invoke it
183 * from the main thread until it's already finished once.
185 private volatile boolean indexPrepFinished = false;
187 public DictionaryActivity() {
190 public static Intent getLaunchIntent(final File dictFile, final String indexShortName,
191 final String searchToken) {
192 final Intent intent = new Intent();
193 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
194 DictionaryActivity.class.getName());
195 intent.putExtra(C.DICT_FILE, dictFile.getPath());
196 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
197 intent.putExtra(C.SEARCH_TOKEN, searchToken);
202 protected void onSaveInstanceState(final Bundle outState) {
203 super.onSaveInstanceState(outState);
204 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
205 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
206 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
210 protected void onRestoreInstanceState(final Bundle savedInstanceState) {
211 super.onRestoreInstanceState(savedInstanceState);
212 Log.d(LOG, "onRestoreInstanceState: " + savedInstanceState.getString(C.SEARCH_TOKEN));
213 onCreate(savedInstanceState);
217 public void onCreate(Bundle savedInstanceState) {
218 // This needs to be before super.onCreate, otherwise ActionbarSherlock
219 // doesn't makes the background of the actionbar white when you're
220 // in the dark theme.
221 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
223 Log.d(LOG, "onCreate:" + this);
224 super.onCreate(savedInstanceState);
226 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
228 // Don't auto-launch if this fails.
229 prefs.edit().remove(C.DICT_FILE).commit();
232 application = (DictionaryApplication) getApplication();
233 theme = application.getSelectedTheme();
234 textColorFg = getResources().getColor(theme.tokenRowFgColor);
236 final Intent intent = getIntent();
237 String intentAction = intent.getAction();
239 * @author Dominik Köppl Querying the Intent
240 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
241 * Arguments: SearchManager.QUERY -> the phrase to search from
242 * -> language in which the phrase is written to -> to which
243 * language shall be translated
245 if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
247 String query = intent.getStringExtra(SearchManager.QUERY);
248 String from = intent.getStringExtra("from");
250 from = from.toLowerCase(Locale.US);
251 String to = intent.getStringExtra("to");
253 to = to.toLowerCase(Locale.US);
256 getIntent().putExtra(C.SEARCH_TOKEN, query);
258 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
260 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
261 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
262 for (DictionaryInfo info : dicts)
264 boolean hasFrom = from == null;
265 boolean hasTo = to == null;
266 for (IndexInfo index : info.indexInfos)
268 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
270 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
273 if (hasFrom && hasTo)
278 for (; which_index < info.indexInfos.size(); ++which_index)
280 if (info.indexInfos.get(which_index).shortName.toLowerCase(
281 Locale.US).equals(from))
284 intent.putExtra(C.INDEX_SHORT_NAME,
285 info.indexInfos.get(which_index).shortName);
288 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
297 * @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
298 * simple query Arguments follow from android standard (see
301 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
303 String query = intent.getStringExtra(SearchManager.QUERY);
305 getIntent().putExtra(C.SEARCH_TOKEN, query);
308 * @author Dominik Köppl If no dictionary is chosen, use the default
309 * dictionary specified in the preferences If this step does
310 * fail (no default directory specified), show a toast and
313 if (intent.getStringExtra(C.DICT_FILE) == null)
315 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
316 if (dictfile != null)
317 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
319 String dictFilename = intent.getStringExtra(C.DICT_FILE);
321 if (dictFilename == null)
323 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
324 startActivity(DictionaryManagerActivity.getLaunchIntent());
328 if (dictFilename != null)
329 dictFile = new File(dictFilename);
332 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
334 public void onInit(int status) {
341 final String name = application.getDictionaryName(dictFile.getName());
342 this.setTitle("QuickDic: " + name);
343 dictRaf = new RandomAccessFile(dictFile, "r");
344 dictionary = new Dictionary(dictRaf);
345 } catch (Exception e) {
346 Log.e(LOG, "Unable to load dictionary.", e);
347 if (dictRaf != null) {
350 } catch (IOException e1) {
351 Log.e(LOG, "Unable to close dictRaf.", e1);
355 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
356 Toast.LENGTH_LONG).show();
357 startActivity(DictionaryManagerActivity.getLaunchIntent());
361 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
362 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
363 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
366 for (int i = 0; i < dictionary.indices.size(); ++i) {
367 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
372 Log.d(LOG, "Loading index " + indexIndex);
373 index = dictionary.indices.get(indexIndex);
374 setListAdapter(new IndexAdapter(index));
376 // Pre-load the collators.
377 new Thread(new Runnable() {
379 final long startMillis = System.currentTimeMillis();
381 TransliteratorManager.init(new TransliteratorManager.Callback() {
383 public void onTransliteratorReady() {
384 uiHandler.post(new Runnable() {
387 onSearchTextChange(searchView.getQuery().toString());
393 for (final Index index : dictionary.indices) {
394 final String searchToken = index.sortedIndexEntries.get(0).token;
395 final IndexEntry entry = index.findExact(searchToken);
396 if (!searchToken.equals(entry.token)) {
397 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
400 indexPrepFinished = true;
401 } catch (Exception e) {
403 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
405 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
409 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
410 if ("SYSTEM".equals(fontName)) {
411 typeface = Typeface.DEFAULT;
414 typeface = Typeface.createFromAsset(getAssets(), fontName);
415 } catch (Exception e) {
416 Log.w(LOG, "Exception trying to use typeface, using default.", e);
417 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
418 Toast.LENGTH_LONG).show();
421 if (typeface == null) {
422 Log.w(LOG, "Unable to create typeface, using default.");
423 typeface = Typeface.DEFAULT;
425 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
427 fontSizeSp = Integer.parseInt(fontSize.trim());
428 } catch (NumberFormatException e) {
432 setContentView(R.layout.dictionary_activity);
435 registerForContextMenu(getListView());
438 wordList = application.getWordListFile();
439 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
441 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
443 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
445 onCreateSetupActionBarAndSearchView();
447 // Set the search text from the intent, then the saved state.
448 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
449 if (savedInstanceState != null) {
450 text = savedInstanceState.getString(C.SEARCH_TOKEN);
455 setSearchText(text, true);
456 Log.d(LOG, "Trying to restore searchText=" + text);
458 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
461 searchView.requestFocus();
463 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
464 // getListView().setCacheColorHint(0);
467 private void onCreateSetupActionBarAndSearchView() {
468 ActionBar actionBar = getSupportActionBar();
469 actionBar.setDisplayShowTitleEnabled(false);
470 actionBar.setDisplayShowHomeEnabled(false);
471 actionBar.setDisplayHomeAsUpEnabled(false);
473 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
475 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
476 getResources().getDisplayMetrics());
477 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
478 width, ViewGroup.LayoutParams.WRAP_CONTENT);
479 customSearchView.setLayoutParams(layoutParams);
481 listView.setOnItemClickListener(new OnItemClickListener() {
483 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
484 onListItemClick(getListView(), view, row, id);
488 languageButton = new ImageButton(customSearchView.getContext());
489 languageButton.setMinimumWidth(application.languageButtonPixels);
490 languageButton.setMinimumHeight(application.languageButtonPixels * 2 / 3);
491 languageButton.setScaleType(ScaleType.FIT_CENTER);
492 languageButton.setOnClickListener(new OnClickListener() {
494 public void onClick(View arg0) {
495 onLanguageButtonClick();
498 languageButton.setOnLongClickListener(new OnLongClickListener() {
500 public boolean onLongClick(View v) {
501 onLanguageButtonLongClick(v.getContext());
505 customSearchView.addView(languageButton);
507 searchView = new SearchView(getSupportActionBar().getThemedContext());
508 searchView.setIconifiedByDefault(false);
509 // searchView.setIconified(false); // puts the magnifying glass in the
511 searchView.setQueryHint(getString(R.string.searchText));
512 searchView.setSubmitButtonEnabled(false);
513 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
514 FrameLayout.LayoutParams.WRAP_CONTENT);
516 searchView.setLayoutParams(lp);
517 searchView.setImeOptions(
518 EditorInfo.IME_ACTION_SEARCH |
519 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
520 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
521 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
523 EditorInfo.IME_MASK_ACTION |
524 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
525 onQueryTextListener = new OnQueryTextListener() {
527 public boolean onQueryTextSubmit(String query) {
528 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
533 public boolean onQueryTextChange(String newText) {
534 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
535 onSearchTextChange(searchView.getQuery().toString());
539 searchView.setOnQueryTextListener(onQueryTextListener);
540 searchView.setFocusable(true);
541 customSearchView.addView(searchView);
543 actionBar.setCustomView(customSearchView);
544 actionBar.setDisplayShowCustomEnabled(true);
548 protected void onResume() {
549 Log.d(LOG, "onResume");
551 if (PreferenceActivity.prefsMightHaveChanged) {
552 PreferenceActivity.prefsMightHaveChanged = false;
554 startActivity(getIntent());
560 protected void onPause() {
566 * Invoked when MyWebView returns, since the user might have clicked some
567 * hypertext in the MyWebView.
569 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
570 super.onActivityResult(requestCode, resultCode, result);
571 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
572 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
573 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
577 private static void setDictionaryPrefs(final Context context, final File dictFile,
578 final String indexShortName, final String searchToken) {
579 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
581 prefs.putString(C.DICT_FILE, dictFile.getPath());
582 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
583 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
588 protected void onDestroy() {
590 if (dictRaf == null) {
594 final SearchOperation searchOperation = currentSearchOperation;
595 currentSearchOperation = null;
597 // Before we close the RAF, we have to wind the current search down.
598 if (searchOperation != null) {
599 Log.d(LOG, "Interrupting search to shut down.");
600 currentSearchOperation = null;
601 searchOperation.interrupted.set(true);
605 Log.d(LOG, "Closing RAF.");
607 } catch (IOException e) {
608 Log.e(LOG, "Failed to close dictionary", e);
613 // --------------------------------------------------------------------------
615 // --------------------------------------------------------------------------
617 private void showKeyboard() {
618 // For some reason, this doesn't always work the first time.
619 // One way to replicate the problem:
620 // Press the "task switch" button repeatedly to pause and resume
621 for (int delay = 1; delay <= 101; delay += 100) {
622 searchView.postDelayed(new Runnable() {
625 Log.d(LOG, "Trying to show soft keyboard.");
626 final boolean searchTextHadFocus = searchView.hasFocus();
627 searchView.requestFocusFromTouch();
628 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
629 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
630 if (!searchTextHadFocus) {
638 void updateLangButton() {
639 final LanguageResources languageResources =
640 DictionaryApplication.isoCodeToResources.get(index.shortName);
641 if (languageResources != null && languageResources.flagId != 0) {
642 languageButton.setImageResource(languageResources.flagId);
644 if (indexIndex % 2 == 0) {
645 languageButton.setImageResource(android.R.drawable.ic_media_next);
647 languageButton.setImageResource(android.R.drawable.ic_media_previous);
653 private void updateTTSLanguage() {
654 if (!ttsReady || index == null || textToSpeech == null) {
655 Log.d(LOG, "Can't updateTTSLanguage.");
658 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
659 Log.d(LOG, "Setting TTS locale to: " + locale);
660 final int ttsResult = textToSpeech.setLanguage(locale);
661 if (ttsResult != TextToSpeech.LANG_AVAILABLE ||
662 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
663 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
667 void onLanguageButtonClick() {
668 if (dictionary.indices.size() == 1) {
669 // No need to work to switch indices.
672 if (currentSearchOperation != null) {
673 currentSearchOperation.interrupted.set(true);
674 currentSearchOperation = null;
676 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
677 searchView.getQuery().toString());
680 void onLanguageButtonLongClick(final Context context) {
681 final Dialog dialog = new Dialog(context);
682 dialog.setContentView(R.layout.select_dictionary_dialog);
683 dialog.setTitle(R.string.selectDictionary);
685 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
687 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
688 final Button button = new Button(listView.getContext());
689 final String name = getString(R.string.dictionaryManager);
690 button.setText(name);
691 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
692 DictionaryManagerActivity.getLaunchIntent()) {
694 protected void onGo() {
696 DictionaryActivity.this.finish();
699 button.setOnClickListener(intentLauncher);
700 listView.addHeaderView(button);
702 listView.setAdapter(new BaseAdapter() {
704 public View getView(int position, View convertView, ViewGroup parent) {
705 final DictionaryInfo dictionaryInfo = getItem(position);
707 final LinearLayout result = new LinearLayout(parent.getContext());
709 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
710 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
711 final View button = application.createButton(parent.getContext(),
712 dictionaryInfo, indexInfo);
713 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
715 application.getPath(dictionaryInfo.uncompressedFilename),
716 indexInfo.shortName, searchView.getQuery().toString())) {
718 protected void onGo() {
720 DictionaryActivity.this.finish();
723 button.setOnClickListener(intentLauncher);
724 result.addView(button);
727 final TextView nameView = new TextView(parent.getContext());
728 final String name = application
729 .getDictionaryName(dictionaryInfo.uncompressedFilename);
730 nameView.setText(name);
731 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
732 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
733 layoutParams.width = 0;
734 layoutParams.weight = 1.0f;
735 nameView.setLayoutParams(layoutParams);
736 nameView.setGravity(Gravity.CENTER_VERTICAL);
737 result.addView(nameView);
742 public long getItemId(int position) {
747 public DictionaryInfo getItem(int position) {
748 return installedDicts.get(position);
752 public int getCount() {
753 return installedDicts.size();
759 void onUpDownButton(final boolean up) {
763 final int firstVisibleRow = getListView().getFirstVisiblePosition();
764 final RowBase row = index.rows.get(firstVisibleRow);
765 final TokenRow tokenRow = row.getTokenRow(true);
766 final int destIndexEntry;
768 if (row != tokenRow) {
769 destIndexEntry = tokenRow.referenceIndex;
771 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
775 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
777 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
778 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
779 setSearchText(dest.token, false);
780 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
784 // --------------------------------------------------------------------------
786 // --------------------------------------------------------------------------
788 final Random random = new Random();
791 public boolean onCreateOptionsMenu(final Menu menu) {
793 if (PreferenceManager.getDefaultSharedPreferences(this)
794 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
796 nextWordMenuItem = menu.add(getString(R.string.nextWord))
797 .setIcon(R.drawable.arrow_down_float);
798 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
799 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
801 public boolean onMenuItemClick(MenuItem item) {
802 onUpDownButton(false);
808 previousWordMenuItem = menu.add(getString(R.string.previousWord))
809 .setIcon(R.drawable.arrow_up_float);
810 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
811 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
813 public boolean onMenuItemClick(MenuItem item) {
814 onUpDownButton(true);
820 application.onCreateGlobalOptionsMenu(this, menu);
823 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
824 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
825 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
826 public boolean onMenuItemClick(final MenuItem menuItem) {
827 startActivity(DictionaryManagerActivity.getLaunchIntent());
835 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
836 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
837 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
838 public boolean onMenuItemClick(final MenuItem menuItem) {
839 final Context context = getListView().getContext();
840 final Dialog dialog = new Dialog(context);
841 dialog.setContentView(R.layout.about_dictionary_dialog);
842 final TextView textView = (TextView) dialog.findViewById(R.id.text);
844 final String name = application.getDictionaryName(dictFile.getName());
845 dialog.setTitle(name);
847 final StringBuilder builder = new StringBuilder();
848 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
849 dictionaryInfo.uncompressedBytes = dictFile.length();
850 if (dictionaryInfo != null) {
851 builder.append(dictionaryInfo.dictInfo).append("\n\n");
852 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
855 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
858 getString(R.string.dictionaryCreationTime,
859 dictionaryInfo.creationMillis)).append("\n");
860 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
861 builder.append("\n");
862 builder.append(getString(R.string.indexName, indexInfo.shortName))
865 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
868 builder.append("\n");
869 builder.append(getString(R.string.sources)).append("\n");
870 for (final EntrySource source : dictionary.sources) {
872 getString(R.string.sourceInfo, source.getName(),
873 source.getNumEntries())).append("\n");
876 textView.setText(builder.toString());
879 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
880 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
881 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
882 dialog.getWindow().setAttributes(layoutParams);
891 // --------------------------------------------------------------------------
892 // Context Menu + clicks
893 // --------------------------------------------------------------------------
896 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
897 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
898 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
900 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
901 wordList.getName()));
903 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
904 public boolean onMenuItemClick(android.view.MenuItem item) {
905 onAppendToWordList(row);
910 final android.view.MenuItem share = menu.add("Share");
911 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
912 public boolean onMenuItemClick(android.view.MenuItem item) {
913 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
914 shareIntent.setType("text/plain");
915 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
917 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
918 row.getRawText(saveOnlyFirstSubentry));
919 startActivity(shareIntent);
924 final android.view.MenuItem copy = menu.add(android.R.string.copy);
925 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
926 public boolean onMenuItemClick(android.view.MenuItem item) {
932 if (selectedSpannableText != null) {
933 final String selectedText = selectedSpannableText;
934 final android.view.MenuItem searchForSelection = menu.add(getString(
935 R.string.searchForSelection,
936 selectedSpannableText));
938 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
939 public boolean onMenuItemClick(android.view.MenuItem item) {
940 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
944 // Rats, this won't be shown:
945 //searchForSelection.setIcon(R.drawable.abs__ic_search);
948 if (row instanceof TokenRow && ttsReady) {
949 final android.view.MenuItem speak = menu.add(R.string.speak);
950 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
952 public boolean onMenuItemClick(android.view.MenuItem item) {
953 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
954 new HashMap<String, String>());
961 private void jumpToTextFromHyperLink(
962 final String selectedText, final int defaultIndexToUse) {
964 for (int i = 0; i < dictionary.indices.size(); ++i) {
965 final Index index = dictionary.indices.get(i);
966 if (indexPrepFinished) {
967 System.out.println("Doing index lookup: on " + selectedText);
968 final IndexEntry indexEntry = index.findExact(selectedText);
969 if (indexEntry != null) {
970 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
972 if (tokenRow != null && tokenRow.hasMainEntry) {
978 Log.w(LOG, "Skipping findExact on index " + index.shortName);
981 if (indexToUse == -1) {
982 indexToUse = defaultIndexToUse;
984 // Without this extra delay, the call to jumpToRow that this
985 // invokes doesn't always actually have any effect.
986 final int actualIndexToUse = indexToUse;
987 getListView().postDelayed(new Runnable() {
990 setIndexAndSearchText(actualIndexToUse, selectedText);
996 * Called when user clicks outside of search text, so that they can start
997 * typing again immediately.
999 void defocusSearchText() {
1000 // Log.d(LOG, "defocusSearchText");
1001 // Request focus so that if we start typing again, it clears the text
1003 getListView().requestFocus();
1005 // Visual indication that a new keystroke will clear the search text.
1006 // Doesn't seem to work unless earchText has focus.
1007 // searchView.selectAll();
1010 protected void onListItemClick(ListView l, View v, int row, long id) {
1011 defocusSearchText();
1012 if (clickOpensContextMenu && dictRaf != null) {
1017 @SuppressLint("SimpleDateFormat")
1018 void onAppendToWordList(final RowBase row) {
1019 defocusSearchText();
1021 final StringBuilder rawText = new StringBuilder();
1022 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1023 rawText.append(index.longName).append("\t");
1024 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1025 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1026 Log.d(LOG, "Writing : " + rawText);
1029 wordList.getParentFile().mkdirs();
1030 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1031 out.println(rawText.toString());
1033 } catch (Exception e) {
1034 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1035 Toast.makeText(this,
1036 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1037 Toast.LENGTH_LONG).show();
1042 @SuppressWarnings("deprecation")
1043 void onCopy(final RowBase row) {
1044 defocusSearchText();
1046 Log.d(LOG, "Copy, row=" + row);
1047 final StringBuilder result = new StringBuilder();
1048 result.append(row.getRawText(false));
1049 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1050 clipboardManager.setText(result.toString());
1051 Log.d(LOG, "Copied: " + result);
1055 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1056 if (event.getUnicodeChar() != 0) {
1057 if (!searchView.hasFocus()) {
1058 setSearchText("" + (char) event.getUnicodeChar(), true);
1059 searchView.requestFocus();
1063 if (keyCode == KeyEvent.KEYCODE_BACK) {
1064 // Log.d(LOG, "Clearing dictionary prefs.");
1065 // Pretend that we just autolaunched so that we won't do it again.
1066 // DictionaryManagerActivity.lastAutoLaunchMillis =
1067 // System.currentTimeMillis();
1069 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1070 Log.d(LOG, "Trying to hide soft keyboard.");
1071 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1072 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
1073 InputMethodManager.HIDE_NOT_ALWAYS);
1076 return super.onKeyDown(keyCode, event);
1079 private void setIndexAndSearchText(int newIndex, String newSearchText) {
1080 Log.d(LOG, "Changing index to: " + newIndex);
1081 if (newIndex == -1) {
1082 Log.e(LOG, "Invalid index.");
1085 if (newIndex != indexIndex) {
1086 indexIndex = newIndex;
1087 index = dictionary.indices.get(indexIndex);
1088 indexAdapter = new IndexAdapter(index);
1089 setListAdapter(indexAdapter);
1090 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1091 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1094 setSearchText(newSearchText, true);
1097 private void setSearchText(final String text, final boolean triggerSearch) {
1098 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1099 // Disable the listener, because sometimes it doesn't work.
1100 searchView.setOnQueryTextListener(null);
1101 searchView.setQuery(text, false);
1102 moveCursorToRight();
1103 searchView.setOnQueryTextListener(onQueryTextListener);
1104 if (triggerSearch) {
1105 onQueryTextListener.onQueryTextChange(text);
1109 // private long cursorDelayMillis = 100;
1110 private void moveCursorToRight() {
1111 // if (searchText.getLayout() != null) {
1112 // cursorDelayMillis = 100;
1113 // // Surprising, but this can crash when you rotate...
1114 // Selection.moveToRightEdge(searchView.getQuery(),
1115 // searchText.getLayout());
1117 // uiHandler.postDelayed(new Runnable() {
1119 // public void run() {
1120 // moveCursorToRight();
1122 // }, cursorDelayMillis);
1123 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1127 // --------------------------------------------------------------------------
1129 // --------------------------------------------------------------------------
1131 private void searchFinished(final SearchOperation searchOperation) {
1132 if (searchOperation.interrupted.get()) {
1133 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1136 if (searchOperation != this.currentSearchOperation) {
1137 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1141 final Index.IndexEntry searchResult = searchOperation.searchResult;
1142 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1144 currentSearchOperation = null;
1145 uiHandler.postDelayed(new Runnable() {
1148 if (currentSearchOperation == null) {
1149 if (searchResult != null) {
1153 jumpToRow(searchResult.startRow);
1154 } else if (searchOperation.multiWordSearchResult != null) {
1155 // Multi-row search....
1156 setFiltered(searchOperation);
1158 throw new IllegalStateException("This should never happen.");
1161 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1167 private final void jumpToRow(final int row) {
1168 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1169 // getListView().requestFocusFromTouch();
1170 getListView().setSelectionFromTop(row, 0);
1171 getListView().setSelected(true);
1174 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1176 final class SearchOperation implements Runnable {
1178 final AtomicBoolean interrupted = new AtomicBoolean(false);
1180 final String searchText;
1182 List<String> searchTokens; // filled in for multiWord.
1186 long searchStartMillis;
1188 Index.IndexEntry searchResult;
1190 List<RowBase> multiWordSearchResult;
1192 boolean done = false;
1194 SearchOperation(final String searchText, final Index index) {
1195 this.searchText = StringUtil.normalizeWhitespace(searchText);
1199 public String toString() {
1200 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1206 searchStartMillis = System.currentTimeMillis();
1207 final String[] searchTokenArray = WHITESPACE.split(searchText);
1208 if (searchTokenArray.length == 1) {
1209 searchResult = index.findInsertionPoint(searchText, interrupted);
1211 searchTokens = Arrays.asList(searchTokenArray);
1212 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1216 "searchText=" + searchText + ", searchDuration="
1217 + (System.currentTimeMillis() - searchStartMillis)
1218 + ", interrupted=" + interrupted.get());
1219 if (!interrupted.get()) {
1220 uiHandler.post(new Runnable() {
1223 searchFinished(SearchOperation.this);
1227 Log.d(LOG, "interrupted, skipping searchFinished.");
1229 } catch (Exception e) {
1230 Log.e(LOG, "Failure during search (can happen during Activity close.");
1232 synchronized (this) {
1240 // --------------------------------------------------------------------------
1242 // --------------------------------------------------------------------------
1244 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1245 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1247 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1248 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1250 final class IndexAdapter extends BaseAdapter {
1252 private static final float PADDING_DEFAULT_DP = 8;
1254 private static final float PADDING_LARGE_DP = 16;
1258 final List<RowBase> rows;
1260 final Set<String> toHighlight;
1262 private int mPaddingDefault;
1264 private int mPaddingLarge;
1266 IndexAdapter(final Index index) {
1269 this.toHighlight = null;
1273 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1276 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1280 private void getMetrics() {
1281 // Get the screen's density scale
1282 final float scale = getResources().getDisplayMetrics().density;
1283 // Convert the dps to pixels, based on density scale
1284 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1285 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1289 public int getCount() {
1294 public RowBase getItem(int position) {
1295 return rows.get(position);
1299 public long getItemId(int position) {
1300 return getItem(position).index();
1304 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1305 final TableLayout result;
1306 if (convertView instanceof TableLayout) {
1307 result = (TableLayout) convertView;
1308 result.removeAllViews();
1310 result = new TableLayout(parent.getContext());
1312 final RowBase row = getItem(position);
1313 if (row instanceof PairEntry.Row) {
1314 return getView(position, (PairEntry.Row) row, parent, result);
1315 } else if (row instanceof TokenRow) {
1316 return getView((TokenRow) row, parent, result);
1317 } else if (row instanceof HtmlEntry.Row) {
1318 return getView((HtmlEntry.Row) row, parent, result);
1320 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1324 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1325 final TableLayout result) {
1326 final PairEntry entry = row.getEntry();
1327 final int rowCount = entry.pairs.size();
1329 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1330 layoutParams.weight = 0.5f;
1331 layoutParams.leftMargin = mPaddingLarge;
1333 for (int r = 0; r < rowCount; ++r) {
1334 final TableRow tableRow = new TableRow(result.getContext());
1336 final TextView col1 = new TextView(tableRow.getContext());
1337 final TextView col2 = new TextView(tableRow.getContext());
1339 // Set the columns in the table.
1341 final TextView bullet = new TextView(tableRow.getContext());
1342 bullet.setText(" • ");
1343 tableRow.addView(bullet);
1345 tableRow.addView(col1, layoutParams);
1346 final TextView margin = new TextView(tableRow.getContext());
1347 margin.setText(" ");
1348 tableRow.addView(margin);
1350 final TextView bullet = new TextView(tableRow.getContext());
1351 bullet.setText(" • ");
1352 tableRow.addView(bullet);
1354 tableRow.addView(col2, layoutParams);
1358 // Set what's in the columns.
1360 final Pair pair = entry.pairs.get(r);
1361 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1362 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1364 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1365 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1367 // Bold the token instances in col1.
1368 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1369 .singleton(row.getTokenRow(true).getToken());
1370 final Spannable col1Spannable = (Spannable) col1.getText();
1371 for (final String token : toBold) {
1373 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1374 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1375 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1376 startPos += token.length();
1380 createTokenLinkSpans(col1, col1Spannable, col1Text);
1381 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1383 col1.setTypeface(typeface);
1384 col2.setTypeface(typeface);
1385 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1386 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1387 // col2.setBackgroundResource(theme.otherLangBg);
1389 if (index.swapPairEntries) {
1390 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1391 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1393 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1394 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1397 result.addView(tableRow);
1400 // Because we have a Button inside a ListView row:
1401 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1402 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1403 result.setClickable(true);
1404 result.setFocusable(true);
1405 result.setLongClickable(true);
1406 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1408 result.setBackgroundResource(theme.normalRowBg);
1410 result.setOnClickListener(new TextView.OnClickListener() {
1412 public void onClick(View v) {
1413 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1420 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1421 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1422 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1423 final Context context = parent.getContext();
1425 final TableRow tableRow = new TableRow(result.getContext());
1426 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1427 : theme.tokenRowOtherBg);
1429 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1431 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1433 result.addView(tableRow);
1435 // Make it so we can long-click on these token rows, too:
1436 final TextView textView = new TextView(context);
1437 textView.setText(text, BufferType.SPANNABLE);
1438 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1439 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1441 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1442 result.setLongClickable(true);
1445 // textView.setTextColor(android.R.color.secondary_text_light);
1446 textView.setTypeface(typeface);
1447 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1449 textView.setTextAppearance(context, theme.tokenRowFg);
1450 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1452 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1456 textView.setLayoutParams(lp);
1457 tableRow.addView(textView);
1459 if (!htmlEntries.isEmpty()) {
1460 final ClickableSpan clickableSpan = new ClickableSpan() {
1462 public void onClick(View widget) {
1465 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1466 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1467 result.setClickable(true);
1468 textView.setClickable(true);
1469 textView.setMovementMethod(LinkMovementMethod.getInstance());
1470 textView.setOnClickListener(new OnClickListener() {
1472 public void onClick(View v) {
1473 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1474 // Log.d(LOG, "html=" + html);
1475 startActivityForResult(
1476 HtmlDisplayActivity.getHtmlIntent(String.format(
1477 "<html><head></head><body>%s</body></html>", html),
1478 htmlTextToHighlight, false),
1486 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1487 final IndexEntry indexEntry = row.getIndexEntry();
1488 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1489 indexEntry.htmlEntries, null, parent, result);
1492 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1493 final HtmlEntry htmlEntry = row.getEntry();
1494 final TokenRow tokenRow = row.getTokenRow(true);
1495 return getPossibleLinkToHtmlEntryView(false,
1496 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1497 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1503 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1505 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1506 final String text) {
1507 // Saw from the source code that LinkMovementMethod sets the selection!
1508 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1509 textView.setMovementMethod(LinkMovementMethod.getInstance());
1510 final Matcher matcher = CHAR_DASH.matcher(text);
1511 while (matcher.find()) {
1512 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1514 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1518 String selectedSpannableText = null;
1520 int selectedSpannableIndex = -1;
1523 public boolean onTouchEvent(MotionEvent event) {
1524 selectedSpannableText = null;
1525 selectedSpannableIndex = -1;
1526 return super.onTouchEvent(event);
1529 private class TextViewLongClickListener implements OnLongClickListener {
1532 private TextViewLongClickListener(final int index) {
1537 public boolean onLongClick(final View v) {
1538 final TextView textView = (TextView) v;
1539 final int start = textView.getSelectionStart();
1540 final int end = textView.getSelectionEnd();
1541 if (start >= 0 && end >= 0) {
1542 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1543 selectedSpannableIndex = index;
1549 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1552 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1555 // --------------------------------------------------------------------------
1557 // --------------------------------------------------------------------------
1559 void onSearchTextChange(final String text) {
1560 if ("thadolina".equals(text)) {
1561 final Dialog dialog = new Dialog(getListView().getContext());
1562 dialog.setContentView(R.layout.thadolina_dialog);
1563 dialog.setTitle("Ti amo, amore mio!");
1564 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1565 imageView.setOnClickListener(new OnClickListener() {
1567 public void onClick(View v) {
1568 final Intent intent = new Intent(Intent.ACTION_VIEW);
1569 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1570 startActivity(intent);
1575 if (dictRaf == null) {
1576 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1579 // if (!searchView.hasFocus()) {
1580 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1583 Log.d(LOG, "onSearchTextChange: " + text);
1584 if (currentSearchOperation != null) {
1585 Log.d(LOG, "Interrupting currentSearchOperation.");
1586 currentSearchOperation.interrupted.set(true);
1588 currentSearchOperation = new SearchOperation(text, index);
1589 searchExecutor.execute(currentSearchOperation);
1592 // --------------------------------------------------------------------------
1593 // Filtered results.
1594 // --------------------------------------------------------------------------
1596 boolean isFiltered() {
1597 return rowsToShow != null;
1600 void setFiltered(final SearchOperation searchOperation) {
1601 if (nextWordMenuItem != null) {
1602 nextWordMenuItem.setEnabled(false);
1603 previousWordMenuItem.setEnabled(false);
1605 rowsToShow = searchOperation.multiWordSearchResult;
1606 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1609 void clearFiltered() {
1610 if (nextWordMenuItem != null) {
1611 nextWordMenuItem.setEnabled(true);
1612 previousWordMenuItem.setEnabled(true);
1614 setListAdapter(new IndexAdapter(index));