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.database.Cursor;
25 import android.database.MatrixCursor;
26 import android.graphics.Color;
27 import android.graphics.Typeface;
28 import android.net.Uri;
29 import android.os.Bundle;
30 import android.os.Handler;
31 import android.preference.PreferenceManager;
32 import android.speech.tts.TextToSpeech;
33 import android.speech.tts.TextToSpeech.OnInitListener;
34 import android.support.annotation.NonNull;
35 import android.support.design.widget.FloatingActionButton;
36 import android.support.v4.view.MenuItemCompat;
37 import android.support.v4.widget.CursorAdapter;
38 import android.support.v7.app.ActionBar;
39 import android.support.v7.app.AppCompatActivity;
40 import android.support.v7.widget.SearchView;
41 import android.support.v7.widget.SearchView.OnQueryTextListener;
42 import android.support.v7.widget.Toolbar;
43 import android.text.ClipboardManager;
44 import android.text.InputType;
45 import android.text.Spannable;
46 import android.text.SpannableString;
47 import android.text.method.LinkMovementMethod;
48 import android.text.style.ClickableSpan;
49 import android.text.style.StyleSpan;
50 import android.util.DisplayMetrics;
51 import android.util.Log;
52 import android.util.TypedValue;
53 import android.view.ContextMenu;
54 import android.view.ContextMenu.ContextMenuInfo;
55 import android.view.Gravity;
56 import android.view.KeyEvent;
57 import android.view.Menu;
58 import android.view.MenuItem;
59 import android.view.MenuItem.OnMenuItemClickListener;
60 import android.view.MotionEvent;
61 import android.view.View;
62 import android.view.View.OnClickListener;
63 import android.view.View.OnLongClickListener;
64 import android.view.ViewGroup;
65 import android.view.WindowManager;
66 import android.view.inputmethod.EditorInfo;
67 import android.view.inputmethod.InputMethodManager;
68 import android.widget.AdapterView;
69 import android.widget.AdapterView.AdapterContextMenuInfo;
70 import android.widget.AdapterView.OnItemClickListener;
71 import android.widget.AutoCompleteTextView;
72 import android.widget.BaseAdapter;
73 import android.widget.Button;
74 import android.widget.FrameLayout;
75 import android.widget.ImageButton;
76 import android.widget.ImageView;
77 import android.widget.ImageView.ScaleType;
78 import android.widget.LinearLayout;
79 import android.widget.ListAdapter;
80 import android.widget.ListView;
81 import android.widget.TableLayout;
82 import android.widget.TableRow;
83 import android.widget.TextView;
84 import android.widget.Toast;
86 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
87 import com.hughes.android.dictionary.engine.Dictionary;
88 import com.hughes.android.dictionary.engine.EntrySource;
89 import com.hughes.android.dictionary.engine.HtmlEntry;
90 import com.hughes.android.dictionary.engine.Index;
91 import com.hughes.android.dictionary.engine.Index.IndexEntry;
92 import com.hughes.android.dictionary.engine.PairEntry;
93 import com.hughes.android.dictionary.engine.PairEntry.Pair;
94 import com.hughes.android.dictionary.engine.RowBase;
95 import com.hughes.android.dictionary.engine.TokenRow;
96 import com.hughes.android.dictionary.engine.TransliteratorManager;
97 import com.hughes.android.util.IntentLauncher;
98 import com.hughes.android.util.NonLinkClickableSpan;
99 import com.hughes.util.StringUtil;
102 import java.io.FileWriter;
103 import java.io.IOException;
104 import java.io.PrintWriter;
105 import java.io.RandomAccessFile;
106 import java.nio.channels.FileChannel;
107 import java.text.SimpleDateFormat;
108 import java.util.ArrayList;
109 import java.util.Arrays;
110 import java.util.Collections;
111 import java.util.Date;
112 import java.util.HashMap;
113 import java.util.LinkedHashSet;
114 import java.util.List;
115 import java.util.Locale;
116 import java.util.Random;
117 import java.util.Set;
118 import java.util.concurrent.ExecutorService;
119 import java.util.concurrent.Executors;
120 import java.util.concurrent.ThreadFactory;
121 import java.util.concurrent.atomic.AtomicBoolean;
122 import java.util.regex.Matcher;
123 import java.util.regex.Pattern;
125 public class DictionaryActivity extends AppCompatActivity {
127 private static final String LOG = "QuickDic";
129 private DictionaryApplication application;
131 private File dictFile = null;
132 private FileChannel dictRaf = null;
133 private String dictFileTitleName = null;
135 private Dictionary dictionary = null;
137 private int indexIndex = 0;
139 private Index index = null;
141 private List<RowBase> rowsToShow = null; // if not null, just show these rows.
143 private final Random rand = new Random();
145 private final Handler uiHandler = new Handler();
147 private final ExecutorService searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
149 public Thread newThread(@NonNull Runnable r) {
150 return new Thread(r, "searchExecutor");
154 private SearchOperation currentSearchOperation = null;
155 private final int MAX_SEARCH_HISTORY = 10;
156 private final ArrayList<String> searchHistory = new ArrayList<>(MAX_SEARCH_HISTORY);
157 private MatrixCursor searchHistoryCursor = new MatrixCursor(new String[] {"_id", "search"});
159 private TextToSpeech textToSpeech;
160 private volatile boolean ttsReady;
162 private Typeface typeface;
163 private DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
164 private int textColorFg = Color.BLACK;
165 private int fontSizeSp;
167 private ListView listView;
168 private ListView getListView() {
169 if (listView == null) {
170 listView = (ListView)findViewById(android.R.id.list);
175 private void setListAdapter(ListAdapter adapter) {
176 getListView().setAdapter(adapter);
179 private ListAdapter getListAdapter() {
180 return getListView().getAdapter();
183 private SearchView searchView;
184 private AutoCompleteTextView searchTextView;
185 private ImageButton languageButton;
186 private SearchView.OnQueryTextListener onQueryTextListener;
188 private MenuItem nextWordMenuItem;
189 private MenuItem previousWordMenuItem;
192 private File wordList = null;
193 private boolean saveOnlyFirstSubentry = false;
194 private boolean clickOpensContextMenu = false;
196 // Visible for testing.
197 private ListAdapter indexAdapter = null;
200 * For some languages, loading the transliterators used in this search takes
201 * a long time, so we fire it up on a different thread, and don't invoke it
202 * from the main thread until it's already finished once.
204 private volatile boolean indexPrepFinished = false;
206 public DictionaryActivity() {
209 public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
210 final String searchToken) {
211 final Intent intent = new Intent(c, DictionaryActivity.class);
212 intent.putExtra(C.DICT_FILE, dictFile.getPath());
213 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
214 intent.putExtra(C.SEARCH_TOKEN, searchToken);
215 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
220 protected void onSaveInstanceState(final Bundle outState) {
221 super.onSaveInstanceState(outState);
222 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
223 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
224 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
227 private int getMatchLen(String search, Index.IndexEntry e) {
228 if (e == null) return 0;
229 for (int i = 0; i < search.length(); ++i) {
230 String a = search.substring(0, i + 1);
231 String b = e.token.substring(0, i + 1);
232 if (!a.equalsIgnoreCase(b))
235 return search.length();
238 private void dictionaryOpenFail(Exception e) {
239 Log.e(LOG, "Unable to load dictionary.", e);
240 if (dictRaf != null) {
242 setListAdapter(null);
245 } catch (IOException e1) {
246 Log.e(LOG, "Unable to close dictRaf.", e1);
251 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
252 Toast.LENGTH_LONG).show();
253 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
257 private void addToSearchHistory(String text) {
258 if (text == null || text.isEmpty()) return;
259 int exists = searchHistory.indexOf(text);
260 if (exists >= 0) searchHistory.remove(exists);
261 else if (searchHistory.size() >= MAX_SEARCH_HISTORY) searchHistory.remove(searchHistory.size() - 1);
262 searchHistory.add(0, text);
263 searchHistoryCursor = new MatrixCursor(new String[] {"_id", "search"});
264 for (int i = 0; i < searchHistory.size(); i++) {
265 final Object[] row = {i, searchHistory.get(i)};
266 searchHistoryCursor.addRow(row);
268 if (searchView.getSuggestionsAdapter().getCursor() != null) {
269 searchView.getSuggestionsAdapter().swapCursor(searchHistoryCursor);
270 searchView.getSuggestionsAdapter().notifyDataSetChanged();
275 public void onCreate(Bundle savedInstanceState) {
276 DictionaryApplication.INSTANCE.init(getApplicationContext());
277 application = DictionaryApplication.INSTANCE;
278 // This needs to be before super.onCreate, otherwise ActionbarSherlock
279 // doesn't makes the background of the actionbar white when you're
280 // in the dark theme.
281 setTheme(application.getSelectedTheme().themeId);
283 Log.d(LOG, "onCreate:" + this);
284 super.onCreate(savedInstanceState);
286 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
288 // Don't auto-launch if this fails.
289 prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
291 setContentView(R.layout.dictionary_activity);
293 theme = application.getSelectedTheme();
294 textColorFg = getResources().getColor(theme.tokenRowFgColor);
296 if (dictRaf != null) {
299 } catch (IOException e) {
300 Log.e(LOG, "Failed to close dictionary", e);
305 final Intent intent = getIntent();
306 String intentAction = intent.getAction();
308 @author Dominik Köppl Querying the Intent
309 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
310 * Arguments: SearchManager.QUERY -> the phrase to search from
311 * -> language in which the phrase is written to -> to which
312 * language shall be translated
314 if ("com.hughes.action.ACTION_SEARCH_DICT".equals(intentAction)) {
315 String query = intent.getStringExtra(SearchManager.QUERY);
316 String from = intent.getStringExtra("from");
318 from = from.toLowerCase(Locale.US);
319 String to = intent.getStringExtra("to");
321 to = to.toLowerCase(Locale.US);
323 getIntent().putExtra(C.SEARCH_TOKEN, query);
325 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null)) {
326 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
327 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
328 for (DictionaryInfo info : dicts) {
329 boolean hasFrom = from == null;
330 boolean hasTo = to == null;
331 for (IndexInfo index : info.indexInfos) {
332 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
334 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
337 if (hasFrom && hasTo) {
340 for (; which_index < info.indexInfos.size(); ++which_index) {
341 if (info.indexInfos.get(which_index).shortName.toLowerCase(
342 Locale.US).equals(from))
345 intent.putExtra(C.INDEX_SHORT_NAME,
346 info.indexInfos.get(which_index).shortName);
349 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
358 @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
359 * simple query Arguments follow from android standard (see
362 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH)) {
363 String query = intent.getStringExtra(SearchManager.QUERY);
365 getIntent().putExtra(C.SEARCH_TOKEN, query);
367 if (intentAction != null && intentAction.equals(Intent.ACTION_SEND)) {
368 String query = intent.getStringExtra(Intent.EXTRA_TEXT);
370 getIntent().putExtra(C.SEARCH_TOKEN, query);
373 * This processes text on M+ devices where QuickDic shows up in the context menu.
375 if (intentAction != null && intentAction.equals(Intent.ACTION_PROCESS_TEXT)) {
376 String query = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
378 getIntent().putExtra(C.SEARCH_TOKEN, query);
381 // Support opening dictionary file directly
382 if (intentAction != null && intentAction.equals(Intent.ACTION_VIEW)) {
383 Uri uri = intent.getData();
384 intent.putExtra(C.DICT_FILE, uri.toString());
385 dictFileTitleName = uri.getLastPathSegment();
387 dictRaf = getContentResolver().openAssetFileDescriptor(uri, "r").createInputStream().getChannel();
388 } catch (Exception e) {
389 dictionaryOpenFail(e);
394 @author Dominik Köppl If no dictionary is chosen, use the default
395 * dictionary specified in the preferences If this step does
396 * fail (no default dictionary specified), show a toast and
399 if (intent.getStringExtra(C.DICT_FILE) == null) {
400 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
401 if (dictfile != null)
402 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
404 String dictFilename = intent.getStringExtra(C.DICT_FILE);
405 if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null) {
406 final List<DictionaryInfo> dics = application.getDictionariesOnDevice(null);
407 final String search = intent.getStringExtra(C.SEARCH_TOKEN);
408 String bestFname = null;
409 String bestIndex = null;
410 int bestMatchLen = 2; // ignore shorter matches
411 AtomicBoolean dummy = new AtomicBoolean();
412 for (int i = 0; dictFilename == null && i < dics.size(); ++i) {
414 Log.d(LOG, "Checking dictionary " + dics.get(i).uncompressedFilename);
415 final File dictfile = application.getPath(dics.get(i).uncompressedFilename);
416 Dictionary dic = new Dictionary(new RandomAccessFile(dictfile, "r").getChannel());
417 for (int j = 0; j < dic.indices.size(); ++j) {
418 Index idx = dic.indices.get(j);
419 Log.d(LOG, "Checking index " + idx.shortName);
420 if (idx.findExact(search) != null) {
421 Log.d(LOG, "Found exact match");
422 dictFilename = dictfile.toString();
423 intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
426 int matchLen = getMatchLen(search, idx.findInsertionPoint(search, dummy));
427 Log.d(LOG, "Found partial match length " + matchLen);
428 if (matchLen > bestMatchLen) {
429 bestFname = dictfile.toString();
430 bestIndex = idx.shortName;
431 bestMatchLen = matchLen;
434 } catch (Exception e) {}
436 if (dictFilename == null && bestFname != null) {
437 dictFilename = bestFname;
438 intent.putExtra(C.INDEX_SHORT_NAME, bestIndex);
442 if (dictFilename == null) {
444 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
445 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
450 dictFile = new File(dictFilename);
453 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
455 public void onInit(int status) {
457 updateTTSLanguage(indexIndex);
462 if (dictRaf == null) {
463 dictFileTitleName = application.getDictionaryName(dictFile.getName());
464 dictRaf = new RandomAccessFile(dictFile, "r").getChannel();
466 this.setTitle("QuickDic: " + dictFileTitleName);
467 dictionary = new Dictionary(dictRaf);
468 } catch (Exception e) {
469 dictionaryOpenFail(e);
472 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
473 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
474 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
477 for (int i = 0; i < dictionary.indices.size(); ++i) {
478 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
483 Log.d(LOG, "Loading index " + indexIndex);
484 index = dictionary.indices.get(indexIndex);
485 getListView().setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
486 getListView().setEmptyView(findViewById(android.R.id.empty));
487 getListView().setOnItemClickListener(new OnItemClickListener() {
489 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
490 onListItemClick(getListView(), view, row, id);
494 setListAdapter(new IndexAdapter(index));
496 // Pre-load the Transliterator (will spawn its own thread)
497 TransliteratorManager.init(new TransliteratorManager.Callback() {
499 public void onTransliteratorReady() {
500 uiHandler.post(new Runnable() {
503 onSearchTextChange(searchView.getQuery().toString());
507 }, DictionaryApplication.threadBackground);
509 // Pre-load the collators.
510 new Thread(new Runnable() {
512 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
513 final long startMillis = System.currentTimeMillis();
515 for (final Index index : dictionary.indices) {
516 final String searchToken = index.sortedIndexEntries.get(0).token;
517 final IndexEntry entry = index.findExact(searchToken);
518 if (entry == null || !searchToken.equals(entry.token)) {
519 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
522 indexPrepFinished = true;
523 } catch (Exception e) {
525 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
527 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
531 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
534 typeface = Typeface.DEFAULT;
537 typeface = Typeface.SERIF;
540 typeface = Typeface.SANS_SERIF;
543 typeface = Typeface.MONOSPACE;
546 if ("FreeSerif.ttf.jpg".equals(fontName)) {
547 fontName = "FreeSerif.otf.jpg";
550 typeface = Typeface.createFromAsset(getAssets(), fontName);
551 } catch (Exception e) {
552 Log.w(LOG, "Exception trying to use typeface, using default.", e);
554 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
555 Toast.LENGTH_LONG).show();
559 if (typeface == null) {
560 Log.w(LOG, "Unable to create typeface, using default.");
561 typeface = Typeface.DEFAULT;
563 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
565 fontSizeSp = Integer.parseInt(fontSize.trim());
566 } catch (NumberFormatException e) {
571 registerForContextMenu(getListView());
574 wordList = application.getWordListFile();
575 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
577 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
578 !getPackageManager().hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN));
579 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
581 onCreateSetupActionBarAndSearchView();
583 View floatSwapButton = findViewById(R.id.floatSwapButton);
584 floatSwapButton.setOnLongClickListener(new OnLongClickListener() {
586 public boolean onLongClick(View v) {
587 onLanguageButtonLongClick(v.getContext());
592 // Set the search text from the intent, then the saved state.
593 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
594 if (savedInstanceState != null) {
595 text = savedInstanceState.getString(C.SEARCH_TOKEN);
601 searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
603 public boolean onSuggestionSelect(int position) {
608 public boolean onSuggestionClick(int position) {
609 setSearchText(searchHistory.get(position), true);
613 searchView.setSuggestionsAdapter(new CursorAdapter(this, text.isEmpty() ? searchHistoryCursor : null, 0) {
615 public View newView(Context context, Cursor c, ViewGroup p) {
616 TextView v = new TextView(context);
617 v.setTextColor(textColorFg);
618 v.setTypeface(typeface);
619 v.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
623 public void bindView(View v, Context context, Cursor c) {
624 TextView t = (TextView)v;
625 t.setText(c.getString(1));
628 // Set up search history
629 addToSearchHistory(text);
631 setSearchText(text, true);
632 Log.d(LOG, "Trying to restore searchText=" + text);
634 setDictionaryPrefs(this, dictFile, index.shortName);
637 searchView.requestFocus();
639 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
640 // getListView().setCacheColorHint(0);
643 private void onCreateSetupActionBarAndSearchView() {
644 ActionBar actionBar = getSupportActionBar();
645 actionBar.setDisplayShowTitleEnabled(false);
646 actionBar.setDisplayShowHomeEnabled(false);
647 actionBar.setDisplayHomeAsUpEnabled(false);
649 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
651 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
652 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
653 customSearchView.setLayoutParams(layoutParams);
655 languageButton = new ImageButton(customSearchView.getContext());
656 languageButton.setId(R.id.languageButton);
657 languageButton.setScaleType(ScaleType.FIT_CENTER);
658 languageButton.setOnClickListener(new OnClickListener() {
660 public void onClick(View v) {
661 onLanguageButtonLongClick(v.getContext());
664 languageButton.setAdjustViewBounds(true);
665 LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
666 customSearchView.addView(languageButton, lpb);
668 searchView = new SearchView(getSupportActionBar().getThemedContext());
669 searchView.setId(R.id.searchView);
671 // Get rid of search icon, it takes up too much space.
672 // There is still text saying "search" in the search field.
673 searchView.setIconifiedByDefault(true);
674 searchView.setIconified(false);
676 searchView.setQueryHint(getString(R.string.searchText));
677 searchView.setSubmitButtonEnabled(false);
678 searchView.setInputType(InputType.TYPE_CLASS_TEXT);
679 searchView.setImeOptions(
680 EditorInfo.IME_ACTION_DONE |
681 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
682 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
684 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
685 onQueryTextListener = new OnQueryTextListener() {
687 public boolean onQueryTextSubmit(String query) {
688 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
689 addToSearchHistory(searchView.getQuery().toString());
695 public boolean onQueryTextChange(String newText) {
696 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
697 onSearchTextChange(searchView.getQuery().toString());
701 searchView.setOnQueryTextListener(onQueryTextListener);
702 searchView.setFocusable(true);
703 searchTextView = (AutoCompleteTextView)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
704 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
705 FrameLayout.LayoutParams.WRAP_CONTENT, 1);
706 customSearchView.addView(searchView, lp);
708 actionBar.setCustomView(customSearchView);
709 actionBar.setDisplayShowCustomEnabled(true);
711 // Avoid wasting space on large left inset
712 Toolbar tb = (Toolbar)customSearchView.getParent();
713 tb.setContentInsetsRelative(0, 0);
715 getListView().setNextFocusLeftId(R.id.searchView);
716 findViewById(R.id.floatSwapButton).setNextFocusRightId(R.id.languageButton);
717 languageButton.setNextFocusLeftId(R.id.floatSwapButton);
721 protected void onResume() {
722 Log.d(LOG, "onResume");
724 if (PreferenceActivity.prefsMightHaveChanged) {
725 PreferenceActivity.prefsMightHaveChanged = false;
727 startActivity(getIntent());
733 * Invoked when MyWebView returns, since the user might have clicked some
734 * hypertext in the MyWebView.
737 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
738 super.onActivityResult(requestCode, resultCode, result);
739 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
740 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
741 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
745 private static void setDictionaryPrefs(final Context context, final File dictFile,
746 final String indexShortName) {
747 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
749 if (dictFile != null) {
750 prefs.putString(C.DICT_FILE, dictFile.getPath());
751 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
753 prefs.remove(C.SEARCH_TOKEN); // Don't need to save search token.
758 protected void onDestroy() {
760 if (dictRaf == null) {
764 final SearchOperation searchOperation = currentSearchOperation;
765 currentSearchOperation = null;
767 // Before we close the RAF, we have to wind the current search down.
768 if (searchOperation != null) {
769 Log.d(LOG, "Interrupting search to shut down.");
770 currentSearchOperation = null;
771 searchOperation.interrupted.set(true);
773 searchExecutor.shutdownNow();
774 textToSpeech.shutdown();
778 setListAdapter(null);
781 Log.d(LOG, "Closing RAF.");
783 } catch (IOException e) {
784 Log.e(LOG, "Failed to close dictionary", e);
789 // --------------------------------------------------------------------------
791 // --------------------------------------------------------------------------
793 private void showKeyboard() {
794 // For some reason, this doesn't always work the first time.
795 // One way to replicate the problem:
796 // Press the "task switch" button repeatedly to pause and resume
797 for (int delay = 1; delay <= 101; delay += 100) {
798 searchView.postDelayed(new Runnable() {
801 Log.d(LOG, "Trying to show soft keyboard.");
802 final boolean searchTextHadFocus = searchView.hasFocus();
803 searchView.requestFocusFromTouch();
804 searchTextView.requestFocus();
805 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
806 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
807 manager.showSoftInput(searchTextView, InputMethodManager.SHOW_IMPLICIT);
808 if (!searchTextHadFocus) {
814 searchView.post(new Runnable() {
817 searchTextView.setThreshold(0);
818 searchTextView.showDropDown();
823 private void hideKeyboard() {
824 Log.d(LOG, "Hide soft keyboard.");
825 searchView.clearFocus();
826 InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
827 manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
830 private void updateLangButton() {
831 final int flagId = IsoUtils.INSTANCE.getFlagIdForIsoCode(index.shortName);
833 languageButton.setImageResource(flagId);
835 if (indexIndex % 2 == 0) {
836 languageButton.setImageResource(android.R.drawable.ic_media_next);
838 languageButton.setImageResource(android.R.drawable.ic_media_previous);
841 updateTTSLanguage(indexIndex);
844 private void updateTTSLanguage(int i) {
845 if (!ttsReady || index == null || textToSpeech == null) {
846 Log.d(LOG, "Can't updateTTSLanguage.");
849 final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
850 Log.d(LOG, "Setting TTS locale to: " + locale);
852 final int ttsResult = textToSpeech.setLanguage(locale);
853 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
854 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
855 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
857 } catch (Exception e) {
859 Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
863 public void onSearchButtonClick(View dummy) {
864 if (!searchView.hasFocus()) {
865 searchView.requestFocus();
867 if (searchView.getQuery().toString().length() > 0) {
868 searchView.setQuery("", false);
871 searchView.setIconified(false);
874 public void onLanguageButtonClick(View dummy) {
875 if (dictionary.indices.size() == 1) {
876 // No need to work to switch indices.
879 if (currentSearchOperation != null) {
880 currentSearchOperation.interrupted.set(true);
881 currentSearchOperation = null;
883 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
884 searchView.getQuery().toString(), false);
887 private void onLanguageButtonLongClick(final Context context) {
888 final Dialog dialog = new Dialog(context);
889 dialog.setContentView(R.layout.select_dictionary_dialog);
890 dialog.setTitle(R.string.selectDictionary);
892 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
894 ListView listView = dialog.findViewById(android.R.id.list);
895 final Button button = new Button(listView.getContext());
896 final String name = getString(R.string.dictionaryManager);
897 button.setText(name);
898 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
899 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
901 protected void onGo() {
903 DictionaryActivity.this.finish();
906 button.setOnClickListener(intentLauncher);
907 listView.addHeaderView(button);
909 listView.setItemsCanFocus(true);
910 listView.setAdapter(new BaseAdapter() {
912 public View getView(int position, View convertView, ViewGroup parent) {
913 final DictionaryInfo dictionaryInfo = getItem(position);
915 final LinearLayout result = new LinearLayout(parent.getContext());
917 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
918 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
919 final View button = IsoUtils.INSTANCE.createButton(parent.getContext(),
920 indexInfo, application.languageButtonPixels);
921 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
922 getLaunchIntent(getApplicationContext(),
923 application.getPath(dictionaryInfo.uncompressedFilename),
924 indexInfo.shortName, searchView.getQuery().toString())) {
926 protected void onGo() {
928 DictionaryActivity.this.finish();
931 button.setOnClickListener(intentLauncher);
932 if (i == indexIndex && dictFile != null &&
933 dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
934 button.setPressed(true);
936 result.addView(button);
939 final TextView nameView = new TextView(parent.getContext());
940 final String name = application
941 .getDictionaryName(dictionaryInfo.uncompressedFilename);
942 nameView.setText(name);
943 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
944 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
945 layoutParams.width = 0;
946 layoutParams.weight = 1.0f;
947 nameView.setLayoutParams(layoutParams);
948 nameView.setGravity(Gravity.CENTER_VERTICAL);
949 result.addView(nameView);
954 public long getItemId(int position) {
959 public DictionaryInfo getItem(int position) {
960 return installedDicts.get(position);
964 public int getCount() {
965 return installedDicts.size();
971 private void onUpDownButton(final boolean up) {
975 final int firstVisibleRow = getListView().getFirstVisiblePosition();
976 final RowBase row = index.rows.get(firstVisibleRow);
977 final TokenRow tokenRow = row.getTokenRow(true);
978 final int destIndexEntry;
980 if (row != tokenRow) {
981 destIndexEntry = tokenRow.referenceIndex;
983 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
987 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
989 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
990 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
991 setSearchText(dest.token, false);
992 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
996 private void onRandomWordButton() {
997 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
998 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
999 setSearchText(dest.token, false);
1000 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
1001 defocusSearchText();
1004 // --------------------------------------------------------------------------
1006 // --------------------------------------------------------------------------
1009 public boolean onCreateOptionsMenu(final Menu menu) {
1011 if (PreferenceManager.getDefaultSharedPreferences(this)
1012 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
1014 nextWordMenuItem = menu.add(getString(R.string.nextWord))
1015 .setIcon(R.drawable.arrow_down_float);
1016 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
1017 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1019 public boolean onMenuItemClick(MenuItem item) {
1020 onUpDownButton(false);
1026 previousWordMenuItem = menu.add(getString(R.string.previousWord))
1027 .setIcon(R.drawable.arrow_up_float);
1028 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
1029 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1031 public boolean onMenuItemClick(MenuItem item) {
1032 onUpDownButton(true);
1038 final MenuItem randomWordMenuItem = menu.add(getString(R.string.randomWord));
1039 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1041 public boolean onMenuItemClick(MenuItem item) {
1042 onRandomWordButton();
1048 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
1049 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
1050 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1051 public boolean onMenuItemClick(final MenuItem menuItem) {
1052 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
1060 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
1061 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
1062 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1063 public boolean onMenuItemClick(final MenuItem menuItem) {
1064 final Context context = getListView().getContext();
1065 final Dialog dialog = new Dialog(context);
1066 dialog.setContentView(R.layout.about_dictionary_dialog);
1067 final TextView textView = dialog.findViewById(R.id.text);
1069 dialog.setTitle(dictFileTitleName);
1071 final StringBuilder builder = new StringBuilder();
1072 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
1073 if (dictionaryInfo != null) {
1075 dictionaryInfo.uncompressedBytes = dictRaf.size();
1076 } catch (IOException e) {
1078 builder.append(dictionaryInfo.dictInfo).append("\n\n");
1079 if (dictFile != null) {
1080 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
1084 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
1087 getString(R.string.dictionaryCreationTime,
1088 dictionaryInfo.creationMillis)).append("\n");
1089 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
1090 builder.append("\n");
1091 builder.append(getString(R.string.indexName, indexInfo.shortName))
1094 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
1097 builder.append("\n");
1098 builder.append(getString(R.string.sources)).append("\n");
1099 for (final EntrySource source : dictionary.sources) {
1101 getString(R.string.sourceInfo, source.getName(),
1102 source.getNumEntries())).append("\n");
1105 textView.setText(builder.toString());
1108 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
1109 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
1110 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
1111 dialog.getWindow().setAttributes(layoutParams);
1117 DictionaryApplication.onCreateGlobalOptionsMenu(this, menu);
1122 // --------------------------------------------------------------------------
1123 // Context Menu + clicks
1124 // --------------------------------------------------------------------------
1127 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1128 final AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
1129 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
1131 if (clickOpensContextMenu && (row instanceof HtmlEntry.Row ||
1132 (row instanceof TokenRow && ((TokenRow)row).getIndexEntry().htmlEntries.size() > 0))) {
1133 final List<HtmlEntry> html = row instanceof TokenRow ? ((TokenRow)row).getIndexEntry().htmlEntries : Collections.singletonList(((HtmlEntry.Row)row).getEntry());
1134 final String highlight = row instanceof HtmlEntry.Row ? row.getTokenRow(true).getToken() : null;
1135 final MenuItem open = menu.add("Open");
1136 open.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1137 public boolean onMenuItemClick(MenuItem item) {
1138 showHtml(html, highlight);
1144 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
1145 wordList.getName()));
1147 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1148 public boolean onMenuItemClick(android.view.MenuItem item) {
1149 onAppendToWordList(row);
1154 final android.view.MenuItem share = menu.add("Share");
1155 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1156 public boolean onMenuItemClick(android.view.MenuItem item) {
1157 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
1158 shareIntent.setType("text/plain");
1159 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
1161 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
1162 row.getRawText(saveOnlyFirstSubentry));
1163 startActivity(shareIntent);
1168 final android.view.MenuItem copy = menu.add(android.R.string.copy);
1169 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1170 public boolean onMenuItemClick(android.view.MenuItem item) {
1176 if (selectedSpannableText != null) {
1177 final String selectedText = selectedSpannableText;
1178 final android.view.MenuItem searchForSelection = menu.add(getString(
1179 R.string.searchForSelection,
1180 selectedSpannableText));
1182 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1183 public boolean onMenuItemClick(android.view.MenuItem item) {
1184 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
1188 // Rats, this won't be shown:
1189 //searchForSelection.setIcon(R.drawable.abs__ic_search);
1192 if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
1193 final android.view.MenuItem speak = menu.add(R.string.speak);
1194 final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
1195 updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
1196 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1198 public boolean onMenuItemClick(android.view.MenuItem item) {
1199 textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
1200 new HashMap<String, String>());
1205 if (row instanceof PairEntry.Row && ttsReady) {
1206 final List<Pair> pairs = ((PairEntry.Row)row).getEntry().pairs;
1207 final MenuItem speakLeft = menu.add(R.string.speak_left);
1208 speakLeft.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1210 public boolean onMenuItemClick(android.view.MenuItem item) {
1211 int idx = index.swapPairEntries ? 1 : 0;
1212 updateTTSLanguage(idx);
1214 for (Pair p : pairs) text += p.get(idx);
1215 text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1216 textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
1217 new HashMap<String, String>());
1221 final MenuItem speakRight = menu.add(R.string.speak_right);
1222 speakRight.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1224 public boolean onMenuItemClick(android.view.MenuItem item) {
1225 int idx = index.swapPairEntries ? 0 : 1;
1226 updateTTSLanguage(idx);
1228 for (Pair p : pairs) text += p.get(idx);
1229 text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1230 textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
1231 new HashMap<String, String>());
1238 private void jumpToTextFromHyperLink(
1239 final String selectedText, final int defaultIndexToUse) {
1240 int indexToUse = -1;
1242 for (int i = 0; i < dictionary.indices.size(); ++i) {
1243 final Index index = dictionary.indices.get(i);
1244 if (indexPrepFinished) {
1245 System.out.println("Doing index lookup: on " + selectedText);
1246 final IndexEntry indexEntry = index.findExact(selectedText);
1247 if (indexEntry != null) {
1248 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1249 .getTokenRow(false);
1250 if (tokenRow != null && tokenRow.hasMainEntry) {
1256 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1259 if (numFound != 1) {
1260 indexToUse = defaultIndexToUse;
1262 // Without this extra delay, the call to jumpToRow that this
1263 // invokes doesn't always actually have any effect.
1264 final int actualIndexToUse = indexToUse;
1265 getListView().postDelayed(new Runnable() {
1268 setIndexAndSearchText(actualIndexToUse, selectedText, true);
1274 * Called when user clicks outside of search text, so that they can start
1275 * typing again immediately.
1277 private void defocusSearchText() {
1278 // Log.d(LOG, "defocusSearchText");
1279 // Request focus so that if we start typing again, it clears the text
1281 getListView().requestFocus();
1283 // Visual indication that a new keystroke will clear the search text.
1284 // Doesn't seem to work unless searchText has focus.
1285 // searchView.selectAll();
1288 private void onListItemClick(ListView l, View v, int rowIdx, long id) {
1289 defocusSearchText();
1290 if (clickOpensContextMenu && dictRaf != null) {
1293 final RowBase row = (RowBase)getListAdapter().getItem(rowIdx);
1294 if (!(row instanceof PairEntry.Row)) {
1300 @SuppressLint("SimpleDateFormat")
1301 private void onAppendToWordList(final RowBase row) {
1302 defocusSearchText();
1304 final StringBuilder rawText = new StringBuilder();
1305 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1306 rawText.append(index.longName).append("\t");
1307 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1308 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1309 Log.d(LOG, "Writing : " + rawText);
1312 wordList.getParentFile().mkdirs();
1313 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1314 out.println(rawText);
1316 } catch (Exception e) {
1317 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1319 Toast.makeText(this,
1320 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1321 Toast.LENGTH_LONG).show();
1325 @SuppressWarnings("deprecation")
1326 private void onCopy(final RowBase row) {
1327 defocusSearchText();
1329 Log.d(LOG, "Copy, row=" + row);
1330 final StringBuilder result = new StringBuilder();
1331 result.append(row.getRawText(false));
1332 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1333 clipboardManager.setText(result.toString());
1334 Log.d(LOG, "Copied: " + result);
1338 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1339 if (event.getUnicodeChar() != 0) {
1340 if (!searchView.hasFocus()) {
1341 setSearchText("" + (char) event.getUnicodeChar(), true);
1342 searchView.requestFocus();
1346 if (keyCode == KeyEvent.KEYCODE_BACK) {
1347 // Log.d(LOG, "Clearing dictionary prefs.");
1348 // Pretend that we just autolaunched so that we won't do it again.
1349 // DictionaryManagerActivity.lastAutoLaunchMillis =
1350 // System.currentTimeMillis();
1352 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1353 Log.d(LOG, "Trying to hide soft keyboard.");
1354 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1355 View focus = getCurrentFocus();
1356 if (inputManager != null && focus != null) {
1357 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1358 InputMethodManager.HIDE_NOT_ALWAYS);
1362 return super.onKeyDown(keyCode, event);
1365 private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
1366 Log.d(LOG, "Changing index to: " + newIndex);
1367 if (newIndex == -1) {
1368 Log.e(LOG, "Invalid index.");
1371 if (newIndex != indexIndex) {
1372 indexIndex = newIndex;
1373 index = dictionary.indices.get(indexIndex);
1374 indexAdapter = new IndexAdapter(index);
1375 setListAdapter(indexAdapter);
1376 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1377 setDictionaryPrefs(this, dictFile, index.shortName);
1380 setSearchText(newSearchText, true, hideKeyboard);
1383 private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
1384 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1385 // Disable the listener, because sometimes it doesn't work.
1386 searchView.setOnQueryTextListener(null);
1387 searchView.setQuery(text, false);
1388 searchView.setOnQueryTextListener(onQueryTextListener);
1390 if (triggerSearch) {
1391 onSearchTextChange(text);
1394 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1400 private void setSearchText(final String text, final boolean triggerSearch) {
1401 setSearchText(text, triggerSearch, true);
1404 // --------------------------------------------------------------------------
1406 // --------------------------------------------------------------------------
1408 private void searchFinished(final SearchOperation searchOperation) {
1409 if (searchOperation.interrupted.get()) {
1410 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1413 if (searchOperation != this.currentSearchOperation) {
1414 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1418 final Index.IndexEntry searchResult = searchOperation.searchResult;
1419 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1421 currentSearchOperation = null;
1422 // Note: it's important to post to the ListView, otherwise
1423 // the jumpToRow will randomly not work.
1424 getListView().post(new Runnable() {
1427 if (currentSearchOperation == null) {
1428 if (searchResult != null) {
1432 jumpToRow(searchResult.startRow);
1433 } else if (searchOperation.multiWordSearchResult != null) {
1434 // Multi-row search....
1435 setFiltered(searchOperation);
1437 throw new IllegalStateException("This should never happen.");
1440 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1446 private void jumpToRow(final int row) {
1447 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1448 // getListView().requestFocusFromTouch();
1449 getListView().setSelectionFromTop(row, 0);
1450 getListView().setSelected(true);
1453 private static final Pattern WHITESPACE = Pattern.compile("\\s+");
1455 final class SearchOperation implements Runnable {
1457 final AtomicBoolean interrupted = new AtomicBoolean(false);
1459 final String searchText;
1461 List<String> searchTokens; // filled in for multiWord.
1465 long searchStartMillis;
1467 Index.IndexEntry searchResult;
1469 List<RowBase> multiWordSearchResult;
1471 boolean done = false;
1473 SearchOperation(final String searchText, final Index index) {
1474 this.searchText = StringUtil.normalizeWhitespace(searchText);
1478 public String toString() {
1479 return String.format("SearchOperation(%s,%s)", searchText, interrupted);
1485 searchStartMillis = System.currentTimeMillis();
1486 final String[] searchTokenArray = WHITESPACE.split(searchText);
1487 if (searchTokenArray.length == 1) {
1488 searchResult = index.findInsertionPoint(searchText, interrupted);
1490 searchTokens = Arrays.asList(searchTokenArray);
1491 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1495 "searchText=" + searchText + ", searchDuration="
1496 + (System.currentTimeMillis() - searchStartMillis)
1497 + ", interrupted=" + interrupted.get());
1498 if (!interrupted.get()) {
1499 uiHandler.post(new Runnable() {
1502 searchFinished(SearchOperation.this);
1506 Log.d(LOG, "interrupted, skipping searchFinished.");
1508 } catch (Exception e) {
1509 Log.e(LOG, "Failure during search (can happen during Activity close): " + e.getMessage());
1511 synchronized (this) {
1519 // --------------------------------------------------------------------------
1521 // --------------------------------------------------------------------------
1523 private void showHtml(final List<HtmlEntry> htmlEntries, final String htmlTextToHighlight) {
1524 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1526 if (typeface == Typeface.SERIF) { style = "font-family: serif;"; }
1527 else if (typeface == Typeface.SANS_SERIF) { style = "font-family: sans-serif;"; }
1528 else if (typeface == Typeface.MONOSPACE) { style = "font-family: monospace;"; }
1529 if (application.getSelectedTheme() == DictionaryApplication.Theme.DEFAULT)
1530 style += "background-color: black; color: white;";
1531 // Log.d(LOG, "html=" + html);
1532 startActivityForResult(
1533 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1534 "<html><head><meta name=\"viewport\" content=\"width=device-width\"></head><body style=\"%s\">%s</body></html>", style, html),
1535 htmlTextToHighlight, false),
1539 final class IndexAdapter extends BaseAdapter {
1541 private static final float PADDING_DEFAULT_DP = 8;
1543 private static final float PADDING_LARGE_DP = 16;
1547 final List<RowBase> rows;
1549 final Set<String> toHighlight;
1551 private int mPaddingDefault;
1553 private int mPaddingLarge;
1555 IndexAdapter(final Index index) {
1558 this.toHighlight = null;
1562 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1565 this.toHighlight = new LinkedHashSet<>(toHighlight);
1569 private void getMetrics() {
1571 // Get the screen's density scale
1572 // The previous method getResources().getDisplayMetrics()
1573 // used to occasionally trigger a null pointer exception,
1574 // so try this instead.
1575 // As it still crashes, add a fallback
1577 DisplayMetrics dm = new DisplayMetrics();
1578 getWindowManager().getDefaultDisplay().getMetrics(dm);
1580 } catch (NullPointerException ignored)
1582 // Convert the dps to pixels, based on density scale
1583 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1584 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1588 public int getCount() {
1593 public RowBase getItem(int position) {
1594 return rows.get(position);
1598 public long getItemId(int position) {
1599 return getItem(position).index();
1603 public int getViewTypeCount() {
1608 public int getItemViewType(int position) {
1609 final RowBase row = getItem(position);
1610 if (row instanceof PairEntry.Row) {
1611 final PairEntry entry = ((PairEntry.Row)row).getEntry();
1612 final int rowCount = entry.pairs.size();
1613 return rowCount > 1 ? 1 : 0;
1614 } else if (row instanceof TokenRow) {
1615 final IndexEntry indexEntry = ((TokenRow)row).getIndexEntry();
1616 return indexEntry.htmlEntries.isEmpty() ? 2 : 3;
1617 } else if (row instanceof HtmlEntry.Row) {
1620 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1625 public View getView(int position, View convertView, ViewGroup parent) {
1626 final RowBase row = getItem(position);
1627 if (row instanceof PairEntry.Row) {
1628 return getView(position, (PairEntry.Row) row, parent, (TableLayout)convertView);
1629 } else if (row instanceof TokenRow) {
1630 return getView((TokenRow) row, parent, (TextView)convertView);
1631 } else if (row instanceof HtmlEntry.Row) {
1632 return getView((HtmlEntry.Row) row, parent, (TextView)convertView);
1634 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1638 private void addBoldSpans(String token, String col1Text, Spannable col1Spannable) {
1640 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1641 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1642 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1643 startPos += token.length();
1647 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1648 TableLayout result) {
1649 final Context context = parent.getContext();
1650 final PairEntry entry = row.getEntry();
1651 final int rowCount = entry.pairs.size();
1652 if (result == null) {
1653 result = new TableLayout(context);
1654 result.setStretchAllColumns(true);
1655 // Because we have a Button inside a ListView row:
1656 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1657 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1658 result.setClickable(true);
1659 result.setFocusable(false);
1660 result.setLongClickable(true);
1661 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1663 result.setBackgroundResource(theme.normalRowBg);
1664 } else if (result.getChildCount() > rowCount) {
1665 result.removeViews(rowCount, result.getChildCount() - rowCount);
1668 for (int r = result.getChildCount(); r < rowCount; ++r) {
1669 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
1670 layoutParams.leftMargin = mPaddingLarge;
1672 final TableRow tableRow = new TableRow(result.getContext());
1674 final TextView col1 = new TextView(tableRow.getContext());
1675 final TextView col2 = new TextView(tableRow.getContext());
1676 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1677 col1.setTextIsSelectable(true);
1678 col2.setTextIsSelectable(true);
1680 col1.setTextColor(textColorFg);
1681 col2.setTextColor(textColorFg);
1686 col1.setTypeface(typeface);
1687 col2.setTypeface(typeface);
1688 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1689 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1690 // col2.setBackgroundResource(theme.otherLangBg);
1692 if (index.swapPairEntries) {
1693 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1694 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1696 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1697 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1700 // Set the columns in the table.
1702 tableRow.addView(col1, layoutParams);
1703 tableRow.addView(col2, layoutParams);
1705 for (int i = 0; i < 2; i++) {
1706 final TextView bullet = new TextView(tableRow.getContext());
1707 bullet.setText(" • ");
1708 LinearLayout wrapped = new LinearLayout(context);
1709 wrapped.setOrientation(LinearLayout.HORIZONTAL);
1710 LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0);
1711 wrapped.addView(bullet, p1);
1712 LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
1713 wrapped.addView(i == 0 ? col1 : col2, p2);
1714 tableRow.addView(wrapped, layoutParams);
1718 result.addView(tableRow);
1721 for (int r = 0; r < rowCount; ++r) {
1722 final TableRow tableRow = (TableRow)result.getChildAt(r);
1723 View left = tableRow.getChildAt(0);
1724 View right = tableRow.getChildAt(1);
1726 left = ((ViewGroup)left).getChildAt(1);
1727 right = ((ViewGroup)right).getChildAt(1);
1729 final TextView col1 = (TextView)left;
1730 final TextView col2 = (TextView)right;
1732 // Set what's in the columns.
1733 final Pair pair = entry.pairs.get(r);
1734 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1735 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1736 final Spannable col1Spannable = new SpannableString(col1Text);
1737 final Spannable col2Spannable = new SpannableString(col2Text);
1739 // Bold the token instances in col1.
1740 if (toHighlight != null) {
1741 for (final String token : toHighlight) {
1742 addBoldSpans(token, col1Text, col1Spannable);
1745 addBoldSpans(row.getTokenRow(true).getToken(), col1Text, col1Spannable);
1747 createTokenLinkSpans(col1, col1Spannable, col1Text);
1748 createTokenLinkSpans(col2, col2Spannable, col2Text);
1750 col1.setText(col1Spannable);
1751 col2.setText(col2Spannable);
1754 result.setOnClickListener(new TextView.OnClickListener() {
1756 public void onClick(View v) {
1757 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1764 private TextView getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1765 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1766 final String htmlTextToHighlight, ViewGroup parent, TextView textView) {
1767 final Context context = parent.getContext();
1768 if (textView == null) {
1769 textView = new TextView(context);
1770 // set up things invariant across one ItemViewType
1771 // ItemViewTypes handled here are:
1772 // 2: isTokenRow == true, htmlEntries.isEmpty() == true
1773 // 3: isTokenRow == true, htmlEntries.isEmpty() == false
1774 // 4: isTokenRow == false, htmlEntries.isEmpty() == false
1775 textView.setPadding(isTokenRow ? mPaddingDefault : mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1776 textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1777 textView.setLongClickable(true);
1779 textView.setTypeface(typeface);
1781 textView.setTextAppearance(context, theme.tokenRowFg);
1782 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1784 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1786 textView.setTextColor(textColorFg);
1787 if (!htmlEntries.isEmpty()) {
1788 textView.setClickable(true);
1789 textView.setMovementMethod(LinkMovementMethod.getInstance());
1793 textView.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1794 : theme.tokenRowOtherBg);
1796 // Make it so we can long-click on these token rows, too:
1797 final Spannable textSpannable = new SpannableString(text);
1798 createTokenLinkSpans(textView, textSpannable, text);
1800 if (!htmlEntries.isEmpty()) {
1801 final ClickableSpan clickableSpan = new ClickableSpan() {
1803 public void onClick(View widget) {
1806 textSpannable.setSpan(clickableSpan, 0, text.length(),
1807 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1808 textView.setOnClickListener(new OnClickListener() {
1810 public void onClick(View v) {
1811 showHtml(htmlEntries, htmlTextToHighlight);
1815 textView.setText(textSpannable);
1819 private TextView getView(TokenRow row, ViewGroup parent, final TextView result) {
1820 final IndexEntry indexEntry = row.getIndexEntry();
1821 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1822 indexEntry.htmlEntries, null, parent, result);
1825 private TextView getView(HtmlEntry.Row row, ViewGroup parent, final TextView result) {
1826 final HtmlEntry htmlEntry = row.getEntry();
1827 final TokenRow tokenRow = row.getTokenRow(true);
1828 return getPossibleLinkToHtmlEntryView(false,
1829 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1830 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1836 private static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1838 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1839 final String text) {
1840 // Saw from the source code that LinkMovementMethod sets the selection!
1841 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1842 textView.setMovementMethod(LinkMovementMethod.getInstance());
1843 final Matcher matcher = CHAR_DASH.matcher(text);
1844 while (matcher.find()) {
1845 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(),
1847 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1851 private String selectedSpannableText = null;
1853 private int selectedSpannableIndex = -1;
1856 public boolean onTouchEvent(MotionEvent event) {
1857 selectedSpannableText = null;
1858 selectedSpannableIndex = -1;
1859 return super.onTouchEvent(event);
1862 private class TextViewLongClickListener implements OnLongClickListener {
1865 private TextViewLongClickListener(final int index) {
1870 public boolean onLongClick(final View v) {
1871 final TextView textView = (TextView) v;
1872 final int start = textView.getSelectionStart();
1873 final int end = textView.getSelectionEnd();
1874 if (start >= 0 && end >= 0) {
1875 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1876 selectedSpannableIndex = index;
1882 private final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1885 private final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1888 // --------------------------------------------------------------------------
1890 // --------------------------------------------------------------------------
1892 private void onSearchTextChange(final String text) {
1893 if ("thadolina".equals(text)) {
1894 final Dialog dialog = new Dialog(getListView().getContext());
1895 dialog.setContentView(R.layout.thadolina_dialog);
1896 dialog.setTitle("Ti amo, amore mio!");
1897 final ImageView imageView = dialog.findViewById(R.id.thadolina_image);
1898 imageView.setOnClickListener(new OnClickListener() {
1900 public void onClick(View v) {
1901 final Intent intent = new Intent(Intent.ACTION_VIEW);
1902 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1903 startActivity(intent);
1908 if (dictRaf == null) {
1909 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1913 // if (!searchView.hasFocus()) {
1914 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1917 Log.d(LOG, "onSearchTextChange: " + text);
1918 if (currentSearchOperation != null) {
1919 Log.d(LOG, "Interrupting currentSearchOperation.");
1920 currentSearchOperation.interrupted.set(true);
1922 currentSearchOperation = new SearchOperation(text, index);
1923 searchExecutor.execute(currentSearchOperation);
1924 ((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
1925 searchView.getSuggestionsAdapter().swapCursor(text.isEmpty() ? searchHistoryCursor : null);
1926 searchView.getSuggestionsAdapter().notifyDataSetChanged();
1929 // --------------------------------------------------------------------------
1930 // Filtered results.
1931 // --------------------------------------------------------------------------
1933 private boolean isFiltered() {
1934 return rowsToShow != null;
1937 private void setFiltered(final SearchOperation searchOperation) {
1938 if (nextWordMenuItem != null) {
1939 nextWordMenuItem.setEnabled(false);
1940 previousWordMenuItem.setEnabled(false);
1942 rowsToShow = searchOperation.multiWordSearchResult;
1943 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1946 private void clearFiltered() {
1947 if (nextWordMenuItem != null) {
1948 nextWordMenuItem.setEnabled(true);
1949 previousWordMenuItem.setEnabled(true);
1951 setListAdapter(new IndexAdapter(index));