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());
212 private int getMatchLen(String search, Index.IndexEntry e)
214 if (e == null) return 0;
215 for (int i = 0; i < search.length(); ++i)
217 String a = search.substring(0, i + 1);
218 String b = e.token.substring(0, i + 1);
219 if (!a.equalsIgnoreCase(b))
222 return search.length();
226 public void onCreate(Bundle savedInstanceState) {
227 // This needs to be before super.onCreate, otherwise ActionbarSherlock
228 // doesn't makes the background of the actionbar white when you're
229 // in the dark theme.
230 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
232 Log.d(LOG, "onCreate:" + this);
233 super.onCreate(savedInstanceState);
235 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
237 // Don't auto-launch if this fails.
238 prefs.edit().remove(C.DICT_FILE).commit();
240 setContentView(R.layout.dictionary_activity);
242 application = (DictionaryApplication) getApplication();
243 theme = application.getSelectedTheme();
244 textColorFg = getResources().getColor(theme.tokenRowFgColor);
246 final Intent intent = getIntent();
247 String intentAction = intent.getAction();
249 * @author Dominik Köppl Querying the Intent
250 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
251 * Arguments: SearchManager.QUERY -> the phrase to search from
252 * -> language in which the phrase is written to -> to which
253 * language shall be translated
255 if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
257 String query = intent.getStringExtra(SearchManager.QUERY);
258 String from = intent.getStringExtra("from");
260 from = from.toLowerCase(Locale.US);
261 String to = intent.getStringExtra("to");
263 to = to.toLowerCase(Locale.US);
266 getIntent().putExtra(C.SEARCH_TOKEN, query);
268 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
270 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
271 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
272 for (DictionaryInfo info : dicts)
274 boolean hasFrom = from == null;
275 boolean hasTo = to == null;
276 for (IndexInfo index : info.indexInfos)
278 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
280 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
283 if (hasFrom && hasTo)
288 for (; which_index < info.indexInfos.size(); ++which_index)
290 if (info.indexInfos.get(which_index).shortName.toLowerCase(
291 Locale.US).equals(from))
294 intent.putExtra(C.INDEX_SHORT_NAME,
295 info.indexInfos.get(which_index).shortName);
298 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
307 * @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
308 * simple query Arguments follow from android standard (see
311 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
313 String query = intent.getStringExtra(SearchManager.QUERY);
315 getIntent().putExtra(C.SEARCH_TOKEN, query);
317 if (intentAction != null && intentAction.equals(Intent.ACTION_SEND))
319 String query = intent.getStringExtra(Intent.EXTRA_TEXT);
321 getIntent().putExtra(C.SEARCH_TOKEN, query);
324 * This processes text on M+ devices where QuickDic shows up in the context menu.
326 if (intentAction != null && intentAction.equals(Intent.ACTION_PROCESS_TEXT)) {
327 String query = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
329 getIntent().putExtra(C.SEARCH_TOKEN, query);
333 * @author Dominik Köppl If no dictionary is chosen, use the default
334 * dictionary specified in the preferences If this step does
335 * fail (no default dictionary specified), show a toast and
338 if (intent.getStringExtra(C.DICT_FILE) == null)
340 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
341 if (dictfile != null)
342 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
344 String dictFilename = intent.getStringExtra(C.DICT_FILE);
345 if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null)
347 final List<DictionaryInfo> dics = application.getDictionariesOnDevice(null);
348 final String search = intent.getStringExtra(C.SEARCH_TOKEN);
349 String bestFname = null;
350 String bestIndex = null;
351 int bestMatchLen = 2; // ignore shorter matches
352 AtomicBoolean dummy = new AtomicBoolean();
353 for (int i = 0; dictFilename == null && i < dics.size(); ++i)
356 final String fname = dics.get(i).uncompressedFilename;
357 Dictionary dic = new Dictionary(new RandomAccessFile(new File(fname), "r"));
358 for (int j = 0; j < dic.indices.size(); ++j) {
359 Index idx = dic.indices.get(j);
360 if (idx.findExact(search) != null)
362 dictFilename = fname;
363 intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
366 int matchLen = getMatchLen(search, idx.findInsertionPoint(search, dummy));
367 if (matchLen > bestMatchLen)
369 dictFilename = fname;
370 intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
371 bestMatchLen = matchLen;
374 } catch (Exception e) {}
378 if (dictFilename == null)
380 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
381 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
385 if (dictFilename != null)
386 dictFile = new File(dictFilename);
389 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
391 public void onInit(int status) {
393 updateTTSLanguage(indexIndex);
398 final String name = application.getDictionaryName(dictFile.getName());
399 this.setTitle("QuickDic: " + name);
400 dictRaf = new RandomAccessFile(dictFile, "r");
401 dictionary = new Dictionary(dictRaf);
402 } catch (Exception e) {
403 Log.e(LOG, "Unable to load dictionary.", e);
404 if (dictRaf != null) {
407 } catch (IOException e1) {
408 Log.e(LOG, "Unable to close dictRaf.", e1);
412 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
413 Toast.LENGTH_LONG).show();
414 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
418 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
419 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
420 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
423 for (int i = 0; i < dictionary.indices.size(); ++i) {
424 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
429 Log.d(LOG, "Loading index " + indexIndex);
430 index = dictionary.indices.get(indexIndex);
431 getListView().setEmptyView(findViewById(android.R.id.empty));
432 setListAdapter(new IndexAdapter(index));
434 // Pre-load the collators.
435 new Thread(new Runnable() {
437 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
438 final long startMillis = System.currentTimeMillis();
440 TransliteratorManager.init(new TransliteratorManager.Callback() {
442 public void onTransliteratorReady() {
443 uiHandler.post(new Runnable() {
446 onSearchTextChange(searchView.getQuery().toString());
452 for (final Index index : dictionary.indices) {
453 final String searchToken = index.sortedIndexEntries.get(0).token;
454 final IndexEntry entry = index.findExact(searchToken);
455 if (entry == null || !searchToken.equals(entry.token)) {
456 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
459 indexPrepFinished = true;
460 } catch (Exception e) {
462 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
464 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
468 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
469 if ("SYSTEM".equals(fontName)) {
470 typeface = Typeface.DEFAULT;
471 } else if ("SERIF".equals(fontName)) {
472 typeface = Typeface.SERIF;
473 } else if ("SANS_SERIF".equals(fontName)) {
474 typeface = Typeface.SANS_SERIF;
475 } else if ("MONOSPACE".equals(fontName)) {
476 typeface = Typeface.MONOSPACE;
478 if ("FreeSerif.ttf.jpg".equals(fontName)) {
479 fontName = "FreeSerif.otf.jpg";
482 typeface = Typeface.createFromAsset(getAssets(), fontName);
483 } catch (Exception e) {
484 Log.w(LOG, "Exception trying to use typeface, using default.", e);
485 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
486 Toast.LENGTH_LONG).show();
489 if (typeface == null) {
490 Log.w(LOG, "Unable to create typeface, using default.");
491 typeface = Typeface.DEFAULT;
493 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
495 fontSizeSp = Integer.parseInt(fontSize.trim());
496 } catch (NumberFormatException e) {
501 registerForContextMenu(getListView());
504 wordList = application.getWordListFile();
505 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
507 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
509 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
511 onCreateSetupActionBarAndSearchView();
513 View floatSwapButton = findViewById(R.id.floatSwapButton);
514 floatSwapButton.setOnClickListener(new OnClickListener() {
516 public void onClick(View arg0) {
517 onLanguageButtonClick();
520 floatSwapButton.setOnLongClickListener(new OnLongClickListener() {
522 public boolean onLongClick(View v) {
523 onLanguageButtonLongClick(v.getContext());
528 final FloatingActionButton floatSearchButton = (FloatingActionButton)findViewById(R.id.floatSearchButton);
529 floatSearchButton.setOnClickListener(new OnClickListener() {
531 public void onClick(View arg0) {
532 if (!searchView.hasFocus()) {
533 searchView.requestFocus();
535 if (searchView.getQuery().toString().length() > 0) {
536 searchView.setQuery("", false);
539 searchView.setIconified(false);
543 // Set the search text from the intent, then the saved state.
544 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
545 if (savedInstanceState != null) {
546 text = savedInstanceState.getString(C.SEARCH_TOKEN);
551 setSearchText(text, true);
552 Log.d(LOG, "Trying to restore searchText=" + text);
554 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
557 searchView.requestFocus();
559 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
560 // getListView().setCacheColorHint(0);
563 private void onCreateSetupActionBarAndSearchView() {
564 ActionBar actionBar = getSupportActionBar();
565 actionBar.setDisplayShowTitleEnabled(false);
566 actionBar.setDisplayShowHomeEnabled(false);
567 actionBar.setDisplayHomeAsUpEnabled(false);
569 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
571 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
572 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
573 customSearchView.setLayoutParams(layoutParams);
575 listView.setOnItemClickListener(new OnItemClickListener() {
577 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
578 onListItemClick(getListView(), view, row, id);
582 languageButton = new ImageButton(customSearchView.getContext());
583 languageButton.setScaleType(ScaleType.FIT_CENTER);
584 languageButton.setOnClickListener(new OnClickListener() {
586 public void onClick(View v) {
587 onLanguageButtonLongClick(v.getContext());
590 languageButton.setAdjustViewBounds(true);
591 LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
592 customSearchView.addView(languageButton, lpb);
594 searchView = new SearchView(getSupportActionBar().getThemedContext());
596 // Get rid of search icon, it takes up too much space.
597 // There is still text saying "search" in the search field.
598 searchView.setIconifiedByDefault(true);
599 searchView.setIconified(false);
601 searchView.setQueryHint(getString(R.string.searchText));
602 searchView.setSubmitButtonEnabled(false);
603 searchView.setInputType(InputType.TYPE_CLASS_TEXT);
604 searchView.setImeOptions(
605 EditorInfo.IME_ACTION_DONE |
606 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
607 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
609 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
610 onQueryTextListener = new OnQueryTextListener() {
612 public boolean onQueryTextSubmit(String query) {
613 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
619 public boolean onQueryTextChange(String newText) {
620 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
621 onSearchTextChange(searchView.getQuery().toString());
625 searchView.setOnQueryTextListener(onQueryTextListener);
626 searchView.setFocusable(true);
627 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
628 FrameLayout.LayoutParams.WRAP_CONTENT, 1);
629 customSearchView.addView(searchView, lp);
631 actionBar.setCustomView(customSearchView);
632 actionBar.setDisplayShowCustomEnabled(true);
634 // Avoid wasting space on large left inset
635 Toolbar tb = (Toolbar)customSearchView.getParent();
636 tb.setContentInsetsRelative(0, 0);
640 protected void onResume() {
641 Log.d(LOG, "onResume");
643 if (PreferenceActivity.prefsMightHaveChanged) {
644 PreferenceActivity.prefsMightHaveChanged = false;
646 startActivity(getIntent());
652 protected void onPause() {
658 * Invoked when MyWebView returns, since the user might have clicked some
659 * hypertext in the MyWebView.
661 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
662 super.onActivityResult(requestCode, resultCode, result);
663 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
664 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
665 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
669 private static void setDictionaryPrefs(final Context context, final File dictFile,
670 final String indexShortName, final String searchToken) {
671 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
673 prefs.putString(C.DICT_FILE, dictFile.getPath());
674 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
675 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
680 protected void onDestroy() {
682 if (dictRaf == null) {
686 final SearchOperation searchOperation = currentSearchOperation;
687 currentSearchOperation = null;
689 // Before we close the RAF, we have to wind the current search down.
690 if (searchOperation != null) {
691 Log.d(LOG, "Interrupting search to shut down.");
692 currentSearchOperation = null;
693 searchOperation.interrupted.set(true);
697 Log.d(LOG, "Closing RAF.");
699 } catch (IOException e) {
700 Log.e(LOG, "Failed to close dictionary", e);
705 // --------------------------------------------------------------------------
707 // --------------------------------------------------------------------------
709 private void showKeyboard() {
710 // For some reason, this doesn't always work the first time.
711 // One way to replicate the problem:
712 // Press the "task switch" button repeatedly to pause and resume
713 for (int delay = 1; delay <= 101; delay += 100) {
714 searchView.postDelayed(new Runnable() {
717 Log.d(LOG, "Trying to show soft keyboard.");
718 final boolean searchTextHadFocus = searchView.hasFocus();
719 searchView.requestFocusFromTouch();
720 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
721 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
722 if (!searchTextHadFocus) {
730 private void hideKeyboard() {
731 Log.d(LOG, "Hide soft keyboard.");
732 searchView.clearFocus();
733 InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
734 manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
737 void updateLangButton() {
738 final LanguageResources languageResources =
739 DictionaryApplication.isoCodeToResources.get(index.shortName);
740 if (languageResources != null && languageResources.flagId != 0) {
741 languageButton.setImageResource(languageResources.flagId);
743 if (indexIndex % 2 == 0) {
744 languageButton.setImageResource(android.R.drawable.ic_media_next);
746 languageButton.setImageResource(android.R.drawable.ic_media_previous);
749 updateTTSLanguage(indexIndex);
752 private void updateTTSLanguage(int i) {
753 if (!ttsReady || index == null || textToSpeech == null) {
754 Log.d(LOG, "Can't updateTTSLanguage.");
757 final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
758 Log.d(LOG, "Setting TTS locale to: " + locale);
760 final int ttsResult = textToSpeech.setLanguage(locale);
761 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
762 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
763 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
765 } catch (Exception e) {
766 Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
770 void onLanguageButtonClick() {
771 if (dictionary.indices.size() == 1) {
772 // No need to work to switch indices.
775 if (currentSearchOperation != null) {
776 currentSearchOperation.interrupted.set(true);
777 currentSearchOperation = null;
779 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
780 searchView.getQuery().toString(), false);
783 void onLanguageButtonLongClick(final Context context) {
784 final Dialog dialog = new Dialog(context);
785 dialog.setContentView(R.layout.select_dictionary_dialog);
786 dialog.setTitle(R.string.selectDictionary);
788 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
790 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
791 final Button button = new Button(listView.getContext());
792 final String name = getString(R.string.dictionaryManager);
793 button.setText(name);
794 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
795 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
797 protected void onGo() {
799 DictionaryActivity.this.finish();
802 button.setOnClickListener(intentLauncher);
803 listView.addHeaderView(button);
805 listView.setAdapter(new BaseAdapter() {
807 public View getView(int position, View convertView, ViewGroup parent) {
808 final DictionaryInfo dictionaryInfo = getItem(position);
810 final LinearLayout result = new LinearLayout(parent.getContext());
812 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
813 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
814 final View button = application.createButton(parent.getContext(),
815 dictionaryInfo, indexInfo);
816 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
817 getLaunchIntent(getApplicationContext(),
818 application.getPath(dictionaryInfo.uncompressedFilename),
819 indexInfo.shortName, searchView.getQuery().toString())) {
821 protected void onGo() {
823 DictionaryActivity.this.finish();
826 button.setOnClickListener(intentLauncher);
827 if (i == indexIndex && dictFile != null &&
828 dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
829 button.setPressed(true);
831 result.addView(button);
834 final TextView nameView = new TextView(parent.getContext());
835 final String name = application
836 .getDictionaryName(dictionaryInfo.uncompressedFilename);
837 nameView.setText(name);
838 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
839 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
840 layoutParams.width = 0;
841 layoutParams.weight = 1.0f;
842 nameView.setLayoutParams(layoutParams);
843 nameView.setGravity(Gravity.CENTER_VERTICAL);
844 result.addView(nameView);
849 public long getItemId(int position) {
854 public DictionaryInfo getItem(int position) {
855 return installedDicts.get(position);
859 public int getCount() {
860 return installedDicts.size();
866 void onUpDownButton(final boolean up) {
870 final int firstVisibleRow = getListView().getFirstVisiblePosition();
871 final RowBase row = index.rows.get(firstVisibleRow);
872 final TokenRow tokenRow = row.getTokenRow(true);
873 final int destIndexEntry;
875 if (row != tokenRow) {
876 destIndexEntry = tokenRow.referenceIndex;
878 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
882 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
884 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
885 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
886 setSearchText(dest.token, false);
887 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
891 void onRandomWordButton() {
892 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
893 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
894 setSearchText(dest.token, false);
895 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
899 // --------------------------------------------------------------------------
901 // --------------------------------------------------------------------------
903 final Random random = new Random();
906 public boolean onCreateOptionsMenu(final Menu menu) {
908 if (PreferenceManager.getDefaultSharedPreferences(this)
909 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
911 nextWordMenuItem = menu.add(getString(R.string.nextWord))
912 .setIcon(R.drawable.arrow_down_float);
913 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
914 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
916 public boolean onMenuItemClick(MenuItem item) {
917 onUpDownButton(false);
923 previousWordMenuItem = menu.add(getString(R.string.previousWord))
924 .setIcon(R.drawable.arrow_up_float);
925 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
926 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
928 public boolean onMenuItemClick(MenuItem item) {
929 onUpDownButton(true);
935 randomWordMenuItem = menu.add(getString(R.string.randomWord));
936 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
938 public boolean onMenuItemClick(MenuItem item) {
939 onRandomWordButton();
944 application.onCreateGlobalOptionsMenu(this, menu);
947 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
948 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
949 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
950 public boolean onMenuItemClick(final MenuItem menuItem) {
951 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
959 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
960 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
961 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
962 public boolean onMenuItemClick(final MenuItem menuItem) {
963 final Context context = getListView().getContext();
964 final Dialog dialog = new Dialog(context);
965 dialog.setContentView(R.layout.about_dictionary_dialog);
966 final TextView textView = (TextView) dialog.findViewById(R.id.text);
968 final String name = application.getDictionaryName(dictFile.getName());
969 dialog.setTitle(name);
971 final StringBuilder builder = new StringBuilder();
972 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
973 dictionaryInfo.uncompressedBytes = dictFile.length();
974 if (dictionaryInfo != null) {
975 builder.append(dictionaryInfo.dictInfo).append("\n\n");
976 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
979 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
982 getString(R.string.dictionaryCreationTime,
983 dictionaryInfo.creationMillis)).append("\n");
984 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
985 builder.append("\n");
986 builder.append(getString(R.string.indexName, indexInfo.shortName))
989 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
992 builder.append("\n");
993 builder.append(getString(R.string.sources)).append("\n");
994 for (final EntrySource source : dictionary.sources) {
996 getString(R.string.sourceInfo, source.getName(),
997 source.getNumEntries())).append("\n");
1000 textView.setText(builder.toString());
1003 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
1004 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
1005 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
1006 dialog.getWindow().setAttributes(layoutParams);
1015 // --------------------------------------------------------------------------
1016 // Context Menu + clicks
1017 // --------------------------------------------------------------------------
1020 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1021 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
1022 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
1024 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
1025 wordList.getName()));
1027 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1028 public boolean onMenuItemClick(android.view.MenuItem item) {
1029 onAppendToWordList(row);
1034 final android.view.MenuItem share = menu.add("Share");
1035 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1036 public boolean onMenuItemClick(android.view.MenuItem item) {
1037 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
1038 shareIntent.setType("text/plain");
1039 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
1041 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
1042 row.getRawText(saveOnlyFirstSubentry));
1043 startActivity(shareIntent);
1048 final android.view.MenuItem copy = menu.add(android.R.string.copy);
1049 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1050 public boolean onMenuItemClick(android.view.MenuItem item) {
1056 if (selectedSpannableText != null) {
1057 final String selectedText = selectedSpannableText;
1058 final android.view.MenuItem searchForSelection = menu.add(getString(
1059 R.string.searchForSelection,
1060 selectedSpannableText));
1062 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1063 public boolean onMenuItemClick(android.view.MenuItem item) {
1064 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
1068 // Rats, this won't be shown:
1069 //searchForSelection.setIcon(R.drawable.abs__ic_search);
1072 if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
1073 final android.view.MenuItem speak = menu.add(R.string.speak);
1074 final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
1075 updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
1076 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1078 public boolean onMenuItemClick(android.view.MenuItem item) {
1079 textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
1080 new HashMap<String, String>());
1087 private void jumpToTextFromHyperLink(
1088 final String selectedText, final int defaultIndexToUse) {
1089 int indexToUse = -1;
1091 for (int i = 0; i < dictionary.indices.size(); ++i) {
1092 final Index index = dictionary.indices.get(i);
1093 if (indexPrepFinished) {
1094 System.out.println("Doing index lookup: on " + selectedText);
1095 final IndexEntry indexEntry = index.findExact(selectedText);
1096 if (indexEntry != null) {
1097 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1098 .getTokenRow(false);
1099 if (tokenRow != null && tokenRow.hasMainEntry) {
1105 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1108 if (numFound != 1 || indexToUse == -1) {
1109 indexToUse = defaultIndexToUse;
1111 // Without this extra delay, the call to jumpToRow that this
1112 // invokes doesn't always actually have any effect.
1113 final int actualIndexToUse = indexToUse;
1114 getListView().postDelayed(new Runnable() {
1117 setIndexAndSearchText(actualIndexToUse, selectedText, true);
1123 * Called when user clicks outside of search text, so that they can start
1124 * typing again immediately.
1126 void defocusSearchText() {
1127 // Log.d(LOG, "defocusSearchText");
1128 // Request focus so that if we start typing again, it clears the text
1130 getListView().requestFocus();
1132 // Visual indication that a new keystroke will clear the search text.
1133 // Doesn't seem to work unless searchText has focus.
1134 // searchView.selectAll();
1137 protected void onListItemClick(ListView l, View v, int row, long id) {
1138 defocusSearchText();
1139 if (clickOpensContextMenu && dictRaf != null) {
1144 @SuppressLint("SimpleDateFormat")
1145 void onAppendToWordList(final RowBase row) {
1146 defocusSearchText();
1148 final StringBuilder rawText = new StringBuilder();
1149 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1150 rawText.append(index.longName).append("\t");
1151 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1152 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1153 Log.d(LOG, "Writing : " + rawText);
1156 wordList.getParentFile().mkdirs();
1157 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1158 out.println(rawText.toString());
1160 } catch (Exception e) {
1161 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1162 Toast.makeText(this,
1163 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1164 Toast.LENGTH_LONG).show();
1169 @SuppressWarnings("deprecation")
1170 void onCopy(final RowBase row) {
1171 defocusSearchText();
1173 Log.d(LOG, "Copy, row=" + row);
1174 final StringBuilder result = new StringBuilder();
1175 result.append(row.getRawText(false));
1176 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1177 clipboardManager.setText(result.toString());
1178 Log.d(LOG, "Copied: " + result);
1182 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1183 if (event.getUnicodeChar() != 0) {
1184 if (!searchView.hasFocus()) {
1185 setSearchText("" + (char) event.getUnicodeChar(), true);
1186 searchView.requestFocus();
1190 if (keyCode == KeyEvent.KEYCODE_BACK) {
1191 // Log.d(LOG, "Clearing dictionary prefs.");
1192 // Pretend that we just autolaunched so that we won't do it again.
1193 // DictionaryManagerActivity.lastAutoLaunchMillis =
1194 // System.currentTimeMillis();
1196 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1197 Log.d(LOG, "Trying to hide soft keyboard.");
1198 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1199 View focus = getCurrentFocus();
1200 if (focus != null) {
1201 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1202 InputMethodManager.HIDE_NOT_ALWAYS);
1206 return super.onKeyDown(keyCode, event);
1209 private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
1210 Log.d(LOG, "Changing index to: " + newIndex);
1211 if (newIndex == -1) {
1212 Log.e(LOG, "Invalid index.");
1215 if (newIndex != indexIndex) {
1216 indexIndex = newIndex;
1217 index = dictionary.indices.get(indexIndex);
1218 indexAdapter = new IndexAdapter(index);
1219 setListAdapter(indexAdapter);
1220 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1221 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1224 setSearchText(newSearchText, true, hideKeyboard);
1227 private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
1228 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1229 // Disable the listener, because sometimes it doesn't work.
1230 searchView.setOnQueryTextListener(null);
1231 searchView.setQuery(text, false);
1232 moveCursorToRight();
1233 searchView.setOnQueryTextListener(onQueryTextListener);
1235 if (triggerSearch) {
1236 onSearchTextChange(text);
1239 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1245 private void setSearchText(final String text, final boolean triggerSearch) {
1246 setSearchText(text, triggerSearch, true);
1249 // private long cursorDelayMillis = 100;
1250 private void moveCursorToRight() {
1251 // if (searchText.getLayout() != null) {
1252 // cursorDelayMillis = 100;
1253 // // Surprising, but this can crash when you rotate...
1254 // Selection.moveToRightEdge(searchView.getQuery(),
1255 // searchText.getLayout());
1257 // uiHandler.postDelayed(new Runnable() {
1259 // public void run() {
1260 // moveCursorToRight();
1262 // }, cursorDelayMillis);
1263 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1267 // --------------------------------------------------------------------------
1269 // --------------------------------------------------------------------------
1271 private void searchFinished(final SearchOperation searchOperation) {
1272 if (searchOperation.interrupted.get()) {
1273 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1276 if (searchOperation != this.currentSearchOperation) {
1277 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1281 final Index.IndexEntry searchResult = searchOperation.searchResult;
1282 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1284 currentSearchOperation = null;
1285 uiHandler.postDelayed(new Runnable() {
1288 if (currentSearchOperation == null) {
1289 if (searchResult != null) {
1293 jumpToRow(searchResult.startRow);
1294 } else if (searchOperation.multiWordSearchResult != null) {
1295 // Multi-row search....
1296 setFiltered(searchOperation);
1298 throw new IllegalStateException("This should never happen.");
1301 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1307 private final void jumpToRow(final int row) {
1308 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1309 // getListView().requestFocusFromTouch();
1310 getListView().setSelectionFromTop(row, 0);
1311 getListView().setSelected(true);
1314 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1316 final class SearchOperation implements Runnable {
1318 final AtomicBoolean interrupted = new AtomicBoolean(false);
1320 final String searchText;
1322 List<String> searchTokens; // filled in for multiWord.
1326 long searchStartMillis;
1328 Index.IndexEntry searchResult;
1330 List<RowBase> multiWordSearchResult;
1332 boolean done = false;
1334 SearchOperation(final String searchText, final Index index) {
1335 this.searchText = StringUtil.normalizeWhitespace(searchText);
1339 public String toString() {
1340 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1346 searchStartMillis = System.currentTimeMillis();
1347 final String[] searchTokenArray = WHITESPACE.split(searchText);
1348 if (searchTokenArray.length == 1) {
1349 searchResult = index.findInsertionPoint(searchText, interrupted);
1351 searchTokens = Arrays.asList(searchTokenArray);
1352 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1356 "searchText=" + searchText + ", searchDuration="
1357 + (System.currentTimeMillis() - searchStartMillis)
1358 + ", interrupted=" + interrupted.get());
1359 if (!interrupted.get()) {
1360 uiHandler.post(new Runnable() {
1363 searchFinished(SearchOperation.this);
1367 Log.d(LOG, "interrupted, skipping searchFinished.");
1369 } catch (Exception e) {
1370 Log.e(LOG, "Failure during search (can happen during Activity close.");
1372 synchronized (this) {
1380 // --------------------------------------------------------------------------
1382 // --------------------------------------------------------------------------
1384 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1385 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1387 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1388 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1390 final class IndexAdapter extends BaseAdapter {
1392 private static final float PADDING_DEFAULT_DP = 8;
1394 private static final float PADDING_LARGE_DP = 16;
1398 final List<RowBase> rows;
1400 final Set<String> toHighlight;
1402 private int mPaddingDefault;
1404 private int mPaddingLarge;
1406 IndexAdapter(final Index index) {
1409 this.toHighlight = null;
1413 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1416 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1420 private void getMetrics() {
1421 // Get the screen's density scale
1422 final float scale = getResources().getDisplayMetrics().density;
1423 // Convert the dps to pixels, based on density scale
1424 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1425 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1429 public int getCount() {
1434 public RowBase getItem(int position) {
1435 return rows.get(position);
1439 public long getItemId(int position) {
1440 return getItem(position).index();
1444 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1445 final TableLayout result;
1446 if (convertView instanceof TableLayout) {
1447 result = (TableLayout) convertView;
1448 result.removeAllViews();
1450 result = new TableLayout(parent.getContext());
1452 final RowBase row = getItem(position);
1453 if (row instanceof PairEntry.Row) {
1454 return getView(position, (PairEntry.Row) row, parent, result);
1455 } else if (row instanceof TokenRow) {
1456 return getView((TokenRow) row, parent, result);
1457 } else if (row instanceof HtmlEntry.Row) {
1458 return getView((HtmlEntry.Row) row, parent, result);
1460 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1464 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1465 final TableLayout result) {
1466 final PairEntry entry = row.getEntry();
1467 final int rowCount = entry.pairs.size();
1469 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1470 layoutParams.weight = 0.5f;
1471 layoutParams.leftMargin = mPaddingLarge;
1473 for (int r = 0; r < rowCount; ++r) {
1474 final TableRow tableRow = new TableRow(result.getContext());
1476 final TextView col1 = new TextView(tableRow.getContext());
1477 final TextView col2 = new TextView(tableRow.getContext());
1479 // Set the columns in the table.
1481 final TextView bullet = new TextView(tableRow.getContext());
1482 bullet.setText(" • ");
1483 tableRow.addView(bullet);
1485 tableRow.addView(col1, layoutParams);
1486 final TextView margin = new TextView(tableRow.getContext());
1487 margin.setText(" ");
1488 tableRow.addView(margin);
1490 final TextView bullet = new TextView(tableRow.getContext());
1491 bullet.setText(" • ");
1492 tableRow.addView(bullet);
1494 tableRow.addView(col2, layoutParams);
1498 // Set what's in the columns.
1500 final Pair pair = entry.pairs.get(r);
1501 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1502 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1504 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1505 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1507 // Bold the token instances in col1.
1508 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1509 .singleton(row.getTokenRow(true).getToken());
1510 final Spannable col1Spannable = (Spannable) col1.getText();
1511 for (final String token : toBold) {
1513 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1514 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1515 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1516 startPos += token.length();
1520 createTokenLinkSpans(col1, col1Spannable, col1Text);
1521 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1523 col1.setTypeface(typeface);
1524 col2.setTypeface(typeface);
1525 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1526 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1527 // col2.setBackgroundResource(theme.otherLangBg);
1529 if (index.swapPairEntries) {
1530 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1531 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1533 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1534 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1537 result.addView(tableRow);
1540 // Because we have a Button inside a ListView row:
1541 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1542 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1543 result.setClickable(true);
1544 result.setFocusable(true);
1545 result.setLongClickable(true);
1546 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1548 result.setBackgroundResource(theme.normalRowBg);
1550 result.setOnClickListener(new TextView.OnClickListener() {
1552 public void onClick(View v) {
1553 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1560 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1561 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1562 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1563 final Context context = parent.getContext();
1565 final TableRow tableRow = new TableRow(result.getContext());
1566 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1567 : theme.tokenRowOtherBg);
1569 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1571 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1573 result.addView(tableRow);
1575 // Make it so we can long-click on these token rows, too:
1576 final TextView textView = new TextView(context);
1577 textView.setText(text, BufferType.SPANNABLE);
1578 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1579 textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1580 result.setLongClickable(true);
1583 // textView.setTextColor(android.R.color.secondary_text_light);
1584 textView.setTypeface(typeface);
1585 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1587 textView.setTextAppearance(context, theme.tokenRowFg);
1588 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1590 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1594 textView.setLayoutParams(lp);
1595 tableRow.addView(textView);
1597 if (!htmlEntries.isEmpty()) {
1598 final ClickableSpan clickableSpan = new ClickableSpan() {
1600 public void onClick(View widget) {
1603 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1604 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1605 result.setClickable(true);
1606 textView.setClickable(true);
1607 textView.setMovementMethod(LinkMovementMethod.getInstance());
1608 textView.setOnClickListener(new OnClickListener() {
1610 public void onClick(View v) {
1611 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1612 // Log.d(LOG, "html=" + html);
1613 startActivityForResult(
1614 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1615 "<html><head></head><body>%s</body></html>", html),
1616 htmlTextToHighlight, false),
1624 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1625 final IndexEntry indexEntry = row.getIndexEntry();
1626 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1627 indexEntry.htmlEntries, null, parent, result);
1630 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1631 final HtmlEntry htmlEntry = row.getEntry();
1632 final TokenRow tokenRow = row.getTokenRow(true);
1633 return getPossibleLinkToHtmlEntryView(false,
1634 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1635 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1641 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1643 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1644 final String text) {
1645 // Saw from the source code that LinkMovementMethod sets the selection!
1646 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1647 textView.setMovementMethod(LinkMovementMethod.getInstance());
1648 final Matcher matcher = CHAR_DASH.matcher(text);
1649 while (matcher.find()) {
1650 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1652 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1656 String selectedSpannableText = null;
1658 int selectedSpannableIndex = -1;
1661 public boolean onTouchEvent(MotionEvent event) {
1662 selectedSpannableText = null;
1663 selectedSpannableIndex = -1;
1664 return super.onTouchEvent(event);
1667 private class TextViewLongClickListener implements OnLongClickListener {
1670 private TextViewLongClickListener(final int index) {
1675 public boolean onLongClick(final View v) {
1676 final TextView textView = (TextView) v;
1677 final int start = textView.getSelectionStart();
1678 final int end = textView.getSelectionEnd();
1679 if (start >= 0 && end >= 0) {
1680 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1681 selectedSpannableIndex = index;
1687 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1690 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1693 // --------------------------------------------------------------------------
1695 // --------------------------------------------------------------------------
1697 void onSearchTextChange(final String text) {
1698 if ("thadolina".equals(text)) {
1699 final Dialog dialog = new Dialog(getListView().getContext());
1700 dialog.setContentView(R.layout.thadolina_dialog);
1701 dialog.setTitle("Ti amo, amore mio!");
1702 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1703 imageView.setOnClickListener(new OnClickListener() {
1705 public void onClick(View v) {
1706 final Intent intent = new Intent(Intent.ACTION_VIEW);
1707 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1708 startActivity(intent);
1713 if (dictRaf == null) {
1714 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1718 // if (!searchView.hasFocus()) {
1719 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1722 Log.d(LOG, "onSearchTextChange: " + text);
1723 if (currentSearchOperation != null) {
1724 Log.d(LOG, "Interrupting currentSearchOperation.");
1725 currentSearchOperation.interrupted.set(true);
1727 currentSearchOperation = new SearchOperation(text, index);
1728 searchExecutor.execute(currentSearchOperation);
1729 ((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
1732 // --------------------------------------------------------------------------
1733 // Filtered results.
1734 // --------------------------------------------------------------------------
1736 boolean isFiltered() {
1737 return rowsToShow != null;
1740 void setFiltered(final SearchOperation searchOperation) {
1741 if (nextWordMenuItem != null) {
1742 nextWordMenuItem.setEnabled(false);
1743 previousWordMenuItem.setEnabled(false);
1745 rowsToShow = searchOperation.multiWordSearchResult;
1746 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1749 void clearFiltered() {
1750 if (nextWordMenuItem != null) {
1751 nextWordMenuItem.setEnabled(true);
1752 previousWordMenuItem.setEnabled(true);
1754 setListAdapter(new IndexAdapter(index));