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.design.widget.FloatingActionButton;
32 import android.support.v4.view.MenuItemCompat;
33 import android.support.v7.app.ActionBar;
34 import android.support.v7.app.ActionBarActivity;
35 import android.support.v7.widget.SearchView;
36 import android.support.v7.widget.SearchView.OnQueryTextListener;
37 import android.support.v7.widget.Toolbar;
38 import android.text.ClipboardManager;
39 import android.text.InputType;
40 import android.text.Spannable;
41 import android.text.method.LinkMovementMethod;
42 import android.text.style.ClickableSpan;
43 import android.text.style.StyleSpan;
44 import android.util.Log;
45 import android.util.TypedValue;
46 import android.view.ContextMenu;
47 import android.view.ContextMenu.ContextMenuInfo;
48 import android.view.Gravity;
49 import android.view.KeyEvent;
50 import android.view.Menu;
51 import android.view.MenuItem;
52 import android.view.MenuItem.OnMenuItemClickListener;
53 import android.view.MotionEvent;
54 import android.view.View;
55 import android.view.View.OnClickListener;
56 import android.view.View.OnLongClickListener;
57 import android.view.ViewGroup;
58 import android.view.WindowManager;
59 import android.view.inputmethod.EditorInfo;
60 import android.view.inputmethod.InputMethodManager;
61 import android.widget.AdapterView;
62 import android.widget.AdapterView.AdapterContextMenuInfo;
63 import android.widget.AdapterView.OnItemClickListener;
64 import android.widget.BaseAdapter;
65 import android.widget.Button;
66 import android.widget.FrameLayout;
67 import android.widget.ImageButton;
68 import android.widget.ImageView;
69 import android.widget.ImageView.ScaleType;
70 import android.widget.LinearLayout;
71 import android.widget.ListAdapter;
72 import android.widget.ListView;
73 import android.widget.TableLayout;
74 import android.widget.TableRow;
75 import android.widget.TextView;
76 import android.widget.TextView.BufferType;
77 import android.widget.Toast;
79 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
80 import com.hughes.android.dictionary.engine.Dictionary;
81 import com.hughes.android.dictionary.engine.EntrySource;
82 import com.hughes.android.dictionary.engine.HtmlEntry;
83 import com.hughes.android.dictionary.engine.Index;
84 import com.hughes.android.dictionary.engine.Index.IndexEntry;
85 import com.hughes.android.dictionary.engine.Language.LanguageResources;
86 import com.hughes.android.dictionary.engine.PairEntry;
87 import com.hughes.android.dictionary.engine.PairEntry.Pair;
88 import com.hughes.android.dictionary.engine.RowBase;
89 import com.hughes.android.dictionary.engine.TokenRow;
90 import com.hughes.android.dictionary.engine.TransliteratorManager;
91 import com.hughes.android.util.IntentLauncher;
92 import com.hughes.android.util.NonLinkClickableSpan;
93 import com.hughes.util.StringUtil;
96 import java.io.FileWriter;
97 import java.io.IOException;
98 import java.io.PrintWriter;
99 import java.io.RandomAccessFile;
100 import java.text.SimpleDateFormat;
101 import java.util.Arrays;
102 import java.util.Collections;
103 import java.util.Date;
104 import java.util.HashMap;
105 import java.util.LinkedHashSet;
106 import java.util.List;
107 import java.util.Locale;
108 import java.util.Random;
109 import java.util.Set;
110 import java.util.concurrent.Executor;
111 import java.util.concurrent.Executors;
112 import java.util.concurrent.ThreadFactory;
113 import java.util.concurrent.atomic.AtomicBoolean;
114 import java.util.regex.Matcher;
115 import java.util.regex.Pattern;
117 public class DictionaryActivity extends ActionBarActivity {
119 static final String LOG = "QuickDic";
121 DictionaryApplication application;
123 File dictFile = null;
124 RandomAccessFile dictRaf = null;
126 Dictionary dictionary = null;
132 List<RowBase> rowsToShow = null; // if not null, just show these rows.
134 final Random rand = new Random();
136 final Handler uiHandler = new Handler();
138 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
140 public Thread newThread(Runnable r) {
141 return new Thread(r, "searchExecutor");
145 private SearchOperation currentSearchOperation = null;
147 TextToSpeech textToSpeech;
148 volatile boolean ttsReady;
151 DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
152 int textColorFg = Color.BLACK;
155 private ListView listView;
156 private ListView getListView() {
157 if (listView == null) {
158 listView = (ListView)findViewById(android.R.id.list);
163 private void setListAdapter(ListAdapter adapter) {
164 getListView().setAdapter(adapter);
167 private ListAdapter getListAdapter() {
168 return getListView().getAdapter();
171 SearchView searchView;
172 ImageButton languageButton;
173 SearchView.OnQueryTextListener onQueryTextListener;
175 MenuItem nextWordMenuItem, previousWordMenuItem, randomWordMenuItem;
178 private File wordList = null;
179 private boolean saveOnlyFirstSubentry = false;
180 private boolean clickOpensContextMenu = false;
182 // Visible for testing.
183 ListAdapter indexAdapter = null;
186 * For some languages, loading the transliterators used in this search takes
187 * a long time, so we fire it up on a different thread, and don't invoke it
188 * from the main thread until it's already finished once.
190 private volatile boolean indexPrepFinished = false;
192 public DictionaryActivity() {
195 public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
196 final String searchToken) {
197 final Intent intent = new Intent(c, DictionaryActivity.class);
198 intent.putExtra(C.DICT_FILE, dictFile.getPath());
199 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
200 intent.putExtra(C.SEARCH_TOKEN, searchToken);
205 protected void onSaveInstanceState(final Bundle outState) {
206 super.onSaveInstanceState(outState);
207 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
208 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
209 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
213 public void onCreate(Bundle savedInstanceState) {
214 // This needs to be before super.onCreate, otherwise ActionbarSherlock
215 // doesn't makes the background of the actionbar white when you're
216 // in the dark theme.
217 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
219 Log.d(LOG, "onCreate:" + this);
220 super.onCreate(savedInstanceState);
222 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
224 // Don't auto-launch if this fails.
225 prefs.edit().remove(C.DICT_FILE).commit();
227 setContentView(R.layout.dictionary_activity);
229 application = (DictionaryApplication) getApplication();
230 theme = application.getSelectedTheme();
231 textColorFg = getResources().getColor(theme.tokenRowFgColor);
233 final Intent intent = getIntent();
234 String intentAction = intent.getAction();
236 * @author Dominik Köppl Querying the Intent
237 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
238 * Arguments: SearchManager.QUERY -> the phrase to search from
239 * -> language in which the phrase is written to -> to which
240 * language shall be translated
242 if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
244 String query = intent.getStringExtra(SearchManager.QUERY);
245 String from = intent.getStringExtra("from");
247 from = from.toLowerCase(Locale.US);
248 String to = intent.getStringExtra("to");
250 to = to.toLowerCase(Locale.US);
253 getIntent().putExtra(C.SEARCH_TOKEN, query);
255 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
257 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
258 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
259 for (DictionaryInfo info : dicts)
261 boolean hasFrom = from == null;
262 boolean hasTo = to == null;
263 for (IndexInfo index : info.indexInfos)
265 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
267 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
270 if (hasFrom && hasTo)
275 for (; which_index < info.indexInfos.size(); ++which_index)
277 if (info.indexInfos.get(which_index).shortName.toLowerCase(
278 Locale.US).equals(from))
281 intent.putExtra(C.INDEX_SHORT_NAME,
282 info.indexInfos.get(which_index).shortName);
285 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
294 * @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
295 * simple query Arguments follow from android standard (see
298 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
300 String query = intent.getStringExtra(SearchManager.QUERY);
302 getIntent().putExtra(C.SEARCH_TOKEN, query);
304 if (intentAction != null && intentAction.equals(Intent.ACTION_SEND))
306 String query = intent.getStringExtra(Intent.EXTRA_TEXT);
308 getIntent().putExtra(C.SEARCH_TOKEN, query);
311 * This processes text on M+ devices where QuickDic shows up in the context menu.
313 if (intentAction != null && intentAction.equals(Intent.ACTION_PROCESS_TEXT)) {
314 String query = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
316 getIntent().putExtra(C.SEARCH_TOKEN, query);
320 * @author Dominik Köppl If no dictionary is chosen, use the default
321 * dictionary specified in the preferences If this step does
322 * fail (no default directory specified), show a toast and
325 if (intent.getStringExtra(C.DICT_FILE) == null)
327 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
328 if (dictfile != null)
329 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
331 String dictFilename = intent.getStringExtra(C.DICT_FILE);
333 if (dictFilename == null)
335 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
336 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
340 if (dictFilename != null)
341 dictFile = new File(dictFilename);
344 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
346 public void onInit(int status) {
348 updateTTSLanguage(indexIndex);
353 final String name = application.getDictionaryName(dictFile.getName());
354 this.setTitle("QuickDic: " + name);
355 dictRaf = new RandomAccessFile(dictFile, "r");
356 dictionary = new Dictionary(dictRaf);
357 } catch (Exception e) {
358 Log.e(LOG, "Unable to load dictionary.", e);
359 if (dictRaf != null) {
362 } catch (IOException e1) {
363 Log.e(LOG, "Unable to close dictRaf.", e1);
367 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
368 Toast.LENGTH_LONG).show();
369 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
373 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
374 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
375 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
378 for (int i = 0; i < dictionary.indices.size(); ++i) {
379 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
384 Log.d(LOG, "Loading index " + indexIndex);
385 index = dictionary.indices.get(indexIndex);
386 getListView().setEmptyView(findViewById(android.R.id.empty));
387 setListAdapter(new IndexAdapter(index));
389 // Pre-load the collators.
390 new Thread(new Runnable() {
392 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
393 final long startMillis = System.currentTimeMillis();
395 TransliteratorManager.init(new TransliteratorManager.Callback() {
397 public void onTransliteratorReady() {
398 uiHandler.post(new Runnable() {
401 onSearchTextChange(searchView.getQuery().toString());
407 for (final Index index : dictionary.indices) {
408 final String searchToken = index.sortedIndexEntries.get(0).token;
409 final IndexEntry entry = index.findExact(searchToken);
410 if (entry == null || !searchToken.equals(entry.token)) {
411 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
414 indexPrepFinished = true;
415 } catch (Exception e) {
417 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
419 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
423 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
424 if ("SYSTEM".equals(fontName)) {
425 typeface = Typeface.DEFAULT;
426 } else if ("SERIF".equals(fontName)) {
427 typeface = Typeface.SERIF;
428 } else if ("SANS_SERIF".equals(fontName)) {
429 typeface = Typeface.SANS_SERIF;
430 } else if ("MONOSPACE".equals(fontName)) {
431 typeface = Typeface.MONOSPACE;
433 if ("FreeSerif.ttf.jpg".equals(fontName)) {
434 fontName = "FreeSerif.otf.jpg";
437 typeface = Typeface.createFromAsset(getAssets(), fontName);
438 } catch (Exception e) {
439 Log.w(LOG, "Exception trying to use typeface, using default.", e);
440 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
441 Toast.LENGTH_LONG).show();
444 if (typeface == null) {
445 Log.w(LOG, "Unable to create typeface, using default.");
446 typeface = Typeface.DEFAULT;
448 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
450 fontSizeSp = Integer.parseInt(fontSize.trim());
451 } catch (NumberFormatException e) {
456 registerForContextMenu(getListView());
459 wordList = application.getWordListFile();
460 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
462 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
464 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
466 onCreateSetupActionBarAndSearchView();
468 View floatSwapButton = findViewById(R.id.floatSwapButton);
469 floatSwapButton.setOnClickListener(new OnClickListener() {
471 public void onClick(View arg0) {
472 onLanguageButtonClick();
475 floatSwapButton.setOnLongClickListener(new OnLongClickListener() {
477 public boolean onLongClick(View v) {
478 onLanguageButtonLongClick(v.getContext());
483 final FloatingActionButton floatSearchButton = (FloatingActionButton)findViewById(R.id.floatSearchButton);
484 floatSearchButton.setOnClickListener(new OnClickListener() {
486 public void onClick(View arg0) {
487 if (!searchView.hasFocus()) {
488 searchView.requestFocus();
490 if (searchView.getQuery().toString().length() > 0) {
491 searchView.setQuery("", false);
494 searchView.setIconified(false);
498 // Set the search text from the intent, then the saved state.
499 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
500 if (savedInstanceState != null) {
501 text = savedInstanceState.getString(C.SEARCH_TOKEN);
506 setSearchText(text, true);
507 Log.d(LOG, "Trying to restore searchText=" + text);
509 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
512 searchView.requestFocus();
514 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
515 // getListView().setCacheColorHint(0);
518 private void onCreateSetupActionBarAndSearchView() {
519 ActionBar actionBar = getSupportActionBar();
520 actionBar.setDisplayShowTitleEnabled(false);
521 actionBar.setDisplayShowHomeEnabled(false);
522 actionBar.setDisplayHomeAsUpEnabled(false);
524 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
526 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
527 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
528 customSearchView.setLayoutParams(layoutParams);
530 listView.setOnItemClickListener(new OnItemClickListener() {
532 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
533 onListItemClick(getListView(), view, row, id);
537 languageButton = new ImageButton(customSearchView.getContext());
538 languageButton.setScaleType(ScaleType.FIT_CENTER);
539 languageButton.setOnClickListener(new OnClickListener() {
541 public void onClick(View v) {
542 onLanguageButtonLongClick(v.getContext());
545 languageButton.setAdjustViewBounds(true);
546 LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
547 customSearchView.addView(languageButton, lpb);
549 searchView = new SearchView(getSupportActionBar().getThemedContext());
551 // Get rid of search icon, it takes up too much space.
552 // There is still text saying "search" in the search field.
553 searchView.setIconifiedByDefault(true);
554 searchView.setIconified(false);
556 searchView.setQueryHint(getString(R.string.searchText));
557 searchView.setSubmitButtonEnabled(false);
558 searchView.setInputType(InputType.TYPE_CLASS_TEXT);
559 searchView.setImeOptions(
560 EditorInfo.IME_ACTION_DONE |
561 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
562 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
564 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
565 onQueryTextListener = new OnQueryTextListener() {
567 public boolean onQueryTextSubmit(String query) {
568 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
574 public boolean onQueryTextChange(String newText) {
575 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
576 onSearchTextChange(searchView.getQuery().toString());
580 searchView.setOnQueryTextListener(onQueryTextListener);
581 searchView.setFocusable(true);
582 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
583 FrameLayout.LayoutParams.WRAP_CONTENT, 1);
584 customSearchView.addView(searchView, lp);
586 actionBar.setCustomView(customSearchView);
587 actionBar.setDisplayShowCustomEnabled(true);
589 // Avoid wasting space on large left inset
590 Toolbar tb = (Toolbar)customSearchView.getParent();
591 tb.setContentInsetsRelative(0, 0);
595 protected void onResume() {
596 Log.d(LOG, "onResume");
598 if (PreferenceActivity.prefsMightHaveChanged) {
599 PreferenceActivity.prefsMightHaveChanged = false;
601 startActivity(getIntent());
607 protected void onPause() {
613 * Invoked when MyWebView returns, since the user might have clicked some
614 * hypertext in the MyWebView.
616 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
617 super.onActivityResult(requestCode, resultCode, result);
618 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
619 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
620 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
624 private static void setDictionaryPrefs(final Context context, final File dictFile,
625 final String indexShortName, final String searchToken) {
626 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
628 prefs.putString(C.DICT_FILE, dictFile.getPath());
629 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
630 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
635 protected void onDestroy() {
637 if (dictRaf == null) {
641 final SearchOperation searchOperation = currentSearchOperation;
642 currentSearchOperation = null;
644 // Before we close the RAF, we have to wind the current search down.
645 if (searchOperation != null) {
646 Log.d(LOG, "Interrupting search to shut down.");
647 currentSearchOperation = null;
648 searchOperation.interrupted.set(true);
652 Log.d(LOG, "Closing RAF.");
654 } catch (IOException e) {
655 Log.e(LOG, "Failed to close dictionary", e);
660 // --------------------------------------------------------------------------
662 // --------------------------------------------------------------------------
664 private void showKeyboard() {
665 // For some reason, this doesn't always work the first time.
666 // One way to replicate the problem:
667 // Press the "task switch" button repeatedly to pause and resume
668 for (int delay = 1; delay <= 101; delay += 100) {
669 searchView.postDelayed(new Runnable() {
672 Log.d(LOG, "Trying to show soft keyboard.");
673 final boolean searchTextHadFocus = searchView.hasFocus();
674 searchView.requestFocusFromTouch();
675 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
676 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
677 if (!searchTextHadFocus) {
685 private void hideKeyboard() {
686 Log.d(LOG, "Hide soft keyboard.");
687 searchView.clearFocus();
688 InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
689 manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
692 void updateLangButton() {
693 final LanguageResources languageResources =
694 DictionaryApplication.isoCodeToResources.get(index.shortName);
695 if (languageResources != null && languageResources.flagId != 0) {
696 languageButton.setImageResource(languageResources.flagId);
698 if (indexIndex % 2 == 0) {
699 languageButton.setImageResource(android.R.drawable.ic_media_next);
701 languageButton.setImageResource(android.R.drawable.ic_media_previous);
704 updateTTSLanguage(indexIndex);
707 private void updateTTSLanguage(int i) {
708 if (!ttsReady || index == null || textToSpeech == null) {
709 Log.d(LOG, "Can't updateTTSLanguage.");
712 final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
713 Log.d(LOG, "Setting TTS locale to: " + locale);
715 final int ttsResult = textToSpeech.setLanguage(locale);
716 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
717 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
718 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
720 } catch (Exception e) {
721 Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
725 void onLanguageButtonClick() {
726 if (dictionary.indices.size() == 1) {
727 // No need to work to switch indices.
730 if (currentSearchOperation != null) {
731 currentSearchOperation.interrupted.set(true);
732 currentSearchOperation = null;
734 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
735 searchView.getQuery().toString(), false);
738 void onLanguageButtonLongClick(final Context context) {
739 final Dialog dialog = new Dialog(context);
740 dialog.setContentView(R.layout.select_dictionary_dialog);
741 dialog.setTitle(R.string.selectDictionary);
743 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
745 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
746 final Button button = new Button(listView.getContext());
747 final String name = getString(R.string.dictionaryManager);
748 button.setText(name);
749 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
750 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
752 protected void onGo() {
754 DictionaryActivity.this.finish();
757 button.setOnClickListener(intentLauncher);
758 listView.addHeaderView(button);
760 listView.setAdapter(new BaseAdapter() {
762 public View getView(int position, View convertView, ViewGroup parent) {
763 final DictionaryInfo dictionaryInfo = getItem(position);
765 final LinearLayout result = new LinearLayout(parent.getContext());
767 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
768 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
769 final View button = application.createButton(parent.getContext(),
770 dictionaryInfo, indexInfo);
771 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
772 getLaunchIntent(getApplicationContext(),
773 application.getPath(dictionaryInfo.uncompressedFilename),
774 indexInfo.shortName, searchView.getQuery().toString())) {
776 protected void onGo() {
778 DictionaryActivity.this.finish();
781 button.setOnClickListener(intentLauncher);
782 if (i == indexIndex && dictFile != null &&
783 dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
784 button.setPressed(true);
786 result.addView(button);
789 final TextView nameView = new TextView(parent.getContext());
790 final String name = application
791 .getDictionaryName(dictionaryInfo.uncompressedFilename);
792 nameView.setText(name);
793 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
794 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
795 layoutParams.width = 0;
796 layoutParams.weight = 1.0f;
797 nameView.setLayoutParams(layoutParams);
798 nameView.setGravity(Gravity.CENTER_VERTICAL);
799 result.addView(nameView);
804 public long getItemId(int position) {
809 public DictionaryInfo getItem(int position) {
810 return installedDicts.get(position);
814 public int getCount() {
815 return installedDicts.size();
821 void onUpDownButton(final boolean up) {
825 final int firstVisibleRow = getListView().getFirstVisiblePosition();
826 final RowBase row = index.rows.get(firstVisibleRow);
827 final TokenRow tokenRow = row.getTokenRow(true);
828 final int destIndexEntry;
830 if (row != tokenRow) {
831 destIndexEntry = tokenRow.referenceIndex;
833 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
837 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
839 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
840 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
841 setSearchText(dest.token, false);
842 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
846 void onRandomWordButton() {
847 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
848 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
849 setSearchText(dest.token, false);
850 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
854 // --------------------------------------------------------------------------
856 // --------------------------------------------------------------------------
858 final Random random = new Random();
861 public boolean onCreateOptionsMenu(final Menu menu) {
863 if (PreferenceManager.getDefaultSharedPreferences(this)
864 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
866 nextWordMenuItem = menu.add(getString(R.string.nextWord))
867 .setIcon(R.drawable.arrow_down_float);
868 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
869 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
871 public boolean onMenuItemClick(MenuItem item) {
872 onUpDownButton(false);
878 previousWordMenuItem = menu.add(getString(R.string.previousWord))
879 .setIcon(R.drawable.arrow_up_float);
880 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
881 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
883 public boolean onMenuItemClick(MenuItem item) {
884 onUpDownButton(true);
890 randomWordMenuItem = menu.add(getString(R.string.randomWord));
891 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
893 public boolean onMenuItemClick(MenuItem item) {
894 onRandomWordButton();
899 application.onCreateGlobalOptionsMenu(this, menu);
902 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
903 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
904 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
905 public boolean onMenuItemClick(final MenuItem menuItem) {
906 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
914 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
915 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
916 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
917 public boolean onMenuItemClick(final MenuItem menuItem) {
918 final Context context = getListView().getContext();
919 final Dialog dialog = new Dialog(context);
920 dialog.setContentView(R.layout.about_dictionary_dialog);
921 final TextView textView = (TextView) dialog.findViewById(R.id.text);
923 final String name = application.getDictionaryName(dictFile.getName());
924 dialog.setTitle(name);
926 final StringBuilder builder = new StringBuilder();
927 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
928 dictionaryInfo.uncompressedBytes = dictFile.length();
929 if (dictionaryInfo != null) {
930 builder.append(dictionaryInfo.dictInfo).append("\n\n");
931 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
934 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
937 getString(R.string.dictionaryCreationTime,
938 dictionaryInfo.creationMillis)).append("\n");
939 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
940 builder.append("\n");
941 builder.append(getString(R.string.indexName, indexInfo.shortName))
944 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
947 builder.append("\n");
948 builder.append(getString(R.string.sources)).append("\n");
949 for (final EntrySource source : dictionary.sources) {
951 getString(R.string.sourceInfo, source.getName(),
952 source.getNumEntries())).append("\n");
955 textView.setText(builder.toString());
958 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
959 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
960 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
961 dialog.getWindow().setAttributes(layoutParams);
970 // --------------------------------------------------------------------------
971 // Context Menu + clicks
972 // --------------------------------------------------------------------------
975 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
976 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
977 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
979 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
980 wordList.getName()));
982 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
983 public boolean onMenuItemClick(android.view.MenuItem item) {
984 onAppendToWordList(row);
989 final android.view.MenuItem share = menu.add("Share");
990 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
991 public boolean onMenuItemClick(android.view.MenuItem item) {
992 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
993 shareIntent.setType("text/plain");
994 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
996 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
997 row.getRawText(saveOnlyFirstSubentry));
998 startActivity(shareIntent);
1003 final android.view.MenuItem copy = menu.add(android.R.string.copy);
1004 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1005 public boolean onMenuItemClick(android.view.MenuItem item) {
1011 if (selectedSpannableText != null) {
1012 final String selectedText = selectedSpannableText;
1013 final android.view.MenuItem searchForSelection = menu.add(getString(
1014 R.string.searchForSelection,
1015 selectedSpannableText));
1017 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1018 public boolean onMenuItemClick(android.view.MenuItem item) {
1019 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
1023 // Rats, this won't be shown:
1024 //searchForSelection.setIcon(R.drawable.abs__ic_search);
1027 if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
1028 final android.view.MenuItem speak = menu.add(R.string.speak);
1029 final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
1030 updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
1031 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1033 public boolean onMenuItemClick(android.view.MenuItem item) {
1034 textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
1035 new HashMap<String, String>());
1042 private void jumpToTextFromHyperLink(
1043 final String selectedText, final int defaultIndexToUse) {
1044 int indexToUse = -1;
1046 for (int i = 0; i < dictionary.indices.size(); ++i) {
1047 final Index index = dictionary.indices.get(i);
1048 if (indexPrepFinished) {
1049 System.out.println("Doing index lookup: on " + selectedText);
1050 final IndexEntry indexEntry = index.findExact(selectedText);
1051 if (indexEntry != null) {
1052 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1053 .getTokenRow(false);
1054 if (tokenRow != null && tokenRow.hasMainEntry) {
1060 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1063 if (numFound != 1 || indexToUse == -1) {
1064 indexToUse = defaultIndexToUse;
1066 // Without this extra delay, the call to jumpToRow that this
1067 // invokes doesn't always actually have any effect.
1068 final int actualIndexToUse = indexToUse;
1069 getListView().postDelayed(new Runnable() {
1072 setIndexAndSearchText(actualIndexToUse, selectedText, true);
1078 * Called when user clicks outside of search text, so that they can start
1079 * typing again immediately.
1081 void defocusSearchText() {
1082 // Log.d(LOG, "defocusSearchText");
1083 // Request focus so that if we start typing again, it clears the text
1085 getListView().requestFocus();
1087 // Visual indication that a new keystroke will clear the search text.
1088 // Doesn't seem to work unless searchText has focus.
1089 // searchView.selectAll();
1092 protected void onListItemClick(ListView l, View v, int row, long id) {
1093 defocusSearchText();
1094 if (clickOpensContextMenu && dictRaf != null) {
1099 @SuppressLint("SimpleDateFormat")
1100 void onAppendToWordList(final RowBase row) {
1101 defocusSearchText();
1103 final StringBuilder rawText = new StringBuilder();
1104 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1105 rawText.append(index.longName).append("\t");
1106 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1107 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1108 Log.d(LOG, "Writing : " + rawText);
1111 wordList.getParentFile().mkdirs();
1112 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1113 out.println(rawText.toString());
1115 } catch (Exception e) {
1116 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1117 Toast.makeText(this,
1118 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1119 Toast.LENGTH_LONG).show();
1124 @SuppressWarnings("deprecation")
1125 void onCopy(final RowBase row) {
1126 defocusSearchText();
1128 Log.d(LOG, "Copy, row=" + row);
1129 final StringBuilder result = new StringBuilder();
1130 result.append(row.getRawText(false));
1131 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1132 clipboardManager.setText(result.toString());
1133 Log.d(LOG, "Copied: " + result);
1137 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1138 if (event.getUnicodeChar() != 0) {
1139 if (!searchView.hasFocus()) {
1140 setSearchText("" + (char) event.getUnicodeChar(), true);
1141 searchView.requestFocus();
1145 if (keyCode == KeyEvent.KEYCODE_BACK) {
1146 // Log.d(LOG, "Clearing dictionary prefs.");
1147 // Pretend that we just autolaunched so that we won't do it again.
1148 // DictionaryManagerActivity.lastAutoLaunchMillis =
1149 // System.currentTimeMillis();
1151 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1152 Log.d(LOG, "Trying to hide soft keyboard.");
1153 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1154 View focus = getCurrentFocus();
1155 if (focus != null) {
1156 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1157 InputMethodManager.HIDE_NOT_ALWAYS);
1161 return super.onKeyDown(keyCode, event);
1164 private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
1165 Log.d(LOG, "Changing index to: " + newIndex);
1166 if (newIndex == -1) {
1167 Log.e(LOG, "Invalid index.");
1170 if (newIndex != indexIndex) {
1171 indexIndex = newIndex;
1172 index = dictionary.indices.get(indexIndex);
1173 indexAdapter = new IndexAdapter(index);
1174 setListAdapter(indexAdapter);
1175 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1176 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1179 setSearchText(newSearchText, true, hideKeyboard);
1182 private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
1183 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1184 // Disable the listener, because sometimes it doesn't work.
1185 searchView.setOnQueryTextListener(null);
1186 searchView.setQuery(text, false);
1187 moveCursorToRight();
1188 searchView.setOnQueryTextListener(onQueryTextListener);
1190 if (triggerSearch) {
1191 onSearchTextChange(text);
1194 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1200 private void setSearchText(final String text, final boolean triggerSearch) {
1201 setSearchText(text, triggerSearch, true);
1204 // private long cursorDelayMillis = 100;
1205 private void moveCursorToRight() {
1206 // if (searchText.getLayout() != null) {
1207 // cursorDelayMillis = 100;
1208 // // Surprising, but this can crash when you rotate...
1209 // Selection.moveToRightEdge(searchView.getQuery(),
1210 // searchText.getLayout());
1212 // uiHandler.postDelayed(new Runnable() {
1214 // public void run() {
1215 // moveCursorToRight();
1217 // }, cursorDelayMillis);
1218 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1222 // --------------------------------------------------------------------------
1224 // --------------------------------------------------------------------------
1226 private void searchFinished(final SearchOperation searchOperation) {
1227 if (searchOperation.interrupted.get()) {
1228 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1231 if (searchOperation != this.currentSearchOperation) {
1232 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1236 final Index.IndexEntry searchResult = searchOperation.searchResult;
1237 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1239 currentSearchOperation = null;
1240 uiHandler.postDelayed(new Runnable() {
1243 if (currentSearchOperation == null) {
1244 if (searchResult != null) {
1248 jumpToRow(searchResult.startRow);
1249 } else if (searchOperation.multiWordSearchResult != null) {
1250 // Multi-row search....
1251 setFiltered(searchOperation);
1253 throw new IllegalStateException("This should never happen.");
1256 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1262 private final void jumpToRow(final int row) {
1263 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1264 // getListView().requestFocusFromTouch();
1265 getListView().setSelectionFromTop(row, 0);
1266 getListView().setSelected(true);
1269 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1271 final class SearchOperation implements Runnable {
1273 final AtomicBoolean interrupted = new AtomicBoolean(false);
1275 final String searchText;
1277 List<String> searchTokens; // filled in for multiWord.
1281 long searchStartMillis;
1283 Index.IndexEntry searchResult;
1285 List<RowBase> multiWordSearchResult;
1287 boolean done = false;
1289 SearchOperation(final String searchText, final Index index) {
1290 this.searchText = StringUtil.normalizeWhitespace(searchText);
1294 public String toString() {
1295 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1301 searchStartMillis = System.currentTimeMillis();
1302 final String[] searchTokenArray = WHITESPACE.split(searchText);
1303 if (searchTokenArray.length == 1) {
1304 searchResult = index.findInsertionPoint(searchText, interrupted);
1306 searchTokens = Arrays.asList(searchTokenArray);
1307 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1311 "searchText=" + searchText + ", searchDuration="
1312 + (System.currentTimeMillis() - searchStartMillis)
1313 + ", interrupted=" + interrupted.get());
1314 if (!interrupted.get()) {
1315 uiHandler.post(new Runnable() {
1318 searchFinished(SearchOperation.this);
1322 Log.d(LOG, "interrupted, skipping searchFinished.");
1324 } catch (Exception e) {
1325 Log.e(LOG, "Failure during search (can happen during Activity close.");
1327 synchronized (this) {
1335 // --------------------------------------------------------------------------
1337 // --------------------------------------------------------------------------
1339 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1340 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1342 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1343 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1345 final class IndexAdapter extends BaseAdapter {
1347 private static final float PADDING_DEFAULT_DP = 8;
1349 private static final float PADDING_LARGE_DP = 16;
1353 final List<RowBase> rows;
1355 final Set<String> toHighlight;
1357 private int mPaddingDefault;
1359 private int mPaddingLarge;
1361 IndexAdapter(final Index index) {
1364 this.toHighlight = null;
1368 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1371 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1375 private void getMetrics() {
1376 // Get the screen's density scale
1377 final float scale = getResources().getDisplayMetrics().density;
1378 // Convert the dps to pixels, based on density scale
1379 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1380 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1384 public int getCount() {
1389 public RowBase getItem(int position) {
1390 return rows.get(position);
1394 public long getItemId(int position) {
1395 return getItem(position).index();
1399 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1400 final TableLayout result;
1401 if (convertView instanceof TableLayout) {
1402 result = (TableLayout) convertView;
1403 result.removeAllViews();
1405 result = new TableLayout(parent.getContext());
1407 final RowBase row = getItem(position);
1408 if (row instanceof PairEntry.Row) {
1409 return getView(position, (PairEntry.Row) row, parent, result);
1410 } else if (row instanceof TokenRow) {
1411 return getView((TokenRow) row, parent, result);
1412 } else if (row instanceof HtmlEntry.Row) {
1413 return getView((HtmlEntry.Row) row, parent, result);
1415 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1419 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1420 final TableLayout result) {
1421 final PairEntry entry = row.getEntry();
1422 final int rowCount = entry.pairs.size();
1424 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1425 layoutParams.weight = 0.5f;
1426 layoutParams.leftMargin = mPaddingLarge;
1428 for (int r = 0; r < rowCount; ++r) {
1429 final TableRow tableRow = new TableRow(result.getContext());
1431 final TextView col1 = new TextView(tableRow.getContext());
1432 final TextView col2 = new TextView(tableRow.getContext());
1434 // Set the columns in the table.
1436 final TextView bullet = new TextView(tableRow.getContext());
1437 bullet.setText(" • ");
1438 tableRow.addView(bullet);
1440 tableRow.addView(col1, layoutParams);
1441 final TextView margin = new TextView(tableRow.getContext());
1442 margin.setText(" ");
1443 tableRow.addView(margin);
1445 final TextView bullet = new TextView(tableRow.getContext());
1446 bullet.setText(" • ");
1447 tableRow.addView(bullet);
1449 tableRow.addView(col2, layoutParams);
1453 // Set what's in the columns.
1455 final Pair pair = entry.pairs.get(r);
1456 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1457 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1459 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1460 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1462 // Bold the token instances in col1.
1463 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1464 .singleton(row.getTokenRow(true).getToken());
1465 final Spannable col1Spannable = (Spannable) col1.getText();
1466 for (final String token : toBold) {
1468 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1469 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1470 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1471 startPos += token.length();
1475 createTokenLinkSpans(col1, col1Spannable, col1Text);
1476 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1478 col1.setTypeface(typeface);
1479 col2.setTypeface(typeface);
1480 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1481 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1482 // col2.setBackgroundResource(theme.otherLangBg);
1484 if (index.swapPairEntries) {
1485 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1486 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1488 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1489 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1492 result.addView(tableRow);
1495 // Because we have a Button inside a ListView row:
1496 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1497 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1498 result.setClickable(true);
1499 result.setFocusable(true);
1500 result.setLongClickable(true);
1501 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1503 result.setBackgroundResource(theme.normalRowBg);
1505 result.setOnClickListener(new TextView.OnClickListener() {
1507 public void onClick(View v) {
1508 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1515 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1516 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1517 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1518 final Context context = parent.getContext();
1520 final TableRow tableRow = new TableRow(result.getContext());
1521 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1522 : theme.tokenRowOtherBg);
1524 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1526 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1528 result.addView(tableRow);
1530 // Make it so we can long-click on these token rows, too:
1531 final TextView textView = new TextView(context);
1532 textView.setText(text, BufferType.SPANNABLE);
1533 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1534 textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1535 result.setLongClickable(true);
1538 // textView.setTextColor(android.R.color.secondary_text_light);
1539 textView.setTypeface(typeface);
1540 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1542 textView.setTextAppearance(context, theme.tokenRowFg);
1543 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1545 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1549 textView.setLayoutParams(lp);
1550 tableRow.addView(textView);
1552 if (!htmlEntries.isEmpty()) {
1553 final ClickableSpan clickableSpan = new ClickableSpan() {
1555 public void onClick(View widget) {
1558 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1559 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1560 result.setClickable(true);
1561 textView.setClickable(true);
1562 textView.setMovementMethod(LinkMovementMethod.getInstance());
1563 textView.setOnClickListener(new OnClickListener() {
1565 public void onClick(View v) {
1566 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1567 // Log.d(LOG, "html=" + html);
1568 startActivityForResult(
1569 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1570 "<html><head></head><body>%s</body></html>", html),
1571 htmlTextToHighlight, false),
1579 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1580 final IndexEntry indexEntry = row.getIndexEntry();
1581 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1582 indexEntry.htmlEntries, null, parent, result);
1585 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1586 final HtmlEntry htmlEntry = row.getEntry();
1587 final TokenRow tokenRow = row.getTokenRow(true);
1588 return getPossibleLinkToHtmlEntryView(false,
1589 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1590 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1596 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1598 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1599 final String text) {
1600 // Saw from the source code that LinkMovementMethod sets the selection!
1601 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1602 textView.setMovementMethod(LinkMovementMethod.getInstance());
1603 final Matcher matcher = CHAR_DASH.matcher(text);
1604 while (matcher.find()) {
1605 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1607 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1611 String selectedSpannableText = null;
1613 int selectedSpannableIndex = -1;
1616 public boolean onTouchEvent(MotionEvent event) {
1617 selectedSpannableText = null;
1618 selectedSpannableIndex = -1;
1619 return super.onTouchEvent(event);
1622 private class TextViewLongClickListener implements OnLongClickListener {
1625 private TextViewLongClickListener(final int index) {
1630 public boolean onLongClick(final View v) {
1631 final TextView textView = (TextView) v;
1632 final int start = textView.getSelectionStart();
1633 final int end = textView.getSelectionEnd();
1634 if (start >= 0 && end >= 0) {
1635 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1636 selectedSpannableIndex = index;
1642 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1645 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1648 // --------------------------------------------------------------------------
1650 // --------------------------------------------------------------------------
1652 void onSearchTextChange(final String text) {
1653 if ("thadolina".equals(text)) {
1654 final Dialog dialog = new Dialog(getListView().getContext());
1655 dialog.setContentView(R.layout.thadolina_dialog);
1656 dialog.setTitle("Ti amo, amore mio!");
1657 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1658 imageView.setOnClickListener(new OnClickListener() {
1660 public void onClick(View v) {
1661 final Intent intent = new Intent(Intent.ACTION_VIEW);
1662 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1663 startActivity(intent);
1668 if (dictRaf == null) {
1669 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1673 // if (!searchView.hasFocus()) {
1674 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1677 Log.d(LOG, "onSearchTextChange: " + text);
1678 if (currentSearchOperation != null) {
1679 Log.d(LOG, "Interrupting currentSearchOperation.");
1680 currentSearchOperation.interrupted.set(true);
1682 currentSearchOperation = new SearchOperation(text, index);
1683 searchExecutor.execute(currentSearchOperation);
1684 ((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
1687 // --------------------------------------------------------------------------
1688 // Filtered results.
1689 // --------------------------------------------------------------------------
1691 boolean isFiltered() {
1692 return rowsToShow != null;
1695 void setFiltered(final SearchOperation searchOperation) {
1696 if (nextWordMenuItem != null) {
1697 nextWordMenuItem.setEnabled(false);
1698 previousWordMenuItem.setEnabled(false);
1700 rowsToShow = searchOperation.multiWordSearchResult;
1701 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1704 void clearFiltered() {
1705 if (nextWordMenuItem != null) {
1706 nextWordMenuItem.setEnabled(true);
1707 previousWordMenuItem.setEnabled(true);
1709 setListAdapter(new IndexAdapter(index));