1 // Copyright 2011 Google Inc. All Rights Reserved.
2 // Some Parts Copyright 2013 Dominik Köppl
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 package com.hughes.android.dictionary;
17 import android.annotation.SuppressLint;
18 import android.app.Dialog;
19 import android.app.SearchManager;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.SharedPreferences;
23 import android.graphics.Color;
24 import android.graphics.Typeface;
25 import android.net.Uri;
26 import android.os.Bundle;
27 import android.os.Handler;
28 import android.preference.PreferenceManager;
29 import android.speech.tts.TextToSpeech;
30 import android.speech.tts.TextToSpeech.OnInitListener;
31 import android.support.v4.view.MenuItemCompat;
32 import android.support.v7.app.ActionBar;
33 import android.support.v7.app.ActionBarActivity;
34 import android.support.v7.widget.SearchView;
35 import android.support.v7.widget.SearchView.OnQueryTextListener;
36 import android.support.v7.widget.Toolbar;
37 import android.text.ClipboardManager;
38 import android.text.InputType;
39 import android.text.Spannable;
40 import android.text.method.LinkMovementMethod;
41 import android.text.style.ClickableSpan;
42 import android.text.style.StyleSpan;
43 import android.util.Log;
44 import android.util.TypedValue;
45 import android.view.ContextMenu;
46 import android.view.ContextMenu.ContextMenuInfo;
47 import android.view.Gravity;
48 import android.view.KeyEvent;
49 import android.view.Menu;
50 import android.view.MenuItem;
51 import android.view.MenuItem.OnMenuItemClickListener;
52 import android.view.MotionEvent;
53 import android.view.View;
54 import android.view.View.OnClickListener;
55 import android.view.View.OnLongClickListener;
56 import android.view.ViewGroup;
57 import android.view.WindowManager;
58 import android.view.inputmethod.EditorInfo;
59 import android.view.inputmethod.InputMethodManager;
60 import android.widget.AdapterView;
61 import android.widget.AdapterView.AdapterContextMenuInfo;
62 import android.widget.AdapterView.OnItemClickListener;
63 import android.widget.BaseAdapter;
64 import android.widget.Button;
65 import android.widget.FrameLayout;
66 import android.widget.ImageButton;
67 import android.widget.ImageView;
68 import android.widget.ImageView.ScaleType;
69 import android.widget.LinearLayout;
70 import android.widget.ListAdapter;
71 import android.widget.ListView;
72 import android.widget.TableLayout;
73 import android.widget.TableRow;
74 import android.widget.TextView;
75 import android.widget.TextView.BufferType;
76 import android.widget.Toast;
78 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
79 import com.hughes.android.dictionary.engine.Dictionary;
80 import com.hughes.android.dictionary.engine.EntrySource;
81 import com.hughes.android.dictionary.engine.HtmlEntry;
82 import com.hughes.android.dictionary.engine.Index;
83 import com.hughes.android.dictionary.engine.Index.IndexEntry;
84 import com.hughes.android.dictionary.engine.Language.LanguageResources;
85 import com.hughes.android.dictionary.engine.PairEntry;
86 import com.hughes.android.dictionary.engine.PairEntry.Pair;
87 import com.hughes.android.dictionary.engine.RowBase;
88 import com.hughes.android.dictionary.engine.TokenRow;
89 import com.hughes.android.dictionary.engine.TransliteratorManager;
90 import com.hughes.android.util.IntentLauncher;
91 import com.hughes.android.util.NonLinkClickableSpan;
92 import com.hughes.util.StringUtil;
95 import java.io.FileWriter;
96 import java.io.IOException;
97 import java.io.PrintWriter;
98 import java.io.RandomAccessFile;
99 import java.text.SimpleDateFormat;
100 import java.util.Arrays;
101 import java.util.Collections;
102 import java.util.Date;
103 import java.util.HashMap;
104 import java.util.LinkedHashSet;
105 import java.util.List;
106 import java.util.Locale;
107 import java.util.Random;
108 import java.util.Set;
109 import java.util.concurrent.Executor;
110 import java.util.concurrent.Executors;
111 import java.util.concurrent.ThreadFactory;
112 import java.util.concurrent.atomic.AtomicBoolean;
113 import java.util.regex.Matcher;
114 import java.util.regex.Pattern;
116 public class DictionaryActivity extends ActionBarActivity {
118 static final String LOG = "QuickDic";
120 DictionaryApplication application;
122 File dictFile = null;
123 RandomAccessFile dictRaf = null;
125 Dictionary dictionary = null;
131 List<RowBase> rowsToShow = null; // if not null, just show these rows.
133 final Random rand = new Random();
135 final Handler uiHandler = new Handler();
137 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
139 public Thread newThread(Runnable r) {
140 return new Thread(r, "searchExecutor");
144 private SearchOperation currentSearchOperation = null;
146 TextToSpeech textToSpeech;
147 volatile boolean ttsReady;
150 DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
151 int textColorFg = Color.BLACK;
154 private ListView listView;
155 private ListView getListView() {
156 if (listView == null) {
157 listView = (ListView)findViewById(android.R.id.list);
162 private void setListAdapter(ListAdapter adapter) {
163 getListView().setAdapter(adapter);
166 private ListAdapter getListAdapter() {
167 return getListView().getAdapter();
170 SearchView searchView;
171 ImageButton languageButton;
172 SearchView.OnQueryTextListener onQueryTextListener;
174 MenuItem nextWordMenuItem, previousWordMenuItem, randomWordMenuItem;
177 private File wordList = null;
178 private boolean saveOnlyFirstSubentry = false;
179 private boolean clickOpensContextMenu = false;
181 // Visible for testing.
182 ListAdapter indexAdapter = null;
185 * For some languages, loading the transliterators used in this search takes
186 * a long time, so we fire it up on a different thread, and don't invoke it
187 * from the main thread until it's already finished once.
189 private volatile boolean indexPrepFinished = false;
191 public DictionaryActivity() {
194 public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
195 final String searchToken) {
196 final Intent intent = new Intent(c, DictionaryActivity.class);
197 intent.putExtra(C.DICT_FILE, dictFile.getPath());
198 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
199 intent.putExtra(C.SEARCH_TOKEN, searchToken);
204 protected void onSaveInstanceState(final Bundle outState) {
205 super.onSaveInstanceState(outState);
206 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
207 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
208 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
212 public void onCreate(Bundle savedInstanceState) {
213 // This needs to be before super.onCreate, otherwise ActionbarSherlock
214 // doesn't makes the background of the actionbar white when you're
215 // in the dark theme.
216 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
218 Log.d(LOG, "onCreate:" + this);
219 super.onCreate(savedInstanceState);
221 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
223 // Don't auto-launch if this fails.
224 prefs.edit().remove(C.DICT_FILE).commit();
226 setContentView(R.layout.dictionary_activity);
228 application = (DictionaryApplication) getApplication();
229 theme = application.getSelectedTheme();
230 textColorFg = getResources().getColor(theme.tokenRowFgColor);
232 final Intent intent = getIntent();
233 String intentAction = intent.getAction();
235 * @author Dominik Köppl Querying the Intent
236 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
237 * Arguments: SearchManager.QUERY -> the phrase to search from
238 * -> language in which the phrase is written to -> to which
239 * language shall be translated
241 if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
243 String query = intent.getStringExtra(SearchManager.QUERY);
244 String from = intent.getStringExtra("from");
246 from = from.toLowerCase(Locale.US);
247 String to = intent.getStringExtra("to");
249 to = to.toLowerCase(Locale.US);
252 getIntent().putExtra(C.SEARCH_TOKEN, query);
254 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
256 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
257 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
258 for (DictionaryInfo info : dicts)
260 boolean hasFrom = from == null;
261 boolean hasTo = to == null;
262 for (IndexInfo index : info.indexInfos)
264 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
266 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
269 if (hasFrom && hasTo)
274 for (; which_index < info.indexInfos.size(); ++which_index)
276 if (info.indexInfos.get(which_index).shortName.toLowerCase(
277 Locale.US).equals(from))
280 intent.putExtra(C.INDEX_SHORT_NAME,
281 info.indexInfos.get(which_index).shortName);
284 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
293 * @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
294 * simple query Arguments follow from android standard (see
297 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
299 String query = intent.getStringExtra(SearchManager.QUERY);
301 getIntent().putExtra(C.SEARCH_TOKEN, query);
304 * @author Dominik Köppl If no dictionary is chosen, use the default
305 * dictionary specified in the preferences If this step does
306 * fail (no default directory specified), show a toast and
309 if (intent.getStringExtra(C.DICT_FILE) == null)
311 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
312 if (dictfile != null)
313 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
315 String dictFilename = intent.getStringExtra(C.DICT_FILE);
317 if (dictFilename == null)
319 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
320 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
324 if (dictFilename != null)
325 dictFile = new File(dictFilename);
328 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
330 public void onInit(int status) {
332 updateTTSLanguage(indexIndex);
337 final String name = application.getDictionaryName(dictFile.getName());
338 this.setTitle("QuickDic: " + name);
339 dictRaf = new RandomAccessFile(dictFile, "r");
340 dictionary = new Dictionary(dictRaf);
341 } catch (Exception e) {
342 Log.e(LOG, "Unable to load dictionary.", e);
343 if (dictRaf != null) {
346 } catch (IOException e1) {
347 Log.e(LOG, "Unable to close dictRaf.", e1);
351 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
352 Toast.LENGTH_LONG).show();
353 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
357 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
358 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
359 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
362 for (int i = 0; i < dictionary.indices.size(); ++i) {
363 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
368 Log.d(LOG, "Loading index " + indexIndex);
369 index = dictionary.indices.get(indexIndex);
370 setListAdapter(new IndexAdapter(index));
372 // Pre-load the collators.
373 new Thread(new Runnable() {
375 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
376 final long startMillis = System.currentTimeMillis();
378 TransliteratorManager.init(new TransliteratorManager.Callback() {
380 public void onTransliteratorReady() {
381 uiHandler.post(new Runnable() {
384 onSearchTextChange(searchView.getQuery().toString());
390 for (final Index index : dictionary.indices) {
391 final String searchToken = index.sortedIndexEntries.get(0).token;
392 final IndexEntry entry = index.findExact(searchToken);
393 if (entry == null || !searchToken.equals(entry.token)) {
394 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
397 indexPrepFinished = true;
398 } catch (Exception e) {
400 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
402 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
406 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
407 if ("SYSTEM".equals(fontName)) {
408 typeface = Typeface.DEFAULT;
409 } else if ("SERIF".equals(fontName)) {
410 typeface = Typeface.SERIF;
411 } else if ("SANS_SERIF".equals(fontName)) {
412 typeface = Typeface.SANS_SERIF;
413 } else if ("MONOSPACE".equals(fontName)) {
414 typeface = Typeface.MONOSPACE;
416 if ("FreeSerif.ttf.jpg".equals(fontName)) {
417 fontName = "FreeSerif.otf.jpg";
420 typeface = Typeface.createFromAsset(getAssets(), fontName);
421 } catch (Exception e) {
422 Log.w(LOG, "Exception trying to use typeface, using default.", e);
423 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
424 Toast.LENGTH_LONG).show();
427 if (typeface == null) {
428 Log.w(LOG, "Unable to create typeface, using default.");
429 typeface = Typeface.DEFAULT;
431 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
433 fontSizeSp = Integer.parseInt(fontSize.trim());
434 } catch (NumberFormatException e) {
439 registerForContextMenu(getListView());
442 wordList = application.getWordListFile();
443 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
445 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
447 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
449 onCreateSetupActionBarAndSearchView();
451 // Set the search text from the intent, then the saved state.
452 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
453 if (savedInstanceState != null) {
454 text = savedInstanceState.getString(C.SEARCH_TOKEN);
459 setSearchText(text, true);
460 Log.d(LOG, "Trying to restore searchText=" + text);
462 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
465 searchView.requestFocus();
467 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
468 // getListView().setCacheColorHint(0);
471 private void onCreateSetupActionBarAndSearchView() {
472 ActionBar actionBar = getSupportActionBar();
473 actionBar.setDisplayShowTitleEnabled(false);
474 actionBar.setDisplayShowHomeEnabled(false);
475 actionBar.setDisplayHomeAsUpEnabled(false);
477 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
479 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
480 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
481 customSearchView.setLayoutParams(layoutParams);
483 listView.setOnItemClickListener(new OnItemClickListener() {
485 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
486 onListItemClick(getListView(), view, row, id);
490 languageButton = new ImageButton(customSearchView.getContext());
491 languageButton.setScaleType(ScaleType.FIT_CENTER);
492 languageButton.setOnClickListener(new OnClickListener() {
494 public void onClick(View arg0) {
495 onLanguageButtonClick();
498 languageButton.setOnLongClickListener(new OnLongClickListener() {
500 public boolean onLongClick(View v) {
501 onLanguageButtonLongClick(v.getContext());
505 languageButton.setAdjustViewBounds(true);
506 LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
507 customSearchView.addView(languageButton, lpb);
509 searchView = new SearchView(getSupportActionBar().getThemedContext());
510 searchView.setIconifiedByDefault(false);
511 // searchView.setIconified(false); // puts the magnifying glass in the
513 searchView.setQueryHint(getString(R.string.searchText));
514 searchView.setSubmitButtonEnabled(false);
515 searchView.setInputType(InputType.TYPE_CLASS_TEXT);
516 searchView.setImeOptions(
517 EditorInfo.IME_ACTION_DONE |
518 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
519 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
521 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
522 onQueryTextListener = new OnQueryTextListener() {
524 public boolean onQueryTextSubmit(String query) {
525 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
531 public boolean onQueryTextChange(String newText) {
532 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
533 onSearchTextChange(searchView.getQuery().toString());
537 searchView.setOnQueryTextListener(onQueryTextListener);
538 searchView.setFocusable(true);
539 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
540 FrameLayout.LayoutParams.WRAP_CONTENT, 1);
541 customSearchView.addView(searchView, lp);
543 actionBar.setCustomView(customSearchView);
544 actionBar.setDisplayShowCustomEnabled(true);
546 // Avoid wasting space on large left inset
547 Toolbar tb = (Toolbar)customSearchView.getParent();
548 tb.setContentInsetsRelative(0, 0);
552 protected void onResume() {
553 Log.d(LOG, "onResume");
555 if (PreferenceActivity.prefsMightHaveChanged) {
556 PreferenceActivity.prefsMightHaveChanged = false;
558 startActivity(getIntent());
564 protected void onPause() {
570 * Invoked when MyWebView returns, since the user might have clicked some
571 * hypertext in the MyWebView.
573 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
574 super.onActivityResult(requestCode, resultCode, result);
575 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
576 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
577 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
581 private static void setDictionaryPrefs(final Context context, final File dictFile,
582 final String indexShortName, final String searchToken) {
583 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
585 prefs.putString(C.DICT_FILE, dictFile.getPath());
586 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
587 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
592 protected void onDestroy() {
594 if (dictRaf == null) {
598 final SearchOperation searchOperation = currentSearchOperation;
599 currentSearchOperation = null;
601 // Before we close the RAF, we have to wind the current search down.
602 if (searchOperation != null) {
603 Log.d(LOG, "Interrupting search to shut down.");
604 currentSearchOperation = null;
605 searchOperation.interrupted.set(true);
609 Log.d(LOG, "Closing RAF.");
611 } catch (IOException e) {
612 Log.e(LOG, "Failed to close dictionary", e);
617 // --------------------------------------------------------------------------
619 // --------------------------------------------------------------------------
621 private void showKeyboard() {
622 // For some reason, this doesn't always work the first time.
623 // One way to replicate the problem:
624 // Press the "task switch" button repeatedly to pause and resume
625 for (int delay = 1; delay <= 101; delay += 100) {
626 searchView.postDelayed(new Runnable() {
629 Log.d(LOG, "Trying to show soft keyboard.");
630 final boolean searchTextHadFocus = searchView.hasFocus();
631 searchView.requestFocusFromTouch();
632 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
633 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
634 if (!searchTextHadFocus) {
642 private void hideKeyboard() {
643 Log.d(LOG, "Hide soft keyboard.");
644 searchView.clearFocus();
645 InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
646 manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
649 void updateLangButton() {
650 final LanguageResources languageResources =
651 DictionaryApplication.isoCodeToResources.get(index.shortName);
652 if (languageResources != null && languageResources.flagId != 0) {
653 languageButton.setImageResource(languageResources.flagId);
655 if (indexIndex % 2 == 0) {
656 languageButton.setImageResource(android.R.drawable.ic_media_next);
658 languageButton.setImageResource(android.R.drawable.ic_media_previous);
661 updateTTSLanguage(indexIndex);
664 private void updateTTSLanguage(int i) {
665 if (!ttsReady || index == null || textToSpeech == null) {
666 Log.d(LOG, "Can't updateTTSLanguage.");
669 final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
670 Log.d(LOG, "Setting TTS locale to: " + locale);
671 final int ttsResult = textToSpeech.setLanguage(locale);
672 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
673 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
674 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
678 void onLanguageButtonClick() {
679 if (dictionary.indices.size() == 1) {
680 // No need to work to switch indices.
683 if (currentSearchOperation != null) {
684 currentSearchOperation.interrupted.set(true);
685 currentSearchOperation = null;
687 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
688 searchView.getQuery().toString());
691 void onLanguageButtonLongClick(final Context context) {
692 final Dialog dialog = new Dialog(context);
693 dialog.setContentView(R.layout.select_dictionary_dialog);
694 dialog.setTitle(R.string.selectDictionary);
696 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
698 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
699 final Button button = new Button(listView.getContext());
700 final String name = getString(R.string.dictionaryManager);
701 button.setText(name);
702 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
703 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
705 protected void onGo() {
707 DictionaryActivity.this.finish();
710 button.setOnClickListener(intentLauncher);
711 listView.addHeaderView(button);
713 listView.setAdapter(new BaseAdapter() {
715 public View getView(int position, View convertView, ViewGroup parent) {
716 final DictionaryInfo dictionaryInfo = getItem(position);
718 final LinearLayout result = new LinearLayout(parent.getContext());
720 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
721 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
722 final View button = application.createButton(parent.getContext(),
723 dictionaryInfo, indexInfo);
724 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
725 getLaunchIntent(getApplicationContext(),
726 application.getPath(dictionaryInfo.uncompressedFilename),
727 indexInfo.shortName, searchView.getQuery().toString())) {
729 protected void onGo() {
731 DictionaryActivity.this.finish();
734 button.setOnClickListener(intentLauncher);
735 if (i == indexIndex && dictFile != null &&
736 dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
737 button.setPressed(true);
739 result.addView(button);
742 final TextView nameView = new TextView(parent.getContext());
743 final String name = application
744 .getDictionaryName(dictionaryInfo.uncompressedFilename);
745 nameView.setText(name);
746 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
747 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
748 layoutParams.width = 0;
749 layoutParams.weight = 1.0f;
750 nameView.setLayoutParams(layoutParams);
751 nameView.setGravity(Gravity.CENTER_VERTICAL);
752 result.addView(nameView);
757 public long getItemId(int position) {
762 public DictionaryInfo getItem(int position) {
763 return installedDicts.get(position);
767 public int getCount() {
768 return installedDicts.size();
774 void onUpDownButton(final boolean up) {
778 final int firstVisibleRow = getListView().getFirstVisiblePosition();
779 final RowBase row = index.rows.get(firstVisibleRow);
780 final TokenRow tokenRow = row.getTokenRow(true);
781 final int destIndexEntry;
783 if (row != tokenRow) {
784 destIndexEntry = tokenRow.referenceIndex;
786 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
790 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
792 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
793 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
794 setSearchText(dest.token, false);
795 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
799 void onRandomWordButton() {
800 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
801 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
802 setSearchText(dest.token, false);
803 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
807 // --------------------------------------------------------------------------
809 // --------------------------------------------------------------------------
811 final Random random = new Random();
814 public boolean onCreateOptionsMenu(final Menu menu) {
816 if (PreferenceManager.getDefaultSharedPreferences(this)
817 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
819 nextWordMenuItem = menu.add(getString(R.string.nextWord))
820 .setIcon(R.drawable.arrow_down_float);
821 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
822 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
824 public boolean onMenuItemClick(MenuItem item) {
825 onUpDownButton(false);
831 previousWordMenuItem = menu.add(getString(R.string.previousWord))
832 .setIcon(R.drawable.arrow_up_float);
833 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
834 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
836 public boolean onMenuItemClick(MenuItem item) {
837 onUpDownButton(true);
843 randomWordMenuItem = menu.add(getString(R.string.randomWord));
844 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
846 public boolean onMenuItemClick(MenuItem item) {
847 onRandomWordButton();
852 application.onCreateGlobalOptionsMenu(this, menu);
855 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
856 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
857 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
858 public boolean onMenuItemClick(final MenuItem menuItem) {
859 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
867 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
868 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
869 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
870 public boolean onMenuItemClick(final MenuItem menuItem) {
871 final Context context = getListView().getContext();
872 final Dialog dialog = new Dialog(context);
873 dialog.setContentView(R.layout.about_dictionary_dialog);
874 final TextView textView = (TextView) dialog.findViewById(R.id.text);
876 final String name = application.getDictionaryName(dictFile.getName());
877 dialog.setTitle(name);
879 final StringBuilder builder = new StringBuilder();
880 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
881 dictionaryInfo.uncompressedBytes = dictFile.length();
882 if (dictionaryInfo != null) {
883 builder.append(dictionaryInfo.dictInfo).append("\n\n");
884 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
887 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
890 getString(R.string.dictionaryCreationTime,
891 dictionaryInfo.creationMillis)).append("\n");
892 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
893 builder.append("\n");
894 builder.append(getString(R.string.indexName, indexInfo.shortName))
897 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
900 builder.append("\n");
901 builder.append(getString(R.string.sources)).append("\n");
902 for (final EntrySource source : dictionary.sources) {
904 getString(R.string.sourceInfo, source.getName(),
905 source.getNumEntries())).append("\n");
908 textView.setText(builder.toString());
911 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
912 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
913 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
914 dialog.getWindow().setAttributes(layoutParams);
923 // --------------------------------------------------------------------------
924 // Context Menu + clicks
925 // --------------------------------------------------------------------------
928 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
929 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
930 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
932 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
933 wordList.getName()));
935 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
936 public boolean onMenuItemClick(android.view.MenuItem item) {
937 onAppendToWordList(row);
942 final android.view.MenuItem share = menu.add("Share");
943 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
944 public boolean onMenuItemClick(android.view.MenuItem item) {
945 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
946 shareIntent.setType("text/plain");
947 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
949 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
950 row.getRawText(saveOnlyFirstSubentry));
951 startActivity(shareIntent);
956 final android.view.MenuItem copy = menu.add(android.R.string.copy);
957 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
958 public boolean onMenuItemClick(android.view.MenuItem item) {
964 if (selectedSpannableText != null) {
965 final String selectedText = selectedSpannableText;
966 final android.view.MenuItem searchForSelection = menu.add(getString(
967 R.string.searchForSelection,
968 selectedSpannableText));
970 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
971 public boolean onMenuItemClick(android.view.MenuItem item) {
972 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
976 // Rats, this won't be shown:
977 //searchForSelection.setIcon(R.drawable.abs__ic_search);
980 if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
981 final android.view.MenuItem speak = menu.add(R.string.speak);
982 final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
983 updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
984 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
986 public boolean onMenuItemClick(android.view.MenuItem item) {
987 textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
988 new HashMap<String, String>());
995 private void jumpToTextFromHyperLink(
996 final String selectedText, final int defaultIndexToUse) {
999 for (int i = 0; i < dictionary.indices.size(); ++i) {
1000 final Index index = dictionary.indices.get(i);
1001 if (indexPrepFinished) {
1002 System.out.println("Doing index lookup: on " + selectedText);
1003 final IndexEntry indexEntry = index.findExact(selectedText);
1004 if (indexEntry != null) {
1005 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1006 .getTokenRow(false);
1007 if (tokenRow != null && tokenRow.hasMainEntry) {
1013 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1016 if (numFound != 1 || indexToUse == -1) {
1017 indexToUse = defaultIndexToUse;
1019 // Without this extra delay, the call to jumpToRow that this
1020 // invokes doesn't always actually have any effect.
1021 final int actualIndexToUse = indexToUse;
1022 getListView().postDelayed(new Runnable() {
1025 setIndexAndSearchText(actualIndexToUse, selectedText);
1031 * Called when user clicks outside of search text, so that they can start
1032 * typing again immediately.
1034 void defocusSearchText() {
1035 // Log.d(LOG, "defocusSearchText");
1036 // Request focus so that if we start typing again, it clears the text
1038 getListView().requestFocus();
1040 // Visual indication that a new keystroke will clear the search text.
1041 // Doesn't seem to work unless searchText has focus.
1042 // searchView.selectAll();
1045 protected void onListItemClick(ListView l, View v, int row, long id) {
1046 defocusSearchText();
1047 if (clickOpensContextMenu && dictRaf != null) {
1052 @SuppressLint("SimpleDateFormat")
1053 void onAppendToWordList(final RowBase row) {
1054 defocusSearchText();
1056 final StringBuilder rawText = new StringBuilder();
1057 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1058 rawText.append(index.longName).append("\t");
1059 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1060 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1061 Log.d(LOG, "Writing : " + rawText);
1064 wordList.getParentFile().mkdirs();
1065 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1066 out.println(rawText.toString());
1068 } catch (Exception e) {
1069 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1070 Toast.makeText(this,
1071 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1072 Toast.LENGTH_LONG).show();
1077 @SuppressWarnings("deprecation")
1078 void onCopy(final RowBase row) {
1079 defocusSearchText();
1081 Log.d(LOG, "Copy, row=" + row);
1082 final StringBuilder result = new StringBuilder();
1083 result.append(row.getRawText(false));
1084 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1085 clipboardManager.setText(result.toString());
1086 Log.d(LOG, "Copied: " + result);
1090 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1091 if (event.getUnicodeChar() != 0) {
1092 if (!searchView.hasFocus()) {
1093 setSearchText("" + (char) event.getUnicodeChar(), true);
1094 searchView.requestFocus();
1098 if (keyCode == KeyEvent.KEYCODE_BACK) {
1099 // Log.d(LOG, "Clearing dictionary prefs.");
1100 // Pretend that we just autolaunched so that we won't do it again.
1101 // DictionaryManagerActivity.lastAutoLaunchMillis =
1102 // System.currentTimeMillis();
1104 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1105 Log.d(LOG, "Trying to hide soft keyboard.");
1106 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1107 View focus = getCurrentFocus();
1108 if (focus != null) {
1109 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1110 InputMethodManager.HIDE_NOT_ALWAYS);
1114 return super.onKeyDown(keyCode, event);
1117 private void setIndexAndSearchText(int newIndex, String newSearchText) {
1118 Log.d(LOG, "Changing index to: " + newIndex);
1119 if (newIndex == -1) {
1120 Log.e(LOG, "Invalid index.");
1123 if (newIndex != indexIndex) {
1124 indexIndex = newIndex;
1125 index = dictionary.indices.get(indexIndex);
1126 indexAdapter = new IndexAdapter(index);
1127 setListAdapter(indexAdapter);
1128 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1129 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1132 setSearchText(newSearchText, true);
1135 private void setSearchText(final String text, final boolean triggerSearch) {
1136 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1137 // Disable the listener, because sometimes it doesn't work.
1138 searchView.setOnQueryTextListener(null);
1139 searchView.setQuery(text, false);
1140 moveCursorToRight();
1141 searchView.setOnQueryTextListener(onQueryTextListener);
1143 // Hide search icon once text is entered
1144 searchView.setIconifiedByDefault(text.length() > 0);
1145 searchView.setIconified(false);
1147 if (triggerSearch) {
1148 onSearchTextChange(text);
1151 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1155 // private long cursorDelayMillis = 100;
1156 private void moveCursorToRight() {
1157 // if (searchText.getLayout() != null) {
1158 // cursorDelayMillis = 100;
1159 // // Surprising, but this can crash when you rotate...
1160 // Selection.moveToRightEdge(searchView.getQuery(),
1161 // searchText.getLayout());
1163 // uiHandler.postDelayed(new Runnable() {
1165 // public void run() {
1166 // moveCursorToRight();
1168 // }, cursorDelayMillis);
1169 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1173 // --------------------------------------------------------------------------
1175 // --------------------------------------------------------------------------
1177 private void searchFinished(final SearchOperation searchOperation) {
1178 if (searchOperation.interrupted.get()) {
1179 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1182 if (searchOperation != this.currentSearchOperation) {
1183 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1187 final Index.IndexEntry searchResult = searchOperation.searchResult;
1188 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1190 currentSearchOperation = null;
1191 uiHandler.postDelayed(new Runnable() {
1194 if (currentSearchOperation == null) {
1195 if (searchResult != null) {
1199 jumpToRow(searchResult.startRow);
1200 } else if (searchOperation.multiWordSearchResult != null) {
1201 // Multi-row search....
1202 setFiltered(searchOperation);
1204 throw new IllegalStateException("This should never happen.");
1207 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1213 private final void jumpToRow(final int row) {
1214 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1215 // getListView().requestFocusFromTouch();
1216 getListView().setSelectionFromTop(row, 0);
1217 getListView().setSelected(true);
1220 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1222 final class SearchOperation implements Runnable {
1224 final AtomicBoolean interrupted = new AtomicBoolean(false);
1226 final String searchText;
1228 List<String> searchTokens; // filled in for multiWord.
1232 long searchStartMillis;
1234 Index.IndexEntry searchResult;
1236 List<RowBase> multiWordSearchResult;
1238 boolean done = false;
1240 SearchOperation(final String searchText, final Index index) {
1241 this.searchText = StringUtil.normalizeWhitespace(searchText);
1245 public String toString() {
1246 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1252 searchStartMillis = System.currentTimeMillis();
1253 final String[] searchTokenArray = WHITESPACE.split(searchText);
1254 if (searchTokenArray.length == 1) {
1255 searchResult = index.findInsertionPoint(searchText, interrupted);
1257 searchTokens = Arrays.asList(searchTokenArray);
1258 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1262 "searchText=" + searchText + ", searchDuration="
1263 + (System.currentTimeMillis() - searchStartMillis)
1264 + ", interrupted=" + interrupted.get());
1265 if (!interrupted.get()) {
1266 uiHandler.post(new Runnable() {
1269 searchFinished(SearchOperation.this);
1273 Log.d(LOG, "interrupted, skipping searchFinished.");
1275 } catch (Exception e) {
1276 Log.e(LOG, "Failure during search (can happen during Activity close.");
1278 synchronized (this) {
1286 // --------------------------------------------------------------------------
1288 // --------------------------------------------------------------------------
1290 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1291 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1293 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1294 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1296 final class IndexAdapter extends BaseAdapter {
1298 private static final float PADDING_DEFAULT_DP = 8;
1300 private static final float PADDING_LARGE_DP = 16;
1304 final List<RowBase> rows;
1306 final Set<String> toHighlight;
1308 private int mPaddingDefault;
1310 private int mPaddingLarge;
1312 IndexAdapter(final Index index) {
1315 this.toHighlight = null;
1319 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1322 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1326 private void getMetrics() {
1327 // Get the screen's density scale
1328 final float scale = getResources().getDisplayMetrics().density;
1329 // Convert the dps to pixels, based on density scale
1330 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1331 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1335 public int getCount() {
1340 public RowBase getItem(int position) {
1341 return rows.get(position);
1345 public long getItemId(int position) {
1346 return getItem(position).index();
1350 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1351 final TableLayout result;
1352 if (convertView instanceof TableLayout) {
1353 result = (TableLayout) convertView;
1354 result.removeAllViews();
1356 result = new TableLayout(parent.getContext());
1358 final RowBase row = getItem(position);
1359 if (row instanceof PairEntry.Row) {
1360 return getView(position, (PairEntry.Row) row, parent, result);
1361 } else if (row instanceof TokenRow) {
1362 return getView((TokenRow) row, parent, result);
1363 } else if (row instanceof HtmlEntry.Row) {
1364 return getView((HtmlEntry.Row) row, parent, result);
1366 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1370 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1371 final TableLayout result) {
1372 final PairEntry entry = row.getEntry();
1373 final int rowCount = entry.pairs.size();
1375 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1376 layoutParams.weight = 0.5f;
1377 layoutParams.leftMargin = mPaddingLarge;
1379 for (int r = 0; r < rowCount; ++r) {
1380 final TableRow tableRow = new TableRow(result.getContext());
1382 final TextView col1 = new TextView(tableRow.getContext());
1383 final TextView col2 = new TextView(tableRow.getContext());
1385 // Set the columns in the table.
1387 final TextView bullet = new TextView(tableRow.getContext());
1388 bullet.setText(" • ");
1389 tableRow.addView(bullet);
1391 tableRow.addView(col1, layoutParams);
1392 final TextView margin = new TextView(tableRow.getContext());
1393 margin.setText(" ");
1394 tableRow.addView(margin);
1396 final TextView bullet = new TextView(tableRow.getContext());
1397 bullet.setText(" • ");
1398 tableRow.addView(bullet);
1400 tableRow.addView(col2, layoutParams);
1404 // Set what's in the columns.
1406 final Pair pair = entry.pairs.get(r);
1407 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1408 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1410 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1411 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1413 // Bold the token instances in col1.
1414 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1415 .singleton(row.getTokenRow(true).getToken());
1416 final Spannable col1Spannable = (Spannable) col1.getText();
1417 for (final String token : toBold) {
1419 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1420 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1421 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1422 startPos += token.length();
1426 createTokenLinkSpans(col1, col1Spannable, col1Text);
1427 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1429 col1.setTypeface(typeface);
1430 col2.setTypeface(typeface);
1431 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1432 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1433 // col2.setBackgroundResource(theme.otherLangBg);
1435 if (index.swapPairEntries) {
1436 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1437 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1439 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1440 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1443 result.addView(tableRow);
1446 // Because we have a Button inside a ListView row:
1447 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1448 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1449 result.setClickable(true);
1450 result.setFocusable(true);
1451 result.setLongClickable(true);
1452 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1454 result.setBackgroundResource(theme.normalRowBg);
1456 result.setOnClickListener(new TextView.OnClickListener() {
1458 public void onClick(View v) {
1459 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1466 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1467 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1468 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1469 final Context context = parent.getContext();
1471 final TableRow tableRow = new TableRow(result.getContext());
1472 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1473 : theme.tokenRowOtherBg);
1475 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1477 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1479 result.addView(tableRow);
1481 // Make it so we can long-click on these token rows, too:
1482 final TextView textView = new TextView(context);
1483 textView.setText(text, BufferType.SPANNABLE);
1484 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1485 textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1486 result.setLongClickable(true);
1489 // textView.setTextColor(android.R.color.secondary_text_light);
1490 textView.setTypeface(typeface);
1491 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1493 textView.setTextAppearance(context, theme.tokenRowFg);
1494 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1496 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1500 textView.setLayoutParams(lp);
1501 tableRow.addView(textView);
1503 if (!htmlEntries.isEmpty()) {
1504 final ClickableSpan clickableSpan = new ClickableSpan() {
1506 public void onClick(View widget) {
1509 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1510 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1511 result.setClickable(true);
1512 textView.setClickable(true);
1513 textView.setMovementMethod(LinkMovementMethod.getInstance());
1514 textView.setOnClickListener(new OnClickListener() {
1516 public void onClick(View v) {
1517 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1518 // Log.d(LOG, "html=" + html);
1519 startActivityForResult(
1520 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1521 "<html><head></head><body>%s</body></html>", html),
1522 htmlTextToHighlight, false),
1530 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1531 final IndexEntry indexEntry = row.getIndexEntry();
1532 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1533 indexEntry.htmlEntries, null, parent, result);
1536 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1537 final HtmlEntry htmlEntry = row.getEntry();
1538 final TokenRow tokenRow = row.getTokenRow(true);
1539 return getPossibleLinkToHtmlEntryView(false,
1540 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1541 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1547 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1549 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1550 final String text) {
1551 // Saw from the source code that LinkMovementMethod sets the selection!
1552 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1553 textView.setMovementMethod(LinkMovementMethod.getInstance());
1554 final Matcher matcher = CHAR_DASH.matcher(text);
1555 while (matcher.find()) {
1556 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1558 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1562 String selectedSpannableText = null;
1564 int selectedSpannableIndex = -1;
1567 public boolean onTouchEvent(MotionEvent event) {
1568 selectedSpannableText = null;
1569 selectedSpannableIndex = -1;
1570 return super.onTouchEvent(event);
1573 private class TextViewLongClickListener implements OnLongClickListener {
1576 private TextViewLongClickListener(final int index) {
1581 public boolean onLongClick(final View v) {
1582 final TextView textView = (TextView) v;
1583 final int start = textView.getSelectionStart();
1584 final int end = textView.getSelectionEnd();
1585 if (start >= 0 && end >= 0) {
1586 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1587 selectedSpannableIndex = index;
1593 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1596 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1599 // --------------------------------------------------------------------------
1601 // --------------------------------------------------------------------------
1603 void onSearchTextChange(final String text) {
1604 if ("thadolina".equals(text)) {
1605 final Dialog dialog = new Dialog(getListView().getContext());
1606 dialog.setContentView(R.layout.thadolina_dialog);
1607 dialog.setTitle("Ti amo, amore mio!");
1608 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1609 imageView.setOnClickListener(new OnClickListener() {
1611 public void onClick(View v) {
1612 final Intent intent = new Intent(Intent.ACTION_VIEW);
1613 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1614 startActivity(intent);
1619 if (dictRaf == null) {
1620 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1624 // Hide search icon once text is entered
1625 searchView.setIconifiedByDefault(text.length() > 0);
1626 searchView.setIconified(false);
1628 // if (!searchView.hasFocus()) {
1629 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1632 Log.d(LOG, "onSearchTextChange: " + text);
1633 if (currentSearchOperation != null) {
1634 Log.d(LOG, "Interrupting currentSearchOperation.");
1635 currentSearchOperation.interrupted.set(true);
1637 currentSearchOperation = new SearchOperation(text, index);
1638 searchExecutor.execute(currentSearchOperation);
1641 // --------------------------------------------------------------------------
1642 // Filtered results.
1643 // --------------------------------------------------------------------------
1645 boolean isFiltered() {
1646 return rowsToShow != null;
1649 void setFiltered(final SearchOperation searchOperation) {
1650 if (nextWordMenuItem != null) {
1651 nextWordMenuItem.setEnabled(false);
1652 previousWordMenuItem.setEnabled(false);
1654 rowsToShow = searchOperation.multiWordSearchResult;
1655 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1658 void clearFiltered() {
1659 if (nextWordMenuItem != null) {
1660 nextWordMenuItem.setEnabled(true);
1661 previousWordMenuItem.setEnabled(true);
1663 setListAdapter(new IndexAdapter(index));