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.content.pm.PackageManager;
24 import android.graphics.Color;
25 import android.graphics.Typeface;
26 import android.net.Uri;
27 import android.os.Bundle;
28 import android.os.Handler;
29 import android.preference.PreferenceManager;
30 import android.speech.tts.TextToSpeech;
31 import android.speech.tts.TextToSpeech.OnInitListener;
32 import android.support.design.widget.FloatingActionButton;
33 import android.support.v4.view.MenuItemCompat;
34 import android.support.v7.app.ActionBar;
35 import android.support.v7.app.ActionBarActivity;
36 import android.support.v7.widget.SearchView;
37 import android.support.v7.widget.SearchView.OnQueryTextListener;
38 import android.support.v7.widget.Toolbar;
39 import android.text.ClipboardManager;
40 import android.text.InputType;
41 import android.text.Spannable;
42 import android.text.method.LinkMovementMethod;
43 import android.text.style.ClickableSpan;
44 import android.text.style.StyleSpan;
45 import android.util.Log;
46 import android.util.TypedValue;
47 import android.view.ContextMenu;
48 import android.view.ContextMenu.ContextMenuInfo;
49 import android.view.Gravity;
50 import android.view.KeyEvent;
51 import android.view.Menu;
52 import android.view.MenuItem;
53 import android.view.MenuItem.OnMenuItemClickListener;
54 import android.view.MotionEvent;
55 import android.view.View;
56 import android.view.View.OnClickListener;
57 import android.view.View.OnLongClickListener;
58 import android.view.ViewGroup;
59 import android.view.WindowManager;
60 import android.view.inputmethod.EditorInfo;
61 import android.view.inputmethod.InputMethodManager;
62 import android.widget.AdapterView;
63 import android.widget.AdapterView.AdapterContextMenuInfo;
64 import android.widget.AdapterView.OnItemClickListener;
65 import android.widget.BaseAdapter;
66 import android.widget.Button;
67 import android.widget.FrameLayout;
68 import android.widget.ImageButton;
69 import android.widget.ImageView;
70 import android.widget.ImageView.ScaleType;
71 import android.widget.LinearLayout;
72 import android.widget.ListAdapter;
73 import android.widget.ListView;
74 import android.widget.TableLayout;
75 import android.widget.TableRow;
76 import android.widget.TextView;
77 import android.widget.TextView.BufferType;
78 import android.widget.Toast;
80 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
81 import com.hughes.android.dictionary.engine.Dictionary;
82 import com.hughes.android.dictionary.engine.EntrySource;
83 import com.hughes.android.dictionary.engine.HtmlEntry;
84 import com.hughes.android.dictionary.engine.Index;
85 import com.hughes.android.dictionary.engine.Index.IndexEntry;
86 import com.hughes.android.dictionary.engine.Language.LanguageResources;
87 import com.hughes.android.dictionary.engine.PairEntry;
88 import com.hughes.android.dictionary.engine.PairEntry.Pair;
89 import com.hughes.android.dictionary.engine.RowBase;
90 import com.hughes.android.dictionary.engine.TokenRow;
91 import com.hughes.android.dictionary.engine.TransliteratorManager;
92 import com.hughes.android.util.IntentLauncher;
93 import com.hughes.android.util.NonLinkClickableSpan;
94 import com.hughes.util.StringUtil;
97 import java.io.FileWriter;
98 import java.io.IOException;
99 import java.io.PrintWriter;
100 import java.io.RandomAccessFile;
101 import java.text.SimpleDateFormat;
102 import java.util.Arrays;
103 import java.util.Collections;
104 import java.util.Date;
105 import java.util.HashMap;
106 import java.util.LinkedHashSet;
107 import java.util.List;
108 import java.util.Locale;
109 import java.util.Random;
110 import java.util.Set;
111 import java.util.concurrent.Executor;
112 import java.util.concurrent.ExecutorService;
113 import java.util.concurrent.Executors;
114 import java.util.concurrent.ThreadFactory;
115 import java.util.concurrent.atomic.AtomicBoolean;
116 import java.util.regex.Matcher;
117 import java.util.regex.Pattern;
119 public class DictionaryActivity extends ActionBarActivity {
121 static final String LOG = "QuickDic";
123 DictionaryApplication application;
125 File dictFile = null;
126 RandomAccessFile dictRaf = null;
128 Dictionary dictionary = null;
134 List<RowBase> rowsToShow = null; // if not null, just show these rows.
136 final Random rand = new Random();
138 final Handler uiHandler = new Handler();
140 private final ExecutorService searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
142 public Thread newThread(Runnable r) {
143 return new Thread(r, "searchExecutor");
147 private SearchOperation currentSearchOperation = null;
149 TextToSpeech textToSpeech;
150 volatile boolean ttsReady;
153 DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
154 int textColorFg = Color.BLACK;
157 private ListView listView;
158 private ListView getListView() {
159 if (listView == null) {
160 listView = (ListView)findViewById(android.R.id.list);
165 private void setListAdapter(ListAdapter adapter) {
166 getListView().setAdapter(adapter);
169 private ListAdapter getListAdapter() {
170 return getListView().getAdapter();
173 SearchView searchView;
174 ImageButton languageButton;
175 SearchView.OnQueryTextListener onQueryTextListener;
177 MenuItem nextWordMenuItem, previousWordMenuItem, randomWordMenuItem;
180 private File wordList = null;
181 private boolean saveOnlyFirstSubentry = false;
182 private boolean clickOpensContextMenu = false;
184 // Visible for testing.
185 ListAdapter indexAdapter = null;
188 * For some languages, loading the transliterators used in this search takes
189 * a long time, so we fire it up on a different thread, and don't invoke it
190 * from the main thread until it's already finished once.
192 private volatile boolean indexPrepFinished = false;
194 public DictionaryActivity() {
197 public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
198 final String searchToken) {
199 final Intent intent = new Intent(c, DictionaryActivity.class);
200 intent.putExtra(C.DICT_FILE, dictFile.getPath());
201 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
202 intent.putExtra(C.SEARCH_TOKEN, searchToken);
203 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
208 protected void onSaveInstanceState(final Bundle outState) {
209 super.onSaveInstanceState(outState);
210 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
211 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
212 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
215 private int getMatchLen(String search, Index.IndexEntry e) {
216 if (e == null) return 0;
217 for (int i = 0; i < search.length(); ++i) {
218 String a = search.substring(0, i + 1);
219 String b = e.token.substring(0, i + 1);
220 if (!a.equalsIgnoreCase(b))
223 return search.length();
227 public void onCreate(Bundle savedInstanceState) {
228 // This needs to be before super.onCreate, otherwise ActionbarSherlock
229 // doesn't makes the background of the actionbar white when you're
230 // in the dark theme.
231 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
233 Log.d(LOG, "onCreate:" + this);
234 super.onCreate(savedInstanceState);
236 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
238 // Don't auto-launch if this fails.
239 prefs.edit().remove(C.DICT_FILE).commit();
241 setContentView(R.layout.dictionary_activity);
243 application = (DictionaryApplication) getApplication();
244 theme = application.getSelectedTheme();
245 textColorFg = getResources().getColor(theme.tokenRowFgColor);
247 final Intent intent = getIntent();
248 String intentAction = intent.getAction();
250 * @author Dominik Köppl Querying the Intent
251 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
252 * Arguments: SearchManager.QUERY -> the phrase to search from
253 * -> language in which the phrase is written to -> to which
254 * language shall be translated
256 if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT")) {
257 String query = intent.getStringExtra(SearchManager.QUERY);
258 String from = intent.getStringExtra("from");
260 from = from.toLowerCase(Locale.US);
261 String to = intent.getStringExtra("to");
263 to = to.toLowerCase(Locale.US);
265 getIntent().putExtra(C.SEARCH_TOKEN, query);
267 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null)) {
268 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
269 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
270 for (DictionaryInfo info : dicts) {
271 boolean hasFrom = from == null;
272 boolean hasTo = to == null;
273 for (IndexInfo index : info.indexInfos) {
274 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
276 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
279 if (hasFrom && hasTo) {
282 for (; which_index < info.indexInfos.size(); ++which_index) {
283 if (info.indexInfos.get(which_index).shortName.toLowerCase(
284 Locale.US).equals(from))
287 intent.putExtra(C.INDEX_SHORT_NAME,
288 info.indexInfos.get(which_index).shortName);
291 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
300 * @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
301 * simple query Arguments follow from android standard (see
304 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH)) {
305 String query = intent.getStringExtra(SearchManager.QUERY);
307 getIntent().putExtra(C.SEARCH_TOKEN, query);
309 if (intentAction != null && intentAction.equals(Intent.ACTION_SEND)) {
310 String query = intent.getStringExtra(Intent.EXTRA_TEXT);
312 getIntent().putExtra(C.SEARCH_TOKEN, query);
315 * This processes text on M+ devices where QuickDic shows up in the context menu.
317 if (intentAction != null && intentAction.equals(Intent.ACTION_PROCESS_TEXT)) {
318 String query = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
320 getIntent().putExtra(C.SEARCH_TOKEN, query);
324 * @author Dominik Köppl If no dictionary is chosen, use the default
325 * dictionary specified in the preferences If this step does
326 * fail (no default dictionary specified), show a toast and
329 if (intent.getStringExtra(C.DICT_FILE) == null) {
330 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
331 if (dictfile != null)
332 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
334 String dictFilename = intent.getStringExtra(C.DICT_FILE);
335 if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null) {
336 final List<DictionaryInfo> dics = application.getDictionariesOnDevice(null);
337 final String search = intent.getStringExtra(C.SEARCH_TOKEN);
338 String bestFname = null;
339 String bestIndex = null;
340 int bestMatchLen = 2; // ignore shorter matches
341 AtomicBoolean dummy = new AtomicBoolean();
342 for (int i = 0; dictFilename == null && i < dics.size(); ++i) {
344 Log.d(LOG, "Checking dictionary " + dics.get(i).uncompressedFilename);
345 final File dictfile = application.getPath(dics.get(i).uncompressedFilename);
346 Dictionary dic = new Dictionary(new RandomAccessFile(dictfile, "r"));
347 for (int j = 0; j < dic.indices.size(); ++j) {
348 Index idx = dic.indices.get(j);
349 Log.d(LOG, "Checking index " + idx.shortName);
350 if (idx.findExact(search) != null) {
351 Log.d(LOG, "Found exact match");
352 dictFilename = dictfile.toString();
353 intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
356 int matchLen = getMatchLen(search, idx.findInsertionPoint(search, dummy));
357 Log.d(LOG, "Found partial match length " + matchLen);
358 if (matchLen > bestMatchLen) {
359 bestFname = dictfile.toString();
360 bestIndex = idx.shortName;
361 bestMatchLen = matchLen;
364 } catch (Exception e) {}
366 if (dictFilename == null && bestFname != null) {
367 dictFilename = bestFname;
368 intent.putExtra(C.INDEX_SHORT_NAME, bestIndex);
372 if (dictFilename == null) {
373 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
374 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
378 if (dictFilename != null)
379 dictFile = new File(dictFilename);
382 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
384 public void onInit(int status) {
386 updateTTSLanguage(indexIndex);
391 final String name = application.getDictionaryName(dictFile.getName());
392 this.setTitle("QuickDic: " + name);
393 dictRaf = new RandomAccessFile(dictFile, "r");
394 dictionary = new Dictionary(dictRaf);
395 } catch (Exception e) {
396 Log.e(LOG, "Unable to load dictionary.", e);
397 if (dictRaf != null) {
400 } catch (IOException e1) {
401 Log.e(LOG, "Unable to close dictRaf.", e1);
405 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
406 Toast.LENGTH_LONG).show();
407 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
411 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
412 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
413 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
416 for (int i = 0; i < dictionary.indices.size(); ++i) {
417 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
422 Log.d(LOG, "Loading index " + indexIndex);
423 index = dictionary.indices.get(indexIndex);
424 getListView().setEmptyView(findViewById(android.R.id.empty));
425 setListAdapter(new IndexAdapter(index));
427 // Pre-load the collators.
428 new Thread(new Runnable() {
430 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
431 final long startMillis = System.currentTimeMillis();
433 TransliteratorManager.init(new TransliteratorManager.Callback() {
435 public void onTransliteratorReady() {
436 uiHandler.post(new Runnable() {
439 onSearchTextChange(searchView.getQuery().toString());
445 for (final Index index : dictionary.indices) {
446 final String searchToken = index.sortedIndexEntries.get(0).token;
447 final IndexEntry entry = index.findExact(searchToken);
448 if (entry == null || !searchToken.equals(entry.token)) {
449 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
452 indexPrepFinished = true;
453 } catch (Exception e) {
455 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
457 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
461 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
462 if ("SYSTEM".equals(fontName)) {
463 typeface = Typeface.DEFAULT;
464 } else if ("SERIF".equals(fontName)) {
465 typeface = Typeface.SERIF;
466 } else if ("SANS_SERIF".equals(fontName)) {
467 typeface = Typeface.SANS_SERIF;
468 } else if ("MONOSPACE".equals(fontName)) {
469 typeface = Typeface.MONOSPACE;
471 if ("FreeSerif.ttf.jpg".equals(fontName)) {
472 fontName = "FreeSerif.otf.jpg";
475 typeface = Typeface.createFromAsset(getAssets(), fontName);
476 } catch (Exception e) {
477 Log.w(LOG, "Exception trying to use typeface, using default.", e);
478 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
479 Toast.LENGTH_LONG).show();
482 if (typeface == null) {
483 Log.w(LOG, "Unable to create typeface, using default.");
484 typeface = Typeface.DEFAULT;
486 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
488 fontSizeSp = Integer.parseInt(fontSize.trim());
489 } catch (NumberFormatException e) {
494 registerForContextMenu(getListView());
497 wordList = application.getWordListFile();
498 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
500 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
501 !getPackageManager().hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN));
502 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
504 onCreateSetupActionBarAndSearchView();
506 View floatSwapButton = findViewById(R.id.floatSwapButton);
507 floatSwapButton.setOnLongClickListener(new OnLongClickListener() {
509 public boolean onLongClick(View v) {
510 onLanguageButtonLongClick(v.getContext());
515 // Set the search text from the intent, then the saved state.
516 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
517 if (savedInstanceState != null) {
518 text = savedInstanceState.getString(C.SEARCH_TOKEN);
523 setSearchText(text, true);
524 Log.d(LOG, "Trying to restore searchText=" + text);
526 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
529 searchView.requestFocus();
531 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
532 // getListView().setCacheColorHint(0);
535 private void onCreateSetupActionBarAndSearchView() {
536 ActionBar actionBar = getSupportActionBar();
537 actionBar.setDisplayShowTitleEnabled(false);
538 actionBar.setDisplayShowHomeEnabled(false);
539 actionBar.setDisplayHomeAsUpEnabled(false);
541 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
543 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
544 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
545 customSearchView.setLayoutParams(layoutParams);
547 listView.setOnItemClickListener(new OnItemClickListener() {
549 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
550 onListItemClick(getListView(), view, row, id);
554 languageButton = new ImageButton(customSearchView.getContext());
555 languageButton.setId(R.id.languageButton);
556 languageButton.setScaleType(ScaleType.FIT_CENTER);
557 languageButton.setOnClickListener(new OnClickListener() {
559 public void onClick(View v) {
560 onLanguageButtonLongClick(v.getContext());
563 languageButton.setAdjustViewBounds(true);
564 LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
565 customSearchView.addView(languageButton, lpb);
567 searchView = new SearchView(getSupportActionBar().getThemedContext());
568 searchView.setId(R.id.searchView);
570 // Get rid of search icon, it takes up too much space.
571 // There is still text saying "search" in the search field.
572 searchView.setIconifiedByDefault(true);
573 searchView.setIconified(false);
575 searchView.setQueryHint(getString(R.string.searchText));
576 searchView.setSubmitButtonEnabled(false);
577 searchView.setInputType(InputType.TYPE_CLASS_TEXT);
578 searchView.setImeOptions(
579 EditorInfo.IME_ACTION_DONE |
580 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
581 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
583 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
584 onQueryTextListener = new OnQueryTextListener() {
586 public boolean onQueryTextSubmit(String query) {
587 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
593 public boolean onQueryTextChange(String newText) {
594 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
595 onSearchTextChange(searchView.getQuery().toString());
599 searchView.setOnQueryTextListener(onQueryTextListener);
600 searchView.setFocusable(true);
601 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
602 FrameLayout.LayoutParams.WRAP_CONTENT, 1);
603 customSearchView.addView(searchView, lp);
605 actionBar.setCustomView(customSearchView);
606 actionBar.setDisplayShowCustomEnabled(true);
608 // Avoid wasting space on large left inset
609 Toolbar tb = (Toolbar)customSearchView.getParent();
610 tb.setContentInsetsRelative(0, 0);
612 getListView().setNextFocusLeftId(R.id.searchView);
613 findViewById(R.id.floatSwapButton).setNextFocusRightId(R.id.languageButton);
614 languageButton.setNextFocusLeftId(R.id.floatSwapButton);
618 protected void onResume() {
619 Log.d(LOG, "onResume");
621 if (PreferenceActivity.prefsMightHaveChanged) {
622 PreferenceActivity.prefsMightHaveChanged = false;
624 startActivity(getIntent());
630 protected void onPause() {
636 * Invoked when MyWebView returns, since the user might have clicked some
637 * hypertext in the MyWebView.
639 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
640 super.onActivityResult(requestCode, resultCode, result);
641 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
642 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
643 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
647 private static void setDictionaryPrefs(final Context context, final File dictFile,
648 final String indexShortName, final String searchToken) {
649 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
651 prefs.putString(C.DICT_FILE, dictFile.getPath());
652 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
653 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
658 protected void onDestroy() {
660 if (dictRaf == null) {
664 final SearchOperation searchOperation = currentSearchOperation;
665 currentSearchOperation = null;
667 // Before we close the RAF, we have to wind the current search down.
668 if (searchOperation != null) {
669 Log.d(LOG, "Interrupting search to shut down.");
670 currentSearchOperation = null;
671 searchOperation.interrupted.set(true);
673 searchExecutor.shutdownNow();
674 textToSpeech.shutdown();
678 Log.d(LOG, "Closing RAF.");
680 } catch (IOException e) {
681 Log.e(LOG, "Failed to close dictionary", e);
686 // --------------------------------------------------------------------------
688 // --------------------------------------------------------------------------
690 private void showKeyboard() {
691 // For some reason, this doesn't always work the first time.
692 // One way to replicate the problem:
693 // Press the "task switch" button repeatedly to pause and resume
694 for (int delay = 1; delay <= 101; delay += 100) {
695 searchView.postDelayed(new Runnable() {
698 Log.d(LOG, "Trying to show soft keyboard.");
699 final boolean searchTextHadFocus = searchView.hasFocus();
700 searchView.requestFocusFromTouch();
701 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
702 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
703 if (!searchTextHadFocus) {
711 private void hideKeyboard() {
712 Log.d(LOG, "Hide soft keyboard.");
713 searchView.clearFocus();
714 InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
715 manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
718 void updateLangButton() {
719 final LanguageResources languageResources =
720 DictionaryApplication.isoCodeToResources.get(index.shortName);
721 if (languageResources != null && languageResources.flagId != 0) {
722 languageButton.setImageResource(languageResources.flagId);
724 if (indexIndex % 2 == 0) {
725 languageButton.setImageResource(android.R.drawable.ic_media_next);
727 languageButton.setImageResource(android.R.drawable.ic_media_previous);
730 updateTTSLanguage(indexIndex);
733 private void updateTTSLanguage(int i) {
734 if (!ttsReady || index == null || textToSpeech == null) {
735 Log.d(LOG, "Can't updateTTSLanguage.");
738 final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
739 Log.d(LOG, "Setting TTS locale to: " + locale);
741 final int ttsResult = textToSpeech.setLanguage(locale);
742 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
743 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
744 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
746 } catch (Exception e) {
747 Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
751 public void onSearchButtonClick(View dummy) {
752 if (!searchView.hasFocus()) {
753 searchView.requestFocus();
755 if (searchView.getQuery().toString().length() > 0) {
756 searchView.setQuery("", false);
759 searchView.setIconified(false);
762 public void onLanguageButtonClick(View dummy) {
763 if (dictionary.indices.size() == 1) {
764 // No need to work to switch indices.
767 if (currentSearchOperation != null) {
768 currentSearchOperation.interrupted.set(true);
769 currentSearchOperation = null;
771 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
772 searchView.getQuery().toString(), false);
775 void onLanguageButtonLongClick(final Context context) {
776 final Dialog dialog = new Dialog(context);
777 dialog.setContentView(R.layout.select_dictionary_dialog);
778 dialog.setTitle(R.string.selectDictionary);
780 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
782 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
783 final Button button = new Button(listView.getContext());
784 final String name = getString(R.string.dictionaryManager);
785 button.setText(name);
786 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
787 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
789 protected void onGo() {
791 DictionaryActivity.this.finish();
794 button.setOnClickListener(intentLauncher);
795 listView.addHeaderView(button);
797 listView.setItemsCanFocus(true);
798 listView.setAdapter(new BaseAdapter() {
800 public View getView(int position, View convertView, ViewGroup parent) {
801 final DictionaryInfo dictionaryInfo = getItem(position);
803 final LinearLayout result = new LinearLayout(parent.getContext());
805 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
806 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
807 final View button = application.createButton(parent.getContext(),
808 dictionaryInfo, indexInfo);
809 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
810 getLaunchIntent(getApplicationContext(),
811 application.getPath(dictionaryInfo.uncompressedFilename),
812 indexInfo.shortName, searchView.getQuery().toString())) {
814 protected void onGo() {
816 DictionaryActivity.this.finish();
819 button.setOnClickListener(intentLauncher);
820 if (i == indexIndex && dictFile != null &&
821 dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
822 button.setPressed(true);
824 result.addView(button);
827 final TextView nameView = new TextView(parent.getContext());
828 final String name = application
829 .getDictionaryName(dictionaryInfo.uncompressedFilename);
830 nameView.setText(name);
831 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
832 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
833 layoutParams.width = 0;
834 layoutParams.weight = 1.0f;
835 nameView.setLayoutParams(layoutParams);
836 nameView.setGravity(Gravity.CENTER_VERTICAL);
837 result.addView(nameView);
842 public long getItemId(int position) {
847 public DictionaryInfo getItem(int position) {
848 return installedDicts.get(position);
852 public int getCount() {
853 return installedDicts.size();
859 void onUpDownButton(final boolean up) {
863 final int firstVisibleRow = getListView().getFirstVisiblePosition();
864 final RowBase row = index.rows.get(firstVisibleRow);
865 final TokenRow tokenRow = row.getTokenRow(true);
866 final int destIndexEntry;
868 if (row != tokenRow) {
869 destIndexEntry = tokenRow.referenceIndex;
871 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
875 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
877 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
878 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
879 setSearchText(dest.token, false);
880 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
884 void onRandomWordButton() {
885 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
886 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
887 setSearchText(dest.token, false);
888 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
892 // --------------------------------------------------------------------------
894 // --------------------------------------------------------------------------
896 final Random random = new Random();
899 public boolean onCreateOptionsMenu(final Menu menu) {
901 if (PreferenceManager.getDefaultSharedPreferences(this)
902 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
904 nextWordMenuItem = menu.add(getString(R.string.nextWord))
905 .setIcon(R.drawable.arrow_down_float);
906 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
907 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
909 public boolean onMenuItemClick(MenuItem item) {
910 onUpDownButton(false);
916 previousWordMenuItem = menu.add(getString(R.string.previousWord))
917 .setIcon(R.drawable.arrow_up_float);
918 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
919 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
921 public boolean onMenuItemClick(MenuItem item) {
922 onUpDownButton(true);
928 randomWordMenuItem = menu.add(getString(R.string.randomWord));
929 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
931 public boolean onMenuItemClick(MenuItem item) {
932 onRandomWordButton();
937 application.onCreateGlobalOptionsMenu(this, menu);
940 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
941 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
942 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
943 public boolean onMenuItemClick(final MenuItem menuItem) {
944 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
952 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
953 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
954 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
955 public boolean onMenuItemClick(final MenuItem menuItem) {
956 final Context context = getListView().getContext();
957 final Dialog dialog = new Dialog(context);
958 dialog.setContentView(R.layout.about_dictionary_dialog);
959 final TextView textView = (TextView) dialog.findViewById(R.id.text);
961 final String name = application.getDictionaryName(dictFile.getName());
962 dialog.setTitle(name);
964 final StringBuilder builder = new StringBuilder();
965 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
966 dictionaryInfo.uncompressedBytes = dictFile.length();
967 if (dictionaryInfo != null) {
968 builder.append(dictionaryInfo.dictInfo).append("\n\n");
969 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
972 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
975 getString(R.string.dictionaryCreationTime,
976 dictionaryInfo.creationMillis)).append("\n");
977 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
978 builder.append("\n");
979 builder.append(getString(R.string.indexName, indexInfo.shortName))
982 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
985 builder.append("\n");
986 builder.append(getString(R.string.sources)).append("\n");
987 for (final EntrySource source : dictionary.sources) {
989 getString(R.string.sourceInfo, source.getName(),
990 source.getNumEntries())).append("\n");
993 textView.setText(builder.toString());
996 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
997 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
998 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
999 dialog.getWindow().setAttributes(layoutParams);
1008 // --------------------------------------------------------------------------
1009 // Context Menu + clicks
1010 // --------------------------------------------------------------------------
1013 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1014 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
1015 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
1017 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
1018 wordList.getName()));
1020 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1021 public boolean onMenuItemClick(android.view.MenuItem item) {
1022 onAppendToWordList(row);
1027 final android.view.MenuItem share = menu.add("Share");
1028 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1029 public boolean onMenuItemClick(android.view.MenuItem item) {
1030 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
1031 shareIntent.setType("text/plain");
1032 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
1034 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
1035 row.getRawText(saveOnlyFirstSubentry));
1036 startActivity(shareIntent);
1041 final android.view.MenuItem copy = menu.add(android.R.string.copy);
1042 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1043 public boolean onMenuItemClick(android.view.MenuItem item) {
1049 if (selectedSpannableText != null) {
1050 final String selectedText = selectedSpannableText;
1051 final android.view.MenuItem searchForSelection = menu.add(getString(
1052 R.string.searchForSelection,
1053 selectedSpannableText));
1055 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1056 public boolean onMenuItemClick(android.view.MenuItem item) {
1057 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
1061 // Rats, this won't be shown:
1062 //searchForSelection.setIcon(R.drawable.abs__ic_search);
1065 if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
1066 final android.view.MenuItem speak = menu.add(R.string.speak);
1067 final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
1068 updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
1069 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1071 public boolean onMenuItemClick(android.view.MenuItem item) {
1072 textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
1073 new HashMap<String, String>());
1080 private void jumpToTextFromHyperLink(
1081 final String selectedText, final int defaultIndexToUse) {
1082 int indexToUse = -1;
1084 for (int i = 0; i < dictionary.indices.size(); ++i) {
1085 final Index index = dictionary.indices.get(i);
1086 if (indexPrepFinished) {
1087 System.out.println("Doing index lookup: on " + selectedText);
1088 final IndexEntry indexEntry = index.findExact(selectedText);
1089 if (indexEntry != null) {
1090 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1091 .getTokenRow(false);
1092 if (tokenRow != null && tokenRow.hasMainEntry) {
1098 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1101 if (numFound != 1 || indexToUse == -1) {
1102 indexToUse = defaultIndexToUse;
1104 // Without this extra delay, the call to jumpToRow that this
1105 // invokes doesn't always actually have any effect.
1106 final int actualIndexToUse = indexToUse;
1107 getListView().postDelayed(new Runnable() {
1110 setIndexAndSearchText(actualIndexToUse, selectedText, true);
1116 * Called when user clicks outside of search text, so that they can start
1117 * typing again immediately.
1119 void defocusSearchText() {
1120 // Log.d(LOG, "defocusSearchText");
1121 // Request focus so that if we start typing again, it clears the text
1123 getListView().requestFocus();
1125 // Visual indication that a new keystroke will clear the search text.
1126 // Doesn't seem to work unless searchText has focus.
1127 // searchView.selectAll();
1130 protected void onListItemClick(ListView l, View v, int row, long id) {
1131 defocusSearchText();
1132 if (clickOpensContextMenu && dictRaf != null) {
1137 @SuppressLint("SimpleDateFormat")
1138 void onAppendToWordList(final RowBase row) {
1139 defocusSearchText();
1141 final StringBuilder rawText = new StringBuilder();
1142 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1143 rawText.append(index.longName).append("\t");
1144 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1145 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1146 Log.d(LOG, "Writing : " + rawText);
1149 wordList.getParentFile().mkdirs();
1150 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1151 out.println(rawText.toString());
1153 } catch (Exception e) {
1154 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1155 Toast.makeText(this,
1156 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1157 Toast.LENGTH_LONG).show();
1162 @SuppressWarnings("deprecation")
1163 void onCopy(final RowBase row) {
1164 defocusSearchText();
1166 Log.d(LOG, "Copy, row=" + row);
1167 final StringBuilder result = new StringBuilder();
1168 result.append(row.getRawText(false));
1169 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1170 clipboardManager.setText(result.toString());
1171 Log.d(LOG, "Copied: " + result);
1175 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1176 if (event.getUnicodeChar() != 0) {
1177 if (!searchView.hasFocus()) {
1178 setSearchText("" + (char) event.getUnicodeChar(), true);
1179 searchView.requestFocus();
1183 if (keyCode == KeyEvent.KEYCODE_BACK) {
1184 // Log.d(LOG, "Clearing dictionary prefs.");
1185 // Pretend that we just autolaunched so that we won't do it again.
1186 // DictionaryManagerActivity.lastAutoLaunchMillis =
1187 // System.currentTimeMillis();
1189 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1190 Log.d(LOG, "Trying to hide soft keyboard.");
1191 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1192 View focus = getCurrentFocus();
1193 if (focus != null) {
1194 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1195 InputMethodManager.HIDE_NOT_ALWAYS);
1199 return super.onKeyDown(keyCode, event);
1202 private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
1203 Log.d(LOG, "Changing index to: " + newIndex);
1204 if (newIndex == -1) {
1205 Log.e(LOG, "Invalid index.");
1208 if (newIndex != indexIndex) {
1209 indexIndex = newIndex;
1210 index = dictionary.indices.get(indexIndex);
1211 indexAdapter = new IndexAdapter(index);
1212 setListAdapter(indexAdapter);
1213 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1214 setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());
1217 setSearchText(newSearchText, true, hideKeyboard);
1220 private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
1221 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1222 // Disable the listener, because sometimes it doesn't work.
1223 searchView.setOnQueryTextListener(null);
1224 searchView.setQuery(text, false);
1225 moveCursorToRight();
1226 searchView.setOnQueryTextListener(onQueryTextListener);
1228 if (triggerSearch) {
1229 onSearchTextChange(text);
1232 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1238 private void setSearchText(final String text, final boolean triggerSearch) {
1239 setSearchText(text, triggerSearch, true);
1242 // private long cursorDelayMillis = 100;
1243 private void moveCursorToRight() {
1244 // if (searchText.getLayout() != null) {
1245 // cursorDelayMillis = 100;
1246 // // Surprising, but this can crash when you rotate...
1247 // Selection.moveToRightEdge(searchView.getQuery(),
1248 // searchText.getLayout());
1250 // uiHandler.postDelayed(new Runnable() {
1252 // public void run() {
1253 // moveCursorToRight();
1255 // }, cursorDelayMillis);
1256 // cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
1260 // --------------------------------------------------------------------------
1262 // --------------------------------------------------------------------------
1264 private void searchFinished(final SearchOperation searchOperation) {
1265 if (searchOperation.interrupted.get()) {
1266 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1269 if (searchOperation != this.currentSearchOperation) {
1270 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1274 final Index.IndexEntry searchResult = searchOperation.searchResult;
1275 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1277 currentSearchOperation = null;
1278 uiHandler.postDelayed(new Runnable() {
1281 if (currentSearchOperation == null) {
1282 if (searchResult != null) {
1286 jumpToRow(searchResult.startRow);
1287 } else if (searchOperation.multiWordSearchResult != null) {
1288 // Multi-row search....
1289 setFiltered(searchOperation);
1291 throw new IllegalStateException("This should never happen.");
1294 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1300 private final void jumpToRow(final int row) {
1301 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1302 // getListView().requestFocusFromTouch();
1303 getListView().setSelectionFromTop(row, 0);
1304 getListView().setSelected(true);
1307 static final Pattern WHITESPACE = Pattern.compile("\\s+");
1309 final class SearchOperation implements Runnable {
1311 final AtomicBoolean interrupted = new AtomicBoolean(false);
1313 final String searchText;
1315 List<String> searchTokens; // filled in for multiWord.
1319 long searchStartMillis;
1321 Index.IndexEntry searchResult;
1323 List<RowBase> multiWordSearchResult;
1325 boolean done = false;
1327 SearchOperation(final String searchText, final Index index) {
1328 this.searchText = StringUtil.normalizeWhitespace(searchText);
1332 public String toString() {
1333 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
1339 searchStartMillis = System.currentTimeMillis();
1340 final String[] searchTokenArray = WHITESPACE.split(searchText);
1341 if (searchTokenArray.length == 1) {
1342 searchResult = index.findInsertionPoint(searchText, interrupted);
1344 searchTokens = Arrays.asList(searchTokenArray);
1345 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1349 "searchText=" + searchText + ", searchDuration="
1350 + (System.currentTimeMillis() - searchStartMillis)
1351 + ", interrupted=" + interrupted.get());
1352 if (!interrupted.get()) {
1353 uiHandler.post(new Runnable() {
1356 searchFinished(SearchOperation.this);
1360 Log.d(LOG, "interrupted, skipping searchFinished.");
1362 } catch (Exception e) {
1363 Log.e(LOG, "Failure during search (can happen during Activity close.");
1365 synchronized (this) {
1373 // --------------------------------------------------------------------------
1375 // --------------------------------------------------------------------------
1377 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
1378 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
1380 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
1381 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
1383 final class IndexAdapter extends BaseAdapter {
1385 private static final float PADDING_DEFAULT_DP = 8;
1387 private static final float PADDING_LARGE_DP = 16;
1391 final List<RowBase> rows;
1393 final Set<String> toHighlight;
1395 private int mPaddingDefault;
1397 private int mPaddingLarge;
1399 IndexAdapter(final Index index) {
1402 this.toHighlight = null;
1406 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1409 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1413 private void getMetrics() {
1414 // Get the screen's density scale
1415 final float scale = getResources().getDisplayMetrics().density;
1416 // Convert the dps to pixels, based on density scale
1417 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1418 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1422 public int getCount() {
1427 public RowBase getItem(int position) {
1428 return rows.get(position);
1432 public long getItemId(int position) {
1433 return getItem(position).index();
1437 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1438 final TableLayout result;
1439 if (convertView instanceof TableLayout) {
1440 result = (TableLayout) convertView;
1441 result.removeAllViews();
1443 result = new TableLayout(parent.getContext());
1445 final RowBase row = getItem(position);
1446 if (row instanceof PairEntry.Row) {
1447 return getView(position, (PairEntry.Row) row, parent, result);
1448 } else if (row instanceof TokenRow) {
1449 return getView((TokenRow) row, parent, result);
1450 } else if (row instanceof HtmlEntry.Row) {
1451 return getView((HtmlEntry.Row) row, parent, result);
1453 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1457 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1458 final TableLayout result) {
1459 final PairEntry entry = row.getEntry();
1460 final int rowCount = entry.pairs.size();
1462 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1463 layoutParams.weight = 0.5f;
1464 layoutParams.leftMargin = mPaddingLarge;
1466 for (int r = 0; r < rowCount; ++r) {
1467 final TableRow tableRow = new TableRow(result.getContext());
1469 final TextView col1 = new TextView(tableRow.getContext());
1470 final TextView col2 = new TextView(tableRow.getContext());
1471 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1472 col1.setTextIsSelectable(true);
1473 col2.setTextIsSelectable(true);
1476 // Set the columns in the table.
1478 final TextView bullet = new TextView(tableRow.getContext());
1479 bullet.setText(" • ");
1480 tableRow.addView(bullet);
1482 tableRow.addView(col1, layoutParams);
1483 final TextView margin = new TextView(tableRow.getContext());
1484 margin.setText(" ");
1485 tableRow.addView(margin);
1487 final TextView bullet = new TextView(tableRow.getContext());
1488 bullet.setText(" • ");
1489 tableRow.addView(bullet);
1491 tableRow.addView(col2, layoutParams);
1495 // Set what's in the columns.
1497 final Pair pair = entry.pairs.get(r);
1498 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1499 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1501 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1502 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1504 // Bold the token instances in col1.
1505 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1506 .singleton(row.getTokenRow(true).getToken());
1507 final Spannable col1Spannable = (Spannable) col1.getText();
1508 for (final String token : toBold) {
1510 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1511 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1512 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1513 startPos += token.length();
1517 createTokenLinkSpans(col1, col1Spannable, col1Text);
1518 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1520 col1.setTypeface(typeface);
1521 col2.setTypeface(typeface);
1522 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1523 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1524 // col2.setBackgroundResource(theme.otherLangBg);
1526 if (index.swapPairEntries) {
1527 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1528 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1530 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1531 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1534 result.addView(tableRow);
1537 // Because we have a Button inside a ListView row:
1538 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1539 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1540 result.setClickable(true);
1541 result.setFocusable(true);
1542 result.setLongClickable(true);
1543 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1545 result.setBackgroundResource(theme.normalRowBg);
1547 result.setOnClickListener(new TextView.OnClickListener() {
1549 public void onClick(View v) {
1550 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1557 private TableLayout getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1558 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1559 final String htmlTextToHighlight, ViewGroup parent, final TableLayout result) {
1560 final Context context = parent.getContext();
1562 final TableRow tableRow = new TableRow(result.getContext());
1563 tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1564 : theme.tokenRowOtherBg);
1566 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1568 tableRow.setPadding(mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1570 result.addView(tableRow);
1572 // Make it so we can long-click on these token rows, too:
1573 final TextView textView = new TextView(context);
1574 textView.setText(text, BufferType.SPANNABLE);
1575 createTokenLinkSpans(textView, (Spannable) textView.getText(), text);
1576 textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1577 result.setLongClickable(true);
1580 // textView.setTextColor(android.R.color.secondary_text_light);
1581 textView.setTypeface(typeface);
1582 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1584 textView.setTextAppearance(context, theme.tokenRowFg);
1585 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1587 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1591 textView.setLayoutParams(lp);
1592 tableRow.addView(textView);
1594 if (!htmlEntries.isEmpty()) {
1595 final ClickableSpan clickableSpan = new ClickableSpan() {
1597 public void onClick(View widget) {
1600 ((Spannable) textView.getText()).setSpan(clickableSpan, 0, text.length(),
1601 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1602 result.setClickable(true);
1603 textView.setClickable(true);
1604 textView.setMovementMethod(LinkMovementMethod.getInstance());
1605 textView.setOnClickListener(new OnClickListener() {
1607 public void onClick(View v) {
1608 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1609 // Log.d(LOG, "html=" + html);
1610 startActivityForResult(
1611 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1612 "<html><head></head><body>%s</body></html>", html),
1613 htmlTextToHighlight, false),
1621 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1622 final IndexEntry indexEntry = row.getIndexEntry();
1623 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1624 indexEntry.htmlEntries, null, parent, result);
1627 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1628 final HtmlEntry htmlEntry = row.getEntry();
1629 final TokenRow tokenRow = row.getTokenRow(true);
1630 return getPossibleLinkToHtmlEntryView(false,
1631 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1632 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1638 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1640 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1641 final String text) {
1642 // Saw from the source code that LinkMovementMethod sets the selection!
1643 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1644 textView.setMovementMethod(LinkMovementMethod.getInstance());
1645 final Matcher matcher = CHAR_DASH.matcher(text);
1646 while (matcher.find()) {
1647 spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
1649 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1653 String selectedSpannableText = null;
1655 int selectedSpannableIndex = -1;
1658 public boolean onTouchEvent(MotionEvent event) {
1659 selectedSpannableText = null;
1660 selectedSpannableIndex = -1;
1661 return super.onTouchEvent(event);
1664 private class TextViewLongClickListener implements OnLongClickListener {
1667 private TextViewLongClickListener(final int index) {
1672 public boolean onLongClick(final View v) {
1673 final TextView textView = (TextView) v;
1674 final int start = textView.getSelectionStart();
1675 final int end = textView.getSelectionEnd();
1676 if (start >= 0 && end >= 0) {
1677 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1678 selectedSpannableIndex = index;
1684 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1687 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1690 // --------------------------------------------------------------------------
1692 // --------------------------------------------------------------------------
1694 void onSearchTextChange(final String text) {
1695 if ("thadolina".equals(text)) {
1696 final Dialog dialog = new Dialog(getListView().getContext());
1697 dialog.setContentView(R.layout.thadolina_dialog);
1698 dialog.setTitle("Ti amo, amore mio!");
1699 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1700 imageView.setOnClickListener(new OnClickListener() {
1702 public void onClick(View v) {
1703 final Intent intent = new Intent(Intent.ACTION_VIEW);
1704 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1705 startActivity(intent);
1710 if (dictRaf == null) {
1711 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1715 // if (!searchView.hasFocus()) {
1716 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1719 Log.d(LOG, "onSearchTextChange: " + text);
1720 if (currentSearchOperation != null) {
1721 Log.d(LOG, "Interrupting currentSearchOperation.");
1722 currentSearchOperation.interrupted.set(true);
1724 currentSearchOperation = new SearchOperation(text, index);
1725 searchExecutor.execute(currentSearchOperation);
1726 ((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
1729 // --------------------------------------------------------------------------
1730 // Filtered results.
1731 // --------------------------------------------------------------------------
1733 boolean isFiltered() {
1734 return rowsToShow != null;
1737 void setFiltered(final SearchOperation searchOperation) {
1738 if (nextWordMenuItem != null) {
1739 nextWordMenuItem.setEnabled(false);
1740 previousWordMenuItem.setEnabled(false);
1742 rowsToShow = searchOperation.multiWordSearchResult;
1743 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1746 void clearFiltered() {
1747 if (nextWordMenuItem != null) {
1748 nextWordMenuItem.setEnabled(true);
1749 previousWordMenuItem.setEnabled(true);
1751 setListAdapter(new IndexAdapter(index));