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.ExecutorService;
112 import java.util.concurrent.Executors;
113 import java.util.concurrent.ThreadFactory;
114 import java.util.concurrent.atomic.AtomicBoolean;
115 import java.util.regex.Matcher;
116 import java.util.regex.Pattern;
118 public class DictionaryActivity extends ActionBarActivity {
120 static final String LOG = "QuickDic";
122 DictionaryApplication application;
124 File dictFile = null;
125 RandomAccessFile dictRaf = null;
127 Dictionary dictionary = null;
133 List<RowBase> rowsToShow = null; // if not null, just show these rows.
135 final Random rand = new Random();
137 final Handler uiHandler = new Handler();
139 private final ExecutorService searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
141 public Thread newThread(Runnable r) {
142 return new Thread(r, "searchExecutor");
146 private SearchOperation currentSearchOperation = null;
148 TextToSpeech textToSpeech;
149 volatile boolean ttsReady;
152 DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
153 int textColorFg = Color.BLACK;
156 private ListView listView;
157 private ListView getListView() {
158 if (listView == null) {
159 listView = (ListView)findViewById(android.R.id.list);
164 private void setListAdapter(ListAdapter adapter) {
165 getListView().setAdapter(adapter);
168 private ListAdapter getListAdapter() {
169 return getListView().getAdapter();
172 SearchView searchView;
173 ImageButton languageButton;
174 SearchView.OnQueryTextListener onQueryTextListener;
176 MenuItem nextWordMenuItem, previousWordMenuItem, randomWordMenuItem;
179 private File wordList = null;
180 private boolean saveOnlyFirstSubentry = false;
181 private boolean clickOpensContextMenu = false;
183 // Visible for testing.
184 ListAdapter indexAdapter = null;
187 * For some languages, loading the transliterators used in this search takes
188 * a long time, so we fire it up on a different thread, and don't invoke it
189 * from the main thread until it's already finished once.
191 private volatile boolean indexPrepFinished = false;
193 public DictionaryActivity() {
196 public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
197 final String searchToken) {
198 final Intent intent = new Intent(c, DictionaryActivity.class);
199 intent.putExtra(C.DICT_FILE, dictFile.getPath());
200 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
201 intent.putExtra(C.SEARCH_TOKEN, searchToken);
202 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
207 protected void onSaveInstanceState(final Bundle outState) {
208 super.onSaveInstanceState(outState);
209 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
210 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
211 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
214 private int getMatchLen(String search, Index.IndexEntry e)
216 if (e == null) return 0;
217 for (int i = 0; i < search.length(); ++i)
219 String a = search.substring(0, i + 1);
220 String b = e.token.substring(0, i + 1);
221 if (!a.equalsIgnoreCase(b))
224 return search.length();
228 public void onCreate(Bundle savedInstanceState) {
229 // This needs to be before super.onCreate, otherwise ActionbarSherlock
230 // doesn't makes the background of the actionbar white when you're
231 // in the dark theme.
232 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
234 Log.d(LOG, "onCreate:" + this);
235 super.onCreate(savedInstanceState);
237 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
239 // Don't auto-launch if this fails.
240 prefs.edit().remove(C.DICT_FILE).commit();
242 setContentView(R.layout.dictionary_activity);
244 application = (DictionaryApplication) getApplication();
245 theme = application.getSelectedTheme();
246 textColorFg = getResources().getColor(theme.tokenRowFgColor);
248 final Intent intent = getIntent();
249 String intentAction = intent.getAction();
251 * @author Dominik Köppl Querying the Intent
252 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
253 * Arguments: SearchManager.QUERY -> the phrase to search from
254 * -> language in which the phrase is written to -> to which
255 * language shall be translated
257 if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
259 String query = intent.getStringExtra(SearchManager.QUERY);
260 String from = intent.getStringExtra("from");
262 from = from.toLowerCase(Locale.US);
263 String to = intent.getStringExtra("to");
265 to = to.toLowerCase(Locale.US);
268 getIntent().putExtra(C.SEARCH_TOKEN, query);
270 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
272 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
273 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
274 for (DictionaryInfo info : dicts)
276 boolean hasFrom = from == null;
277 boolean hasTo = to == null;
278 for (IndexInfo index : info.indexInfos)
280 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
282 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
285 if (hasFrom && hasTo)
290 for (; which_index < info.indexInfos.size(); ++which_index)
292 if (info.indexInfos.get(which_index).shortName.toLowerCase(
293 Locale.US).equals(from))
296 intent.putExtra(C.INDEX_SHORT_NAME,
297 info.indexInfos.get(which_index).shortName);
300 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
309 * @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
310 * simple query Arguments follow from android standard (see
313 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
315 String query = intent.getStringExtra(SearchManager.QUERY);
317 getIntent().putExtra(C.SEARCH_TOKEN, query);
319 if (intentAction != null && intentAction.equals(Intent.ACTION_SEND))
321 String query = intent.getStringExtra(Intent.EXTRA_TEXT);
323 getIntent().putExtra(C.SEARCH_TOKEN, query);
326 * This processes text on M+ devices where QuickDic shows up in the context menu.
328 if (intentAction != null && intentAction.equals(Intent.ACTION_PROCESS_TEXT)) {
329 String query = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
331 getIntent().putExtra(C.SEARCH_TOKEN, query);
335 * @author Dominik Köppl If no dictionary is chosen, use the default
336 * dictionary specified in the preferences If this step does
337 * fail (no default dictionary specified), show a toast and
340 if (intent.getStringExtra(C.DICT_FILE) == null)
342 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
343 if (dictfile != null)
344 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
346 String dictFilename = intent.getStringExtra(C.DICT_FILE);
347 if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null)
349 final List<DictionaryInfo> dics = application.getDictionariesOnDevice(null);
350 final String search = intent.getStringExtra(C.SEARCH_TOKEN);
351 String bestFname = null;
352 String bestIndex = null;
353 int bestMatchLen = 2; // ignore shorter matches
354 AtomicBoolean dummy = new AtomicBoolean();
355 for (int i = 0; dictFilename == null && i < dics.size(); ++i)
358 Log.d(LOG, "Checking dictionary " + dics.get(i).uncompressedFilename);
359 final File dictfile = application.getPath(dics.get(i).uncompressedFilename);
360 Dictionary dic = new Dictionary(new RandomAccessFile(dictfile, "r"));
361 for (int j = 0; j < dic.indices.size(); ++j) {
362 Index idx = dic.indices.get(j);
363 Log.d(LOG, "Checking index " + idx.shortName);
364 if (idx.findExact(search) != null)
366 Log.d(LOG, "Found exact match");
367 dictFilename = dictfile.toString();
368 intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
371 int matchLen = getMatchLen(search, idx.findInsertionPoint(search, dummy));
372 Log.d(LOG, "Found partial match length " + matchLen);
373 if (matchLen > bestMatchLen)
375 bestFname = dictfile.toString();
376 bestIndex = idx.shortName;
377 bestMatchLen = matchLen;
380 } catch (Exception e) {}
382 if (dictFilename == null && bestFname != null)
384 dictFilename = bestFname;
385 intent.putExtra(C.INDEX_SHORT_NAME, bestIndex);
389 if (dictFilename == null)
391 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
392 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
396 if (dictFilename != null)
397 dictFile = new File(dictFilename);
400 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
402 public void onInit(int status) {
404 updateTTSLanguage(indexIndex);
409 final String name = application.getDictionaryName(dictFile.getName());
410 this.setTitle("QuickDic: " + name);
411 dictRaf = new RandomAccessFile(dictFile, "r");
412 dictionary = new Dictionary(dictRaf);
413 } catch (Exception e) {
414 Log.e(LOG, "Unable to load dictionary.", e);
415 if (dictRaf != null) {
418 } catch (IOException e1) {
419 Log.e(LOG, "Unable to close dictRaf.", e1);
423 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
424 Toast.LENGTH_LONG).show();
425 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
429 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
430 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
431 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
434 for (int i = 0; i < dictionary.indices.size(); ++i) {
435 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
440 Log.d(LOG, "Loading index " + indexIndex);
441 index = dictionary.indices.get(indexIndex);
442 getListView().setEmptyView(findViewById(android.R.id.empty));
443 setListAdapter(new IndexAdapter(index));
445 // Pre-load the collators.
446 new Thread(new Runnable() {
448 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
449 final long startMillis = System.currentTimeMillis();
451 TransliteratorManager.init(new TransliteratorManager.Callback() {
453 public void onTransliteratorReady() {
454 uiHandler.post(new Runnable() {
457 onSearchTextChange(searchView.getQuery().toString());
463 for (final Index index : dictionary.indices) {
464 final String searchToken = index.sortedIndexEntries.get(0).token;
465 final IndexEntry entry = index.findExact(searchToken);
466 if (entry == null || !searchToken.equals(entry.token)) {
467 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
470 indexPrepFinished = true;
471 } catch (Exception e) {
473 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
475 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
479 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
480 if ("SYSTEM".equals(fontName)) {
481 typeface = Typeface.DEFAULT;
482 } else if ("SERIF".equals(fontName)) {
483 typeface = Typeface.SERIF;
484 } else if ("SANS_SERIF".equals(fontName)) {
485 typeface = Typeface.SANS_SERIF;
486 } else if ("MONOSPACE".equals(fontName)) {
487 typeface = Typeface.MONOSPACE;
489 if ("FreeSerif.ttf.jpg".equals(fontName)) {
490 fontName = "FreeSerif.otf.jpg";
493 typeface = Typeface.createFromAsset(getAssets(), fontName);
494 } catch (Exception e) {
495 Log.w(LOG, "Exception trying to use typeface, using default.", e);
496 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
497 Toast.LENGTH_LONG).show();
500 if (typeface == null) {
501 Log.w(LOG, "Unable to create typeface, using default.");
502 typeface = Typeface.DEFAULT;
504 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
506 fontSizeSp = Integer.parseInt(fontSize.trim());
507 } catch (NumberFormatException e) {
512 registerForContextMenu(getListView());
515 wordList = application.getWordListFile();
516 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
518 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
520 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
522 onCreateSetupActionBarAndSearchView();
524 View floatSwapButton = findViewById(R.id.floatSwapButton);
525 floatSwapButton.setOnClickListener(new OnClickListener() {
527 public void onClick(View arg0) {
528 onLanguageButtonClick();
531 floatSwapButton.setOnLongClickListener(new OnLongClickListener() {
533 public boolean onLongClick(View v) {
534 onLanguageButtonLongClick(v.getContext());
539 final FloatingActionButton floatSearchButton = (FloatingActionButton)findViewById(R.id.floatSearchButton);
540 floatSearchButton.setOnClickListener(new OnClickListener() {
542 public void onClick(View arg0) {
543 if (!searchView.hasFocus()) {
544 searchView.requestFocus();
546 if (searchView.getQuery().toString().length() > 0) {
547 searchView.setQuery("", false);
550 searchView.setIconified(false);
554 // Set the search text from the intent, then the saved state.
555 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
556 if (savedInstanceState != null) {
557 text = savedInstanceState.getString(C.SEARCH_TOKEN);
562 setSearchText(text, true);
563 Log.d(LOG, "Trying to restore searchText=" + text);
565 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
568 searchView.requestFocus();
570 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
571 // getListView().setCacheColorHint(0);
574 private void onCreateSetupActionBarAndSearchView() {
575 ActionBar actionBar = getSupportActionBar();
576 actionBar.setDisplayShowTitleEnabled(false);
577 actionBar.setDisplayShowHomeEnabled(false);
578 actionBar.setDisplayHomeAsUpEnabled(false);
580 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
582 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
583 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
584 customSearchView.setLayoutParams(layoutParams);
586 listView.setOnItemClickListener(new OnItemClickListener() {
588 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
589 onListItemClick(getListView(), view, row, id);
593 languageButton = new ImageButton(customSearchView.getContext());
594 languageButton.setScaleType(ScaleType.FIT_CENTER);
595 languageButton.setOnClickListener(new OnClickListener() {
597 public void onClick(View v) {
598 onLanguageButtonLongClick(v.getContext());
601 languageButton.setAdjustViewBounds(true);
602 LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
603 customSearchView.addView(languageButton, lpb);
605 searchView = new SearchView(getSupportActionBar().getThemedContext());
607 // Get rid of search icon, it takes up too much space.
608 // There is still text saying "search" in the search field.
609 searchView.setIconifiedByDefault(true);
610 searchView.setIconified(false);
612 searchView.setQueryHint(getString(R.string.searchText));
613 searchView.setSubmitButtonEnabled(false);
614 searchView.setInputType(InputType.TYPE_CLASS_TEXT);
615 searchView.setImeOptions(
616 EditorInfo.IME_ACTION_DONE |
617 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
618 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
620 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
621 onQueryTextListener = new OnQueryTextListener() {
623 public boolean onQueryTextSubmit(String query) {
624 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
630 public boolean onQueryTextChange(String newText) {
631 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
632 onSearchTextChange(searchView.getQuery().toString());
636 searchView.setOnQueryTextListener(onQueryTextListener);
637 searchView.setFocusable(true);
638 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
639 FrameLayout.LayoutParams.WRAP_CONTENT, 1);
640 customSearchView.addView(searchView, lp);
642 actionBar.setCustomView(customSearchView);
643 actionBar.setDisplayShowCustomEnabled(true);
645 // Avoid wasting space on large left inset
646 Toolbar tb = (Toolbar)customSearchView.getParent();
647 tb.setContentInsetsRelative(0, 0);
651 protected void onResume() {
652 Log.d(LOG, "onResume");
654 if (PreferenceActivity.prefsMightHaveChanged) {
655 PreferenceActivity.prefsMightHaveChanged = false;
657 startActivity(getIntent());
663 protected void onPause() {
669 * Invoked when MyWebView returns, since the user might have clicked some
670 * hypertext in the MyWebView.
672 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
673 super.onActivityResult(requestCode, resultCode, result);
674 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
675 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
676 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
680 private static void setDictionaryPrefs(final Context context, final File dictFile,
681 final String indexShortName, final String searchToken) {
682 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
684 prefs.putString(C.DICT_FILE, dictFile.getPath());
685 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
686 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
691 protected void onDestroy() {
693 if (dictRaf == null) {
697 final SearchOperation searchOperation = currentSearchOperation;
698 currentSearchOperation = null;
700 // Before we close the RAF, we have to wind the current search down.
701 if (searchOperation != null) {
702 Log.d(LOG, "Interrupting search to shut down.");
703 currentSearchOperation = null;
704 searchOperation.interrupted.set(true);
706 searchExecutor.shutdownNow();
707 textToSpeech.shutdown();
711 Log.d(LOG, "Closing RAF.");
713 } catch (IOException e) {
714 Log.e(LOG, "Failed to close dictionary", e);
719 // --------------------------------------------------------------------------
721 // --------------------------------------------------------------------------
723 private void showKeyboard() {
724 // For some reason, this doesn't always work the first time.
725 // One way to replicate the problem:
726 // Press the "task switch" button repeatedly to pause and resume
727 for (int delay = 1; delay <= 101; delay += 100) {
728 searchView.postDelayed(new Runnable() {
731 Log.d(LOG, "Trying to show soft keyboard.");
732 final boolean searchTextHadFocus = searchView.hasFocus();
733 searchView.requestFocusFromTouch();
734 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
735 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
736 if (!searchTextHadFocus) {
744 private void hideKeyboard() {
745 Log.d(LOG, "Hide soft keyboard.");
746 searchView.clearFocus();
747 InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
748 manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
751 void updateLangButton() {
752 final LanguageResources languageResources =
753 DictionaryApplication.isoCodeToResources.get(index.shortName);
754 if (languageResources != null && languageResources.flagId != 0) {
755 languageButton.setImageResource(languageResources.flagId);
757 if (indexIndex % 2 == 0) {
758 languageButton.setImageResource(android.R.drawable.ic_media_next);
760 languageButton.setImageResource(android.R.drawable.ic_media_previous);
763 updateTTSLanguage(indexIndex);
766 private void updateTTSLanguage(int i) {
767 if (!ttsReady || index == null || textToSpeech == null) {
768 Log.d(LOG, "Can't updateTTSLanguage.");
771 final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
772 Log.d(LOG, "Setting TTS locale to: " + locale);
774 final int ttsResult = textToSpeech.setLanguage(locale);
775 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
776 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
777 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
779 } catch (Exception e) {
780 Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
784 void onLanguageButtonClick() {
785 if (dictionary.indices.size() == 1) {
786 // No need to work to switch indices.
789 if (currentSearchOperation != null) {
790 currentSearchOperation.interrupted.set(true);
791 currentSearchOperation = null;
793 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
794 searchView.getQuery().toString(), false);
797 void onLanguageButtonLongClick(final Context context) {
798 final Dialog dialog = new Dialog(context);
799 dialog.setContentView(R.layout.select_dictionary_dialog);
800 dialog.setTitle(R.string.selectDictionary);
802 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
804 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
805 final Button button = new Button(listView.getContext());
806 final String name = getString(R.string.dictionaryManager);
807 button.setText(name);
808 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
809 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
811 protected void onGo() {
813 DictionaryActivity.this.finish();
816 button.setOnClickListener(intentLauncher);
817 listView.addHeaderView(button);
819 listView.setAdapter(new BaseAdapter() {
821 public View getView(int position, View convertView, ViewGroup parent) {
822 final DictionaryInfo dictionaryInfo = getItem(position);
824 final LinearLayout result = new LinearLayout(parent.getContext());
826 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
827 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
828 final View button = application.createButton(parent.getContext(),
829 dictionaryInfo, indexInfo);
830 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
831 getLaunchIntent(getApplicationContext(),
832 application.getPath(dictionaryInfo.uncompressedFilename),
833 indexInfo.shortName, searchView.getQuery().toString())) {
835 protected void onGo() {
837 DictionaryActivity.this.finish();
840 button.setOnClickListener(intentLauncher);
841 if (i == indexIndex && dictFile != null &&
842 dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
843 button.setPressed(true);
845 result.addView(button);
848 final TextView nameView = new TextView(parent.getContext());
849 final String name = application
850 .getDictionaryName(dictionaryInfo.uncompressedFilename);
851 nameView.setText(name);
852 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
853 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
854 layoutParams.width = 0;
855 layoutParams.weight = 1.0f;
856 nameView.setLayoutParams(layoutParams);
857 nameView.setGravity(Gravity.CENTER_VERTICAL);
858 result.addView(nameView);
863 public long getItemId(int position) {
868 public DictionaryInfo getItem(int position) {
869 return installedDicts.get(position);
873 public int getCount() {
874 return installedDicts.size();
880 void onUpDownButton(final boolean up) {
884 final int firstVisibleRow = getListView().getFirstVisiblePosition();
885 final RowBase row = index.rows.get(firstVisibleRow);
886 final TokenRow tokenRow = row.getTokenRow(true);
887 final int destIndexEntry;
889 if (row != tokenRow) {
890 destIndexEntry = tokenRow.referenceIndex;
892 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
896 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
898 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
899 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
900 setSearchText(dest.token, false);
901 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
905 void onRandomWordButton() {
906 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
907 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
908 setSearchText(dest.token, false);
909 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
913 // --------------------------------------------------------------------------
915 // --------------------------------------------------------------------------
917 final Random random = new Random();
920 public boolean onCreateOptionsMenu(final Menu menu) {
922 if (PreferenceManager.getDefaultSharedPreferences(this)
923 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
925 nextWordMenuItem = menu.add(getString(R.string.nextWord))
926 .setIcon(R.drawable.arrow_down_float);
927 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
928 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
930 public boolean onMenuItemClick(MenuItem item) {
931 onUpDownButton(false);
937 previousWordMenuItem = menu.add(getString(R.string.previousWord))
938 .setIcon(R.drawable.arrow_up_float);
939 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
940 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
942 public boolean onMenuItemClick(MenuItem item) {
943 onUpDownButton(true);
949 randomWordMenuItem = menu.add(getString(R.string.randomWord));
950 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
952 public boolean onMenuItemClick(MenuItem item) {
953 onRandomWordButton();
958 application.onCreateGlobalOptionsMenu(this, menu);
961 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
962 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
963 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
964 public boolean onMenuItemClick(final MenuItem menuItem) {
965 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
973 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
974 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
975 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
976 public boolean onMenuItemClick(final MenuItem menuItem) {
977 final Context context = getListView().getContext();
978 final Dialog dialog = new Dialog(context);
979 dialog.setContentView(R.layout.about_dictionary_dialog);
980 final TextView textView = (TextView) dialog.findViewById(R.id.text);
982 final String name = application.getDictionaryName(dictFile.getName());
983 dialog.setTitle(name);
985 final StringBuilder builder = new StringBuilder();
986 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
987 dictionaryInfo.uncompressedBytes = dictFile.length();
988 if (dictionaryInfo != null) {
989 builder.append(dictionaryInfo.dictInfo).append("\n\n");
990 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
993 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
996 getString(R.string.dictionaryCreationTime,
997 dictionaryInfo.creationMillis)).append("\n");
998 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
999 builder.append("\n");
1000 builder.append(getString(R.string.indexName, indexInfo.shortName))
1003 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
1006 builder.append("\n");
1007 builder.append(getString(R.string.sources)).append("\n");
1008 for (final EntrySource source : dictionary.sources) {
1010 getString(R.string.sourceInfo, source.getName(),
1011 source.getNumEntries())).append("\n");
1014 textView.setText(builder.toString());
1017 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
1018 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
1019 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
1020 dialog.getWindow().setAttributes(layoutParams);
1029 // --------------------------------------------------------------------------
1030 // Context Menu + clicks
1031 // --------------------------------------------------------------------------
1034 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1035 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
1036 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
1038 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
1039 wordList.getName()));
1041 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1042 public boolean onMenuItemClick(android.view.MenuItem item) {
1043 onAppendToWordList(row);
1048 final android.view.MenuItem share = menu.add("Share");
1049 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1050 public boolean onMenuItemClick(android.view.MenuItem item) {
1051 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
1052 shareIntent.setType("text/plain");
1053 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
1055 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
1056 row.getRawText(saveOnlyFirstSubentry));
1057 startActivity(shareIntent);
1062 final android.view.MenuItem copy = menu.add(android.R.string.copy);
1063 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1064 public boolean onMenuItemClick(android.view.MenuItem item) {
1070 if (selectedSpannableText != null) {
1071 final String selectedText = selectedSpannableText;
1072 final android.view.MenuItem searchForSelection = menu.add(getString(
1073 R.string.searchForSelection,
1074 selectedSpannableText));
1076 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1077 public boolean onMenuItemClick(android.view.MenuItem item) {
1078 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
1082 // Rats, this won't be shown:
1083 //searchForSelection.setIcon(R.drawable.abs__ic_search);
1086 if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
1087 final android.view.MenuItem speak = menu.add(R.string.speak);
1088 final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
1089 updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
1090 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1092 public boolean onMenuItemClick(android.view.MenuItem item) {
1093 textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
1094 new HashMap<String, String>());
1101 private void jumpToTextFromHyperLink(
1102 final String selectedText, final int defaultIndexToUse) {
1103 int indexToUse = -1;
1105 for (int i = 0; i < dictionary.indices.size(); ++i) {
1106 final Index index = dictionary.indices.get(i);
1107 if (indexPrepFinished) {
1108 System.out.println("Doing index lookup: on " + selectedText);
1109 final IndexEntry indexEntry = index.findExact(selectedText);
1110 if (indexEntry != null) {
1111 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1112 .getTokenRow(false);
1113 if (tokenRow != null && tokenRow.hasMainEntry) {
1119 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1122 if (numFound != 1 || indexToUse == -1) {
1123 indexToUse = defaultIndexToUse;
1125 // Without this extra delay, the call to jumpToRow that this
1126 // invokes doesn't always actually have any effect.
1127 final int actualIndexToUse = indexToUse;
1128 getListView().postDelayed(new Runnable() {
1131 setIndexAndSearchText(actualIndexToUse, selectedText, true);
1137 * Called when user clicks outside of search text, so that they can start
1138 * typing again immediately.
1140 void defocusSearchText() {
1141 // Log.d(LOG, "defocusSearchText");
1142 // Request focus so that if we start typing again, it clears the text
1144 getListView().requestFocus();
1146 // Visual indication that a new keystroke will clear the search text.
1147 // Doesn't seem to work unless searchText has focus.
1148 // searchView.selectAll();
1151 protected void onListItemClick(ListView l, View v, int row, long id) {
1152 defocusSearchText();
1153 if (clickOpensContextMenu && dictRaf != null) {
1158 @SuppressLint("SimpleDateFormat")
1159 void onAppendToWordList(final RowBase row) {
1160 defocusSearchText();
1162 final StringBuilder rawText = new StringBuilder();
1163 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1164 rawText.append(index.longName).append("\t");
1165 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1166 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1167 Log.d(LOG, "Writing : " + rawText);
1170 wordList.getParentFile().mkdirs();
1171 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1172 out.println(rawText.toString());
1174 } catch (Exception e) {
1175 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1176 Toast.makeText(this,
1177 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1178 Toast.LENGTH_LONG).show();
1183 @SuppressWarnings("deprecation")
1184 void onCopy(final RowBase row) {
1185 defocusSearchText();
1187 Log.d(LOG, "Copy, row=" + row);
1188 final StringBuilder result = new StringBuilder();
1189 result.append(row.getRawText(false));
1190 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1191 clipboardManager.setText(result.toString());
1192 Log.d(LOG, "Copied: " + result);
1196 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1197 if (event.getUnicodeChar() != 0) {
1198 if (!searchView.hasFocus()) {
1199 setSearchText("" + (char) event.getUnicodeChar(), true);
1200 searchView.requestFocus();
1204 if (keyCode == KeyEvent.KEYCODE_BACK) {
1205 // Log.d(LOG, "Clearing dictionary prefs.");
1206 // Pretend that we just autolaunched so that we won't do it again.
1207 // DictionaryManagerActivity.lastAutoLaunchMillis =
1208 // System.currentTimeMillis();
1210 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1211 Log.d(LOG, "Trying to hide soft keyboard.");
1212 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1213 View focus = getCurrentFocus();
1214 if (focus != null) {
1215 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1216 InputMethodManager.HIDE_NOT_ALWAYS);
1220 return super.onKeyDown(keyCode, event);
1223 private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
1224 Log.d(LOG, "Changing index to: " + newIndex);
1225 if (newIndex == -1) {
1226 Log.e(LOG, "Invalid index.");
1229 if (newIndex != indexIndex) {
1230 indexIndex = newIndex;
1231 index = dictionary.indices.get(indexIndex);
1232 indexAdapter = new IndexAdapter(index);
1233 setListAdapter(indexAdapter);
1234 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1235 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1238 setSearchText(newSearchText, true, hideKeyboard);
1241 private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
1242 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1243 // Disable the listener, because sometimes it doesn't work.
1244 searchView.setOnQueryTextListener(null);
1245 searchView.setQuery(text, false);
1246 moveCursorToRight();
1247 searchView.setOnQueryTextListener(onQueryTextListener);
1249 if (triggerSearch) {
1250 onSearchTextChange(text);
1253 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1259 private void setSearchText(final String text, final boolean triggerSearch) {
1260 setSearchText(text, triggerSearch, true);
1263 // private long cursorDelayMillis = 100;
1264 private void moveCursorToRight() {
1265 // if (searchText.getLayout() != null) {
1266 // cursorDelayMillis = 100;
1267 // // Surprising, but this can crash when you rotate...
1268 // Selection.moveToRightEdge(searchView.getQuery(),
1269 // searchText.getLayout());
1271 // uiHandler.postDelayed(new Runnable() {
1273 // public void run() {
1274 // moveCursorToRight();
1276 // }, cursorDelayMillis);
1277 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1281 // --------------------------------------------------------------------------
1283 // --------------------------------------------------------------------------
1285 private void searchFinished(final SearchOperation searchOperation) {
1286 if (searchOperation.interrupted.get()) {
1287 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1290 if (searchOperation != this.currentSearchOperation) {
1291 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1295 final Index.IndexEntry searchResult = searchOperation.searchResult;
1296 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1298 currentSearchOperation = null;
1299 uiHandler.postDelayed(new Runnable() {
1302 if (currentSearchOperation == null) {
1303 if (searchResult != null) {
1307 jumpToRow(searchResult.startRow);
1308 } else if (searchOperation.multiWordSearchResult != null) {
1309 // Multi-row search....
1310 setFiltered(searchOperation);
1312 throw new IllegalStateException("This should never happen.");
1315 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1321 private final void jumpToRow(final int row) {
1322 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1323 // getListView().requestFocusFromTouch();
1324 getListView().setSelectionFromTop(row, 0);
1325 getListView().setSelected(true);
1328 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1330 final class SearchOperation implements Runnable {
1332 final AtomicBoolean interrupted = new AtomicBoolean(false);
1334 final String searchText;
1336 List<String> searchTokens; // filled in for multiWord.
1340 long searchStartMillis;
1342 Index.IndexEntry searchResult;
1344 List<RowBase> multiWordSearchResult;
1346 boolean done = false;
1348 SearchOperation(final String searchText, final Index index) {
1349 this.searchText = StringUtil.normalizeWhitespace(searchText);
1353 public String toString() {
1354 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1360 searchStartMillis = System.currentTimeMillis();
1361 final String[] searchTokenArray = WHITESPACE.split(searchText);
1362 if (searchTokenArray.length == 1) {
1363 searchResult = index.findInsertionPoint(searchText, interrupted);
1365 searchTokens = Arrays.asList(searchTokenArray);
1366 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1370 "searchText=" + searchText + ", searchDuration="
1371 + (System.currentTimeMillis() - searchStartMillis)
1372 + ", interrupted=" + interrupted.get());
1373 if (!interrupted.get()) {
1374 uiHandler.post(new Runnable() {
1377 searchFinished(SearchOperation.this);
1381 Log.d(LOG, "interrupted, skipping searchFinished.");
1383 } catch (Exception e) {
1384 Log.e(LOG, "Failure during search (can happen during Activity close.");
1386 synchronized (this) {
1394 // --------------------------------------------------------------------------
1396 // --------------------------------------------------------------------------
1398 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1399 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1401 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1402 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1404 final class IndexAdapter extends BaseAdapter {
1406 private static final float PADDING_DEFAULT_DP = 8;
1408 private static final float PADDING_LARGE_DP = 16;
1412 final List<RowBase> rows;
1414 final Set<String> toHighlight;
1416 private int mPaddingDefault;
1418 private int mPaddingLarge;
1420 IndexAdapter(final Index index) {
1423 this.toHighlight = null;
1427 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1430 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1434 private void getMetrics() {
1435 // Get the screen's density scale
1436 final float scale = getResources().getDisplayMetrics().density;
1437 // Convert the dps to pixels, based on density scale
1438 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1439 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1443 public int getCount() {
1448 public RowBase getItem(int position) {
1449 return rows.get(position);
1453 public long getItemId(int position) {
1454 return getItem(position).index();
1458 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1459 final TableLayout result;
1460 if (convertView instanceof TableLayout) {
1461 result = (TableLayout) convertView;
1462 result.removeAllViews();
1464 result = new TableLayout(parent.getContext());
1466 final RowBase row = getItem(position);
1467 if (row instanceof PairEntry.Row) {
1468 return getView(position, (PairEntry.Row) row, parent, result);
1469 } else if (row instanceof TokenRow) {
1470 return getView((TokenRow) row, parent, result);
1471 } else if (row instanceof HtmlEntry.Row) {
1472 return getView((HtmlEntry.Row) row, parent, result);
1474 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1478 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1479 final TableLayout result) {
1480 final PairEntry entry = row.getEntry();
1481 final int rowCount = entry.pairs.size();
1483 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1484 layoutParams.weight = 0.5f;
1485 layoutParams.leftMargin = mPaddingLarge;
1487 for (int r = 0; r < rowCount; ++r) {
1488 final TableRow tableRow = new TableRow(result.getContext());
1490 final TextView col1 = new TextView(tableRow.getContext());
1491 final TextView col2 = new TextView(tableRow.getContext());
1492 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
1494 col1.setTextIsSelectable(true);
1495 col2.setTextIsSelectable(true);
1498 // Set the columns in the table.
1500 final TextView bullet = new TextView(tableRow.getContext());
1501 bullet.setText(" • ");
1502 tableRow.addView(bullet);
1504 tableRow.addView(col1, layoutParams);
1505 final TextView margin = new TextView(tableRow.getContext());
1506 margin.setText(" ");
1507 tableRow.addView(margin);
1509 final TextView bullet = new TextView(tableRow.getContext());
1510 bullet.setText(" • ");
1511 tableRow.addView(bullet);
1513 tableRow.addView(col2, layoutParams);
1517 // Set what's in the columns.
1519 final Pair pair = entry.pairs.get(r);
1520 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1521 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1523 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1524 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1526 // Bold the token instances in col1.
1527 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1528 .singleton(row.getTokenRow(true).getToken());
1529 final Spannable col1Spannable = (Spannable) col1.getText();
1530 for (final String token : toBold) {
1532 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1533 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1534 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1535 startPos += token.length();
1539 createTokenLinkSpans(col1, col1Spannable, col1Text);
1540 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1542 col1.setTypeface(typeface);
1543 col2.setTypeface(typeface);
1544 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1545 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1546 // col2.setBackgroundResource(theme.otherLangBg);
1548 if (index.swapPairEntries) {
1549 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1550 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1552 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1553 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1556 result.addView(tableRow);
1559 // Because we have a Button inside a ListView row:
1560 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1561 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1562 result.setClickable(true);
1563 result.setFocusable(true);
1564 result.setLongClickable(true);
1565 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1567 result.setBackgroundResource(theme.normalRowBg);
1569 result.setOnClickListener(new TextView.OnClickListener() {
1571 public void onClick(View v) {
1572 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1579 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1580 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1581 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1582 final Context context = parent.getContext();
1584 final TableRow tableRow = new TableRow(result.getContext());
1585 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1586 : theme.tokenRowOtherBg);
1588 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1590 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1592 result.addView(tableRow);
1594 // Make it so we can long-click on these token rows, too:
1595 final TextView textView = new TextView(context);
1596 textView.setText(text, BufferType.SPANNABLE);
1597 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1598 textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1599 result.setLongClickable(true);
1602 // textView.setTextColor(android.R.color.secondary_text_light);
1603 textView.setTypeface(typeface);
1604 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1606 textView.setTextAppearance(context, theme.tokenRowFg);
1607 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1609 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1613 textView.setLayoutParams(lp);
1614 tableRow.addView(textView);
1616 if (!htmlEntries.isEmpty()) {
1617 final ClickableSpan clickableSpan = new ClickableSpan() {
1619 public void onClick(View widget) {
1622 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1623 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1624 result.setClickable(true);
1625 textView.setClickable(true);
1626 textView.setMovementMethod(LinkMovementMethod.getInstance());
1627 textView.setOnClickListener(new OnClickListener() {
1629 public void onClick(View v) {
1630 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1631 // Log.d(LOG, "html=" + html);
1632 startActivityForResult(
1633 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1634 "<html><head></head><body>%s</body></html>", html),
1635 htmlTextToHighlight, false),
1643 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1644 final IndexEntry indexEntry = row.getIndexEntry();
1645 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1646 indexEntry.htmlEntries, null, parent, result);
1649 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1650 final HtmlEntry htmlEntry = row.getEntry();
1651 final TokenRow tokenRow = row.getTokenRow(true);
1652 return getPossibleLinkToHtmlEntryView(false,
1653 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1654 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1660 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1662 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1663 final String text) {
1664 // Saw from the source code that LinkMovementMethod sets the selection!
1665 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1666 textView.setMovementMethod(LinkMovementMethod.getInstance());
1667 final Matcher matcher = CHAR_DASH.matcher(text);
1668 while (matcher.find()) {
1669 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1671 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1675 String selectedSpannableText = null;
1677 int selectedSpannableIndex = -1;
1680 public boolean onTouchEvent(MotionEvent event) {
1681 selectedSpannableText = null;
1682 selectedSpannableIndex = -1;
1683 return super.onTouchEvent(event);
1686 private class TextViewLongClickListener implements OnLongClickListener {
1689 private TextViewLongClickListener(final int index) {
1694 public boolean onLongClick(final View v) {
1695 final TextView textView = (TextView) v;
1696 final int start = textView.getSelectionStart();
1697 final int end = textView.getSelectionEnd();
1698 if (start >= 0 && end >= 0) {
1699 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1700 selectedSpannableIndex = index;
1706 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1709 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1712 // --------------------------------------------------------------------------
1714 // --------------------------------------------------------------------------
1716 void onSearchTextChange(final String text) {
1717 if ("thadolina".equals(text)) {
1718 final Dialog dialog = new Dialog(getListView().getContext());
1719 dialog.setContentView(R.layout.thadolina_dialog);
1720 dialog.setTitle("Ti amo, amore mio!");
1721 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1722 imageView.setOnClickListener(new OnClickListener() {
1724 public void onClick(View v) {
1725 final Intent intent = new Intent(Intent.ACTION_VIEW);
1726 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1727 startActivity(intent);
1732 if (dictRaf == null) {
1733 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1737 // if (!searchView.hasFocus()) {
1738 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1741 Log.d(LOG, "onSearchTextChange: " + text);
1742 if (currentSearchOperation != null) {
1743 Log.d(LOG, "Interrupting currentSearchOperation.");
1744 currentSearchOperation.interrupted.set(true);
1746 currentSearchOperation = new SearchOperation(text, index);
1747 searchExecutor.execute(currentSearchOperation);
1748 ((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
1751 // --------------------------------------------------------------------------
1752 // Filtered results.
1753 // --------------------------------------------------------------------------
1755 boolean isFiltered() {
1756 return rowsToShow != null;
1759 void setFiltered(final SearchOperation searchOperation) {
1760 if (nextWordMenuItem != null) {
1761 nextWordMenuItem.setEnabled(false);
1762 previousWordMenuItem.setEnabled(false);
1764 rowsToShow = searchOperation.multiWordSearchResult;
1765 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1768 void clearFiltered() {
1769 if (nextWordMenuItem != null) {
1770 nextWordMenuItem.setEnabled(true);
1771 previousWordMenuItem.setEnabled(true);
1773 setListAdapter(new IndexAdapter(index));