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.support.v7.widget.Toolbar;
37 import android.text.ClipboardManager;
38 import android.text.Spannable;
39 import android.text.method.LinkMovementMethod;
40 import android.text.style.ClickableSpan;
41 import android.text.style.StyleSpan;
42 import android.util.Log;
43 import android.util.TypedValue;
44 import android.view.ContextMenu;
45 import android.view.ContextMenu.ContextMenuInfo;
46 import android.view.Gravity;
47 import android.view.KeyEvent;
48 import android.view.Menu;
49 import android.view.MenuItem;
50 import android.view.MenuItem.OnMenuItemClickListener;
51 import android.view.MotionEvent;
52 import android.view.View;
53 import android.view.View.OnClickListener;
54 import android.view.View.OnLongClickListener;
55 import android.view.ViewGroup;
56 import android.view.WindowManager;
57 import android.view.inputmethod.EditorInfo;
58 import android.view.inputmethod.InputMethodManager;
59 import android.widget.AdapterView;
60 import android.widget.AdapterView.AdapterContextMenuInfo;
61 import android.widget.AdapterView.OnItemClickListener;
62 import android.widget.BaseAdapter;
63 import android.widget.Button;
64 import android.widget.FrameLayout;
65 import android.widget.ImageButton;
66 import android.widget.ImageView;
67 import android.widget.ImageView.ScaleType;
68 import android.widget.LinearLayout;
69 import android.widget.ListAdapter;
70 import android.widget.ListView;
71 import android.widget.TableLayout;
72 import android.widget.TableRow;
73 import android.widget.TextView;
74 import android.widget.TextView.BufferType;
75 import android.widget.Toast;
77 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
78 import com.hughes.android.dictionary.engine.Dictionary;
79 import com.hughes.android.dictionary.engine.EntrySource;
80 import com.hughes.android.dictionary.engine.HtmlEntry;
81 import com.hughes.android.dictionary.engine.Index;
82 import com.hughes.android.dictionary.engine.Index.IndexEntry;
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 Random rand = new Random();
134 final Handler uiHandler = new Handler();
136 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
138 public Thread newThread(Runnable r) {
139 return new Thread(r, "searchExecutor");
143 private SearchOperation currentSearchOperation = null;
145 TextToSpeech textToSpeech;
146 volatile boolean ttsReady;
149 DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
150 int textColorFg = Color.BLACK;
153 private ListView listView;
154 private ListView getListView() {
155 if (listView == null) {
156 listView = (ListView)findViewById(android.R.id.list);
161 private void setListAdapter(ListAdapter adapter) {
162 getListView().setAdapter(adapter);
165 private ListAdapter getListAdapter() {
166 return getListView().getAdapter();
169 SearchView searchView;
170 ImageButton languageButton;
171 SearchView.OnQueryTextListener onQueryTextListener;
173 MenuItem nextWordMenuItem, previousWordMenuItem, randomWordMenuItem;
176 private File wordList = null;
177 private boolean saveOnlyFirstSubentry = false;
178 private boolean clickOpensContextMenu = false;
180 // Visible for testing.
181 ListAdapter indexAdapter = null;
184 * For some languages, loading the transliterators used in this search takes
185 * a long time, so we fire it up on a different thread, and don't invoke it
186 * from the main thread until it's already finished once.
188 private volatile boolean indexPrepFinished = false;
190 public DictionaryActivity() {
193 public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
194 final String searchToken) {
195 final Intent intent = new Intent(c, DictionaryActivity.class);
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 public void onCreate(Bundle savedInstanceState) {
212 // This needs to be before super.onCreate, otherwise ActionbarSherlock
213 // doesn't makes the background of the actionbar white when you're
214 // in the dark theme.
215 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
217 Log.d(LOG, "onCreate:" + this);
218 super.onCreate(savedInstanceState);
220 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
222 // Don't auto-launch if this fails.
223 prefs.edit().remove(C.DICT_FILE).commit();
225 setContentView(R.layout.dictionary_activity);
227 application = (DictionaryApplication) getApplication();
228 theme = application.getSelectedTheme();
229 textColorFg = getResources().getColor(theme.tokenRowFgColor);
231 final Intent intent = getIntent();
232 String intentAction = intent.getAction();
234 * @author Dominik Köppl Querying the Intent
235 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
236 * Arguments: SearchManager.QUERY -> the phrase to search from
237 * -> language in which the phrase is written to -> to which
238 * language shall be translated
240 if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
242 String query = intent.getStringExtra(SearchManager.QUERY);
243 String from = intent.getStringExtra("from");
245 from = from.toLowerCase(Locale.US);
246 String to = intent.getStringExtra("to");
248 to = to.toLowerCase(Locale.US);
251 getIntent().putExtra(C.SEARCH_TOKEN, query);
253 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
255 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
256 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
257 for (DictionaryInfo info : dicts)
259 boolean hasFrom = from == null;
260 boolean hasTo = to == null;
261 for (IndexInfo index : info.indexInfos)
263 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
265 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
268 if (hasFrom && hasTo)
273 for (; which_index < info.indexInfos.size(); ++which_index)
275 if (info.indexInfos.get(which_index).shortName.toLowerCase(
276 Locale.US).equals(from))
279 intent.putExtra(C.INDEX_SHORT_NAME,
280 info.indexInfos.get(which_index).shortName);
283 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
292 * @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
293 * simple query Arguments follow from android standard (see
296 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
298 String query = intent.getStringExtra(SearchManager.QUERY);
300 getIntent().putExtra(C.SEARCH_TOKEN, query);
303 * @author Dominik Köppl If no dictionary is chosen, use the default
304 * dictionary specified in the preferences If this step does
305 * fail (no default directory specified), show a toast and
308 if (intent.getStringExtra(C.DICT_FILE) == null)
310 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
311 if (dictfile != null)
312 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
314 String dictFilename = intent.getStringExtra(C.DICT_FILE);
316 if (dictFilename == null)
318 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
319 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
323 if (dictFilename != null)
324 dictFile = new File(dictFilename);
327 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
329 public void onInit(int status) {
336 final String name = application.getDictionaryName(dictFile.getName());
337 this.setTitle("QuickDic: " + name);
338 dictRaf = new RandomAccessFile(dictFile, "r");
339 dictionary = new Dictionary(dictRaf);
340 } catch (Exception e) {
341 Log.e(LOG, "Unable to load dictionary.", e);
342 if (dictRaf != null) {
345 } catch (IOException e1) {
346 Log.e(LOG, "Unable to close dictRaf.", e1);
350 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
351 Toast.LENGTH_LONG).show();
352 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
356 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
357 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
358 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
361 for (int i = 0; i < dictionary.indices.size(); ++i) {
362 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
367 Log.d(LOG, "Loading index " + indexIndex);
368 index = dictionary.indices.get(indexIndex);
369 setListAdapter(new IndexAdapter(index));
371 // Pre-load the collators.
372 new Thread(new Runnable() {
374 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
375 final long startMillis = System.currentTimeMillis();
377 TransliteratorManager.init(new TransliteratorManager.Callback() {
379 public void onTransliteratorReady() {
380 uiHandler.post(new Runnable() {
383 onSearchTextChange(searchView.getQuery().toString());
389 for (final Index index : dictionary.indices) {
390 final String searchToken = index.sortedIndexEntries.get(0).token;
391 final IndexEntry entry = index.findExact(searchToken);
392 if (!searchToken.equals(entry.token)) {
393 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
396 indexPrepFinished = true;
397 } catch (Exception e) {
399 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
401 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
405 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
406 if ("SYSTEM".equals(fontName)) {
407 typeface = Typeface.DEFAULT;
408 } else if ("SERIF".equals(fontName)) {
409 typeface = Typeface.SERIF;
410 } else if ("SANS_SERIF".equals(fontName)) {
411 typeface = Typeface.SANS_SERIF;
412 } else if ("MONOSPACE".equals(fontName)) {
413 typeface = Typeface.MONOSPACE;
415 if ("FreeSerif.ttf.jpg".equals(fontName)) {
416 fontName = "FreeSerif.otf.jpg";
419 typeface = Typeface.createFromAsset(getAssets(), fontName);
420 } catch (Exception e) {
421 Log.w(LOG, "Exception trying to use typeface, using default.", e);
422 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
423 Toast.LENGTH_LONG).show();
426 if (typeface == null) {
427 Log.w(LOG, "Unable to create typeface, using default.");
428 typeface = Typeface.DEFAULT;
430 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
432 fontSizeSp = Integer.parseInt(fontSize.trim());
433 } catch (NumberFormatException e) {
438 registerForContextMenu(getListView());
441 wordList = application.getWordListFile();
442 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
444 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
446 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
448 onCreateSetupActionBarAndSearchView();
450 // Set the search text from the intent, then the saved state.
451 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
452 if (savedInstanceState != null) {
453 text = savedInstanceState.getString(C.SEARCH_TOKEN);
458 setSearchText(text, true);
459 Log.d(LOG, "Trying to restore searchText=" + text);
461 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
464 searchView.requestFocus();
466 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
467 // getListView().setCacheColorHint(0);
470 private void onCreateSetupActionBarAndSearchView() {
471 ActionBar actionBar = getSupportActionBar();
472 actionBar.setDisplayShowTitleEnabled(false);
473 actionBar.setDisplayShowHomeEnabled(false);
474 actionBar.setDisplayHomeAsUpEnabled(false);
476 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
478 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
479 ViewGroup.LayoutParams.WRAP_CONTENT, 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.setScaleType(ScaleType.FIT_CENTER);
491 languageButton.setOnClickListener(new OnClickListener() {
493 public void onClick(View arg0) {
494 onLanguageButtonClick();
497 languageButton.setOnLongClickListener(new OnLongClickListener() {
499 public boolean onLongClick(View v) {
500 onLanguageButtonLongClick(v.getContext());
504 languageButton.setAdjustViewBounds(true);
505 LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
506 customSearchView.addView(languageButton, lpb);
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 searchView.setImeOptions(
515 EditorInfo.IME_ACTION_DONE |
516 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
517 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
519 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
520 onQueryTextListener = new OnQueryTextListener() {
522 public boolean onQueryTextSubmit(String query) {
523 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
529 public boolean onQueryTextChange(String newText) {
530 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
531 onSearchTextChange(searchView.getQuery().toString());
535 searchView.setOnQueryTextListener(onQueryTextListener);
536 searchView.setFocusable(true);
537 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
538 FrameLayout.LayoutParams.WRAP_CONTENT, 1);
539 customSearchView.addView(searchView, lp);
541 actionBar.setCustomView(customSearchView);
542 actionBar.setDisplayShowCustomEnabled(true);
544 // Avoid wasting space on large left inset
545 Toolbar tb = (Toolbar)customSearchView.getParent();
546 tb.setContentInsetsRelative(0, 0);
550 protected void onResume() {
551 Log.d(LOG, "onResume");
553 if (PreferenceActivity.prefsMightHaveChanged) {
554 PreferenceActivity.prefsMightHaveChanged = false;
556 startActivity(getIntent());
562 protected void onPause() {
568 * Invoked when MyWebView returns, since the user might have clicked some
569 * hypertext in the MyWebView.
571 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
572 super.onActivityResult(requestCode, resultCode, result);
573 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
574 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
575 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
579 private static void setDictionaryPrefs(final Context context, final File dictFile,
580 final String indexShortName, final String searchToken) {
581 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
583 prefs.putString(C.DICT_FILE, dictFile.getPath());
584 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
585 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
590 protected void onDestroy() {
592 if (dictRaf == null) {
596 final SearchOperation searchOperation = currentSearchOperation;
597 currentSearchOperation = null;
599 // Before we close the RAF, we have to wind the current search down.
600 if (searchOperation != null) {
601 Log.d(LOG, "Interrupting search to shut down.");
602 currentSearchOperation = null;
603 searchOperation.interrupted.set(true);
607 Log.d(LOG, "Closing RAF.");
609 } catch (IOException e) {
610 Log.e(LOG, "Failed to close dictionary", e);
615 // --------------------------------------------------------------------------
617 // --------------------------------------------------------------------------
619 private void showKeyboard() {
620 // For some reason, this doesn't always work the first time.
621 // One way to replicate the problem:
622 // Press the "task switch" button repeatedly to pause and resume
623 for (int delay = 1; delay <= 101; delay += 100) {
624 searchView.postDelayed(new Runnable() {
627 Log.d(LOG, "Trying to show soft keyboard.");
628 final boolean searchTextHadFocus = searchView.hasFocus();
629 searchView.requestFocusFromTouch();
630 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
631 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
632 if (!searchTextHadFocus) {
640 private void hideKeyboard() {
641 Log.d(LOG, "Hide soft keyboard.");
642 searchView.clearFocus();
643 InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
644 manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
647 void updateLangButton() {
648 final LanguageResources languageResources =
649 DictionaryApplication.isoCodeToResources.get(index.shortName);
650 if (languageResources != null && languageResources.flagId != 0) {
651 languageButton.setImageResource(languageResources.flagId);
653 if (indexIndex % 2 == 0) {
654 languageButton.setImageResource(android.R.drawable.ic_media_next);
656 languageButton.setImageResource(android.R.drawable.ic_media_previous);
662 private void updateTTSLanguage() {
663 if (!ttsReady || index == null || textToSpeech == null) {
664 Log.d(LOG, "Can't updateTTSLanguage.");
667 final Locale locale = new Locale(index.sortLanguage.getIsoCode());
668 Log.d(LOG, "Setting TTS locale to: " + locale);
669 final int ttsResult = textToSpeech.setLanguage(locale);
670 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
671 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
672 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
676 void onLanguageButtonClick() {
677 if (dictionary.indices.size() == 1) {
678 // No need to work to switch indices.
681 if (currentSearchOperation != null) {
682 currentSearchOperation.interrupted.set(true);
683 currentSearchOperation = null;
685 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
686 searchView.getQuery().toString());
689 void onLanguageButtonLongClick(final Context context) {
690 final Dialog dialog = new Dialog(context);
691 dialog.setContentView(R.layout.select_dictionary_dialog);
692 dialog.setTitle(R.string.selectDictionary);
694 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
696 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
697 final Button button = new Button(listView.getContext());
698 final String name = getString(R.string.dictionaryManager);
699 button.setText(name);
700 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
701 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
703 protected void onGo() {
705 DictionaryActivity.this.finish();
708 button.setOnClickListener(intentLauncher);
709 listView.addHeaderView(button);
711 listView.setAdapter(new BaseAdapter() {
713 public View getView(int position, View convertView, ViewGroup parent) {
714 final DictionaryInfo dictionaryInfo = getItem(position);
716 final LinearLayout result = new LinearLayout(parent.getContext());
718 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
719 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
720 final View button = application.createButton(parent.getContext(),
721 dictionaryInfo, indexInfo);
722 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
723 getLaunchIntent(getApplicationContext(),
724 application.getPath(dictionaryInfo.uncompressedFilename),
725 indexInfo.shortName, searchView.getQuery().toString())) {
727 protected void onGo() {
729 DictionaryActivity.this.finish();
732 button.setOnClickListener(intentLauncher);
733 result.addView(button);
736 final TextView nameView = new TextView(parent.getContext());
737 final String name = application
738 .getDictionaryName(dictionaryInfo.uncompressedFilename);
739 nameView.setText(name);
740 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
741 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
742 layoutParams.width = 0;
743 layoutParams.weight = 1.0f;
744 nameView.setLayoutParams(layoutParams);
745 nameView.setGravity(Gravity.CENTER_VERTICAL);
746 result.addView(nameView);
751 public long getItemId(int position) {
756 public DictionaryInfo getItem(int position) {
757 return installedDicts.get(position);
761 public int getCount() {
762 return installedDicts.size();
768 void onUpDownButton(final boolean up) {
772 final int firstVisibleRow = getListView().getFirstVisiblePosition();
773 final RowBase row = index.rows.get(firstVisibleRow);
774 final TokenRow tokenRow = row.getTokenRow(true);
775 final int destIndexEntry;
777 if (row != tokenRow) {
778 destIndexEntry = tokenRow.referenceIndex;
780 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
784 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
786 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
787 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
788 setSearchText(dest.token, false);
789 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
793 void onRandomWordButton() {
794 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
795 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
796 setSearchText(dest.token, false);
797 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
801 // --------------------------------------------------------------------------
803 // --------------------------------------------------------------------------
805 final Random random = new Random();
808 public boolean onCreateOptionsMenu(final Menu menu) {
810 if (PreferenceManager.getDefaultSharedPreferences(this)
811 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
813 nextWordMenuItem = menu.add(getString(R.string.nextWord))
814 .setIcon(R.drawable.arrow_down_float);
815 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
816 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
818 public boolean onMenuItemClick(MenuItem item) {
819 onUpDownButton(false);
825 previousWordMenuItem = menu.add(getString(R.string.previousWord))
826 .setIcon(R.drawable.arrow_up_float);
827 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
828 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
830 public boolean onMenuItemClick(MenuItem item) {
831 onUpDownButton(true);
837 randomWordMenuItem = menu.add(getString(R.string.randomWord));
838 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
840 public boolean onMenuItemClick(MenuItem item) {
841 onRandomWordButton();
846 application.onCreateGlobalOptionsMenu(this, menu);
849 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
850 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
851 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
852 public boolean onMenuItemClick(final MenuItem menuItem) {
853 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
861 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
862 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
863 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
864 public boolean onMenuItemClick(final MenuItem menuItem) {
865 final Context context = getListView().getContext();
866 final Dialog dialog = new Dialog(context);
867 dialog.setContentView(R.layout.about_dictionary_dialog);
868 final TextView textView = (TextView) dialog.findViewById(R.id.text);
870 final String name = application.getDictionaryName(dictFile.getName());
871 dialog.setTitle(name);
873 final StringBuilder builder = new StringBuilder();
874 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
875 dictionaryInfo.uncompressedBytes = dictFile.length();
876 if (dictionaryInfo != null) {
877 builder.append(dictionaryInfo.dictInfo).append("\n\n");
878 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
881 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
884 getString(R.string.dictionaryCreationTime,
885 dictionaryInfo.creationMillis)).append("\n");
886 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
887 builder.append("\n");
888 builder.append(getString(R.string.indexName, indexInfo.shortName))
891 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
894 builder.append("\n");
895 builder.append(getString(R.string.sources)).append("\n");
896 for (final EntrySource source : dictionary.sources) {
898 getString(R.string.sourceInfo, source.getName(),
899 source.getNumEntries())).append("\n");
902 textView.setText(builder.toString());
905 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
906 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
907 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
908 dialog.getWindow().setAttributes(layoutParams);
917 // --------------------------------------------------------------------------
918 // Context Menu + clicks
919 // --------------------------------------------------------------------------
922 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
923 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
924 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
926 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
927 wordList.getName()));
929 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
930 public boolean onMenuItemClick(android.view.MenuItem item) {
931 onAppendToWordList(row);
936 final android.view.MenuItem share = menu.add("Share");
937 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
938 public boolean onMenuItemClick(android.view.MenuItem item) {
939 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
940 shareIntent.setType("text/plain");
941 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
943 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
944 row.getRawText(saveOnlyFirstSubentry));
945 startActivity(shareIntent);
950 final android.view.MenuItem copy = menu.add(android.R.string.copy);
951 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
952 public boolean onMenuItemClick(android.view.MenuItem item) {
958 if (selectedSpannableText != null) {
959 final String selectedText = selectedSpannableText;
960 final android.view.MenuItem searchForSelection = menu.add(getString(
961 R.string.searchForSelection,
962 selectedSpannableText));
964 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
965 public boolean onMenuItemClick(android.view.MenuItem item) {
966 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
970 // Rats, this won't be shown:
971 //searchForSelection.setIcon(R.drawable.abs__ic_search);
974 if (row instanceof TokenRow && ttsReady) {
975 final android.view.MenuItem speak = menu.add(R.string.speak);
976 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
978 public boolean onMenuItemClick(android.view.MenuItem item) {
979 textToSpeech.speak(((TokenRow) row).getToken(), TextToSpeech.QUEUE_FLUSH,
980 new HashMap<String, String>());
987 private void jumpToTextFromHyperLink(
988 final String selectedText, final int defaultIndexToUse) {
990 for (int i = 0; i < dictionary.indices.size(); ++i) {
991 final Index index = dictionary.indices.get(i);
992 if (indexPrepFinished) {
993 System.out.println("Doing index lookup: on " + selectedText);
994 final IndexEntry indexEntry = index.findExact(selectedText);
995 if (indexEntry != null) {
996 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
998 if (tokenRow != null && tokenRow.hasMainEntry) {
1004 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1007 if (indexToUse == -1) {
1008 indexToUse = defaultIndexToUse;
1010 // Without this extra delay, the call to jumpToRow that this
1011 // invokes doesn't always actually have any effect.
1012 final int actualIndexToUse = indexToUse;
1013 getListView().postDelayed(new Runnable() {
1016 setIndexAndSearchText(actualIndexToUse, selectedText);
1022 * Called when user clicks outside of search text, so that they can start
1023 * typing again immediately.
1025 void defocusSearchText() {
1026 // Log.d(LOG, "defocusSearchText");
1027 // Request focus so that if we start typing again, it clears the text
1029 getListView().requestFocus();
1031 // Visual indication that a new keystroke will clear the search text.
1032 // Doesn't seem to work unless searchText has focus.
1033 // searchView.selectAll();
1036 protected void onListItemClick(ListView l, View v, int row, long id) {
1037 defocusSearchText();
1038 if (clickOpensContextMenu && dictRaf != null) {
1043 @SuppressLint("SimpleDateFormat")
1044 void onAppendToWordList(final RowBase row) {
1045 defocusSearchText();
1047 final StringBuilder rawText = new StringBuilder();
1048 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1049 rawText.append(index.longName).append("\t");
1050 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1051 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1052 Log.d(LOG, "Writing : " + rawText);
1055 wordList.getParentFile().mkdirs();
1056 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1057 out.println(rawText.toString());
1059 } catch (Exception e) {
1060 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1061 Toast.makeText(this,
1062 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1063 Toast.LENGTH_LONG).show();
1068 @SuppressWarnings("deprecation")
1069 void onCopy(final RowBase row) {
1070 defocusSearchText();
1072 Log.d(LOG, "Copy, row=" + row);
1073 final StringBuilder result = new StringBuilder();
1074 result.append(row.getRawText(false));
1075 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1076 clipboardManager.setText(result.toString());
1077 Log.d(LOG, "Copied: " + result);
1081 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1082 if (event.getUnicodeChar() != 0) {
1083 if (!searchView.hasFocus()) {
1084 setSearchText("" + (char) event.getUnicodeChar(), true);
1085 searchView.requestFocus();
1089 if (keyCode == KeyEvent.KEYCODE_BACK) {
1090 // Log.d(LOG, "Clearing dictionary prefs.");
1091 // Pretend that we just autolaunched so that we won't do it again.
1092 // DictionaryManagerActivity.lastAutoLaunchMillis =
1093 // System.currentTimeMillis();
1095 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1096 Log.d(LOG, "Trying to hide soft keyboard.");
1097 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1098 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
1099 InputMethodManager.HIDE_NOT_ALWAYS);
1102 return super.onKeyDown(keyCode, event);
1105 private void setIndexAndSearchText(int newIndex, String newSearchText) {
1106 Log.d(LOG, "Changing index to: " + newIndex);
1107 if (newIndex == -1) {
1108 Log.e(LOG, "Invalid index.");
1111 if (newIndex != indexIndex) {
1112 indexIndex = newIndex;
1113 index = dictionary.indices.get(indexIndex);
1114 indexAdapter = new IndexAdapter(index);
1115 setListAdapter(indexAdapter);
1116 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1117 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1120 setSearchText(newSearchText, true);
1123 private void setSearchText(final String text, final boolean triggerSearch) {
1124 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1125 // Disable the listener, because sometimes it doesn't work.
1126 searchView.setOnQueryTextListener(null);
1127 searchView.setQuery(text, false);
1128 moveCursorToRight();
1129 searchView.setOnQueryTextListener(onQueryTextListener);
1131 // Hide search icon once text is entered
1132 searchView.setIconifiedByDefault(text.length() > 0);
1133 searchView.setIconified(false);
1135 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1138 if (triggerSearch) {
1139 onQueryTextListener.onQueryTextChange(text);
1143 // private long cursorDelayMillis = 100;
1144 private void moveCursorToRight() {
1145 // if (searchText.getLayout() != null) {
1146 // cursorDelayMillis = 100;
1147 // // Surprising, but this can crash when you rotate...
1148 // Selection.moveToRightEdge(searchView.getQuery(),
1149 // searchText.getLayout());
1151 // uiHandler.postDelayed(new Runnable() {
1153 // public void run() {
1154 // moveCursorToRight();
1156 // }, cursorDelayMillis);
1157 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1161 // --------------------------------------------------------------------------
1163 // --------------------------------------------------------------------------
1165 private void searchFinished(final SearchOperation searchOperation) {
1166 if (searchOperation.interrupted.get()) {
1167 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1170 if (searchOperation != this.currentSearchOperation) {
1171 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1175 final Index.IndexEntry searchResult = searchOperation.searchResult;
1176 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1178 currentSearchOperation = null;
1179 uiHandler.postDelayed(new Runnable() {
1182 if (currentSearchOperation == null) {
1183 if (searchResult != null) {
1187 jumpToRow(searchResult.startRow);
1188 } else if (searchOperation.multiWordSearchResult != null) {
1189 // Multi-row search....
1190 setFiltered(searchOperation);
1192 throw new IllegalStateException("This should never happen.");
1195 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1201 private final void jumpToRow(final int row) {
1202 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1203 // getListView().requestFocusFromTouch();
1204 getListView().setSelectionFromTop(row, 0);
1205 getListView().setSelected(true);
1208 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1210 final class SearchOperation implements Runnable {
1212 final AtomicBoolean interrupted = new AtomicBoolean(false);
1214 final String searchText;
1216 List<String> searchTokens; // filled in for multiWord.
1220 long searchStartMillis;
1222 Index.IndexEntry searchResult;
1224 List<RowBase> multiWordSearchResult;
1226 boolean done = false;
1228 SearchOperation(final String searchText, final Index index) {
1229 this.searchText = StringUtil.normalizeWhitespace(searchText);
1233 public String toString() {
1234 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1240 searchStartMillis = System.currentTimeMillis();
1241 final String[] searchTokenArray = WHITESPACE.split(searchText);
1242 if (searchTokenArray.length == 1) {
1243 searchResult = index.findInsertionPoint(searchText, interrupted);
1245 searchTokens = Arrays.asList(searchTokenArray);
1246 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1250 "searchText=" + searchText + ", searchDuration="
1251 + (System.currentTimeMillis() - searchStartMillis)
1252 + ", interrupted=" + interrupted.get());
1253 if (!interrupted.get()) {
1254 uiHandler.post(new Runnable() {
1257 searchFinished(SearchOperation.this);
1261 Log.d(LOG, "interrupted, skipping searchFinished.");
1263 } catch (Exception e) {
1264 Log.e(LOG, "Failure during search (can happen during Activity close.");
1266 synchronized (this) {
1274 // --------------------------------------------------------------------------
1276 // --------------------------------------------------------------------------
1278 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1279 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1281 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1282 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1284 final class IndexAdapter extends BaseAdapter {
1286 private static final float PADDING_DEFAULT_DP = 8;
1288 private static final float PADDING_LARGE_DP = 16;
1292 final List<RowBase> rows;
1294 final Set<String> toHighlight;
1296 private int mPaddingDefault;
1298 private int mPaddingLarge;
1300 IndexAdapter(final Index index) {
1303 this.toHighlight = null;
1307 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1310 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1314 private void getMetrics() {
1315 // Get the screen's density scale
1316 final float scale = getResources().getDisplayMetrics().density;
1317 // Convert the dps to pixels, based on density scale
1318 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1319 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1323 public int getCount() {
1328 public RowBase getItem(int position) {
1329 return rows.get(position);
1333 public long getItemId(int position) {
1334 return getItem(position).index();
1338 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1339 final TableLayout result;
1340 if (convertView instanceof TableLayout) {
1341 result = (TableLayout) convertView;
1342 result.removeAllViews();
1344 result = new TableLayout(parent.getContext());
1346 final RowBase row = getItem(position);
1347 if (row instanceof PairEntry.Row) {
1348 return getView(position, (PairEntry.Row) row, parent, result);
1349 } else if (row instanceof TokenRow) {
1350 return getView((TokenRow) row, parent, result);
1351 } else if (row instanceof HtmlEntry.Row) {
1352 return getView((HtmlEntry.Row) row, parent, result);
1354 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1358 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1359 final TableLayout result) {
1360 final PairEntry entry = row.getEntry();
1361 final int rowCount = entry.pairs.size();
1363 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1364 layoutParams.weight = 0.5f;
1365 layoutParams.leftMargin = mPaddingLarge;
1367 for (int r = 0; r < rowCount; ++r) {
1368 final TableRow tableRow = new TableRow(result.getContext());
1370 final TextView col1 = new TextView(tableRow.getContext());
1371 final TextView col2 = new TextView(tableRow.getContext());
1373 // Set the columns in the table.
1375 final TextView bullet = new TextView(tableRow.getContext());
1376 bullet.setText(" • ");
1377 tableRow.addView(bullet);
1379 tableRow.addView(col1, layoutParams);
1380 final TextView margin = new TextView(tableRow.getContext());
1381 margin.setText(" ");
1382 tableRow.addView(margin);
1384 final TextView bullet = new TextView(tableRow.getContext());
1385 bullet.setText(" • ");
1386 tableRow.addView(bullet);
1388 tableRow.addView(col2, layoutParams);
1392 // Set what's in the columns.
1394 final Pair pair = entry.pairs.get(r);
1395 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1396 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1398 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1399 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1401 // Bold the token instances in col1.
1402 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1403 .singleton(row.getTokenRow(true).getToken());
1404 final Spannable col1Spannable = (Spannable) col1.getText();
1405 for (final String token : toBold) {
1407 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1408 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1409 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1410 startPos += token.length();
1414 createTokenLinkSpans(col1, col1Spannable, col1Text);
1415 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1417 col1.setTypeface(typeface);
1418 col2.setTypeface(typeface);
1419 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1420 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1421 // col2.setBackgroundResource(theme.otherLangBg);
1423 if (index.swapPairEntries) {
1424 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1425 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1427 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1428 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1431 result.addView(tableRow);
1434 // Because we have a Button inside a ListView row:
1435 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1436 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1437 result.setClickable(true);
1438 result.setFocusable(true);
1439 result.setLongClickable(true);
1440 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1442 result.setBackgroundResource(theme.normalRowBg);
1444 result.setOnClickListener(new TextView.OnClickListener() {
1446 public void onClick(View v) {
1447 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1454 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1455 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1456 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1457 final Context context = parent.getContext();
1459 final TableRow tableRow = new TableRow(result.getContext());
1460 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1461 : theme.tokenRowOtherBg);
1463 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1465 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1467 result.addView(tableRow);
1469 // Make it so we can long-click on these token rows, too:
1470 final TextView textView = new TextView(context);
1471 textView.setText(text, BufferType.SPANNABLE);
1472 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1473 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1475 textView.setOnLongClickListener(textViewLongClickListenerIndex0);
1476 result.setLongClickable(true);
1479 // textView.setTextColor(android.R.color.secondary_text_light);
1480 textView.setTypeface(typeface);
1481 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1483 textView.setTextAppearance(context, theme.tokenRowFg);
1484 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1486 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1490 textView.setLayoutParams(lp);
1491 tableRow.addView(textView);
1493 if (!htmlEntries.isEmpty()) {
1494 final ClickableSpan clickableSpan = new ClickableSpan() {
1496 public void onClick(View widget) {
1499 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1500 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1501 result.setClickable(true);
1502 textView.setClickable(true);
1503 textView.setMovementMethod(LinkMovementMethod.getInstance());
1504 textView.setOnClickListener(new OnClickListener() {
1506 public void onClick(View v) {
1507 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1508 // Log.d(LOG, "html=" + html);
1509 startActivityForResult(
1510 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1511 "<html><head></head><body>%s</body></html>", html),
1512 htmlTextToHighlight, false),
1520 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1521 final IndexEntry indexEntry = row.getIndexEntry();
1522 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1523 indexEntry.htmlEntries, null, parent, result);
1526 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1527 final HtmlEntry htmlEntry = row.getEntry();
1528 final TokenRow tokenRow = row.getTokenRow(true);
1529 return getPossibleLinkToHtmlEntryView(false,
1530 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1531 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1537 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1539 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1540 final String text) {
1541 // Saw from the source code that LinkMovementMethod sets the selection!
1542 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1543 textView.setMovementMethod(LinkMovementMethod.getInstance());
1544 final Matcher matcher = CHAR_DASH.matcher(text);
1545 while (matcher.find()) {
1546 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1548 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1552 String selectedSpannableText = null;
1554 int selectedSpannableIndex = -1;
1557 public boolean onTouchEvent(MotionEvent event) {
1558 selectedSpannableText = null;
1559 selectedSpannableIndex = -1;
1560 return super.onTouchEvent(event);
1563 private class TextViewLongClickListener implements OnLongClickListener {
1566 private TextViewLongClickListener(final int index) {
1571 public boolean onLongClick(final View v) {
1572 final TextView textView = (TextView) v;
1573 final int start = textView.getSelectionStart();
1574 final int end = textView.getSelectionEnd();
1575 if (start >= 0 && end >= 0) {
1576 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1577 selectedSpannableIndex = index;
1583 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1586 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1589 // --------------------------------------------------------------------------
1591 // --------------------------------------------------------------------------
1593 void onSearchTextChange(final String text) {
1594 if ("thadolina".equals(text)) {
1595 final Dialog dialog = new Dialog(getListView().getContext());
1596 dialog.setContentView(R.layout.thadolina_dialog);
1597 dialog.setTitle("Ti amo, amore mio!");
1598 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1599 imageView.setOnClickListener(new OnClickListener() {
1601 public void onClick(View v) {
1602 final Intent intent = new Intent(Intent.ACTION_VIEW);
1603 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1604 startActivity(intent);
1609 if (dictRaf == null) {
1610 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1614 // Hide search icon once text is entered
1615 searchView.setIconifiedByDefault(text.length() > 0);
1616 searchView.setIconified(false);
1618 // if (!searchView.hasFocus()) {
1619 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1622 Log.d(LOG, "onSearchTextChange: " + text);
1623 if (currentSearchOperation != null) {
1624 Log.d(LOG, "Interrupting currentSearchOperation.");
1625 currentSearchOperation.interrupted.set(true);
1627 currentSearchOperation = new SearchOperation(text, index);
1628 searchExecutor.execute(currentSearchOperation);
1631 // --------------------------------------------------------------------------
1632 // Filtered results.
1633 // --------------------------------------------------------------------------
1635 boolean isFiltered() {
1636 return rowsToShow != null;
1639 void setFiltered(final SearchOperation searchOperation) {
1640 if (nextWordMenuItem != null) {
1641 nextWordMenuItem.setEnabled(false);
1642 previousWordMenuItem.setEnabled(false);
1644 rowsToShow = searchOperation.multiWordSearchResult;
1645 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1648 void clearFiltered() {
1649 if (nextWordMenuItem != null) {
1650 nextWordMenuItem.setEnabled(true);
1651 previousWordMenuItem.setEnabled(true);
1653 setListAdapter(new IndexAdapter(index));