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.support.v7.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.LinkedHashSet;
113 import java.util.List;
114 import java.util.Locale;
115 import java.util.Random;
116 import java.util.Set;
117 import java.util.concurrent.ExecutorService;
118 import java.util.concurrent.Executors;
119 import java.util.concurrent.ThreadFactory;
120 import java.util.concurrent.atomic.AtomicBoolean;
121 import java.util.regex.Matcher;
122 import java.util.regex.Pattern;
124 public class DictionaryActivity extends AppCompatActivity {
126 private static final String LOG = "QuickDic";
128 private DictionaryApplication application;
130 private File dictFile = null;
131 private FileChannel dictRaf = null;
132 private String dictFileTitleName = null;
134 private Dictionary dictionary = null;
136 private int indexIndex = 0;
138 private Index index = null;
140 private List<RowBase> rowsToShow = null; // if not null, just show these rows.
142 private final Random rand = new Random();
144 private final Handler uiHandler = new Handler();
146 private final ExecutorService searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
148 public Thread newThread(@NonNull Runnable r) {
149 return new Thread(r, "searchExecutor");
153 private SearchOperation currentSearchOperation = null;
154 private final int MAX_SEARCH_HISTORY = 10;
155 private final ArrayList<String> searchHistory = new ArrayList<>(MAX_SEARCH_HISTORY);
156 private MatrixCursor searchHistoryCursor = new MatrixCursor(new String[] {"_id", "search"});
158 private TextToSpeech textToSpeech;
159 private volatile boolean ttsReady;
161 private Typeface typeface;
162 private DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
163 private int textColorFg = Color.BLACK;
164 private int fontSizeSp;
166 private ListView listView;
167 private ListView getListView() {
168 if (listView == null) {
169 listView = (ListView)findViewById(android.R.id.list);
174 private void setListAdapter(ListAdapter adapter) {
175 getListView().setAdapter(adapter);
178 private ListAdapter getListAdapter() {
179 return getListView().getAdapter();
182 private SearchView searchView;
183 private AutoCompleteTextView searchTextView;
184 private ImageButton languageButton;
185 private SearchView.OnQueryTextListener onQueryTextListener;
187 private MenuItem nextWordMenuItem;
188 private MenuItem previousWordMenuItem;
191 private File wordList = null;
192 private boolean saveOnlyFirstSubentry = false;
193 private boolean clickOpensContextMenu = false;
195 // Visible for testing.
196 private ListAdapter indexAdapter = null;
199 * For some languages, loading the transliterators used in this search takes
200 * a long time, so we fire it up on a different thread, and don't invoke it
201 * from the main thread until it's already finished once.
203 private volatile boolean indexPrepFinished = false;
205 public DictionaryActivity() {
208 public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
209 final String searchToken) {
210 final Intent intent = new Intent(c, DictionaryActivity.class);
211 intent.putExtra(C.DICT_FILE, dictFile.getPath());
212 intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
213 intent.putExtra(C.SEARCH_TOKEN, searchToken);
214 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
219 protected void onSaveInstanceState(final Bundle outState) {
220 super.onSaveInstanceState(outState);
221 Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
222 outState.putString(C.INDEX_SHORT_NAME, index.shortName);
223 outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
224 outState.putStringArrayList(C.SEARCH_HISTORY, searchHistory);
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 saveSearchHistory() {
258 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
259 final SharedPreferences.Editor ed = prefs.edit();
260 for (int i = 0; i < searchHistory.size(); i++) {
261 ed.putString("history" + i, searchHistory.get(i));
263 ed.remove("history" + searchHistory.size());
267 private void addToSearchHistory() {
268 addToSearchHistory(searchView.getQuery().toString());
271 private void addToSearchHistory(String text) {
272 if (text == null || text.isEmpty()) return;
273 int exists = searchHistory.indexOf(text);
274 if (exists >= 0) searchHistory.remove(exists);
275 else if (searchHistory.size() >= MAX_SEARCH_HISTORY) searchHistory.remove(searchHistory.size() - 1);
276 searchHistory.add(0, text);
277 searchHistoryCursor = new MatrixCursor(new String[] {"_id", "search"});
278 for (int i = 0; i < searchHistory.size(); i++) {
279 final Object[] row = {i, searchHistory.get(i)};
280 searchHistoryCursor.addRow(row);
282 if (searchView.getSuggestionsAdapter().getCursor() != null) {
283 searchView.getSuggestionsAdapter().swapCursor(searchHistoryCursor);
284 searchView.getSuggestionsAdapter().notifyDataSetChanged();
289 public void onCreate(Bundle savedInstanceState) {
290 DictionaryApplication.INSTANCE.init(getApplicationContext());
291 application = DictionaryApplication.INSTANCE;
292 // This needs to be before super.onCreate, otherwise ActionbarSherlock
293 // doesn't makes the background of the actionbar white when you're
294 // in the dark theme.
295 setTheme(application.getSelectedTheme().themeId);
297 Log.d(LOG, "onCreate:" + this);
298 super.onCreate(savedInstanceState);
300 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
302 // Don't auto-launch if this fails.
303 prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
305 setContentView(R.layout.dictionary_activity);
307 theme = application.getSelectedTheme();
308 textColorFg = getResources().getColor(theme.tokenRowFgColor);
310 if (dictRaf != null) {
313 } catch (IOException e) {
314 Log.e(LOG, "Failed to close dictionary", e);
319 final Intent intent = getIntent();
320 String intentAction = intent.getAction();
322 @author Dominik Köppl Querying the Intent
323 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
324 * Arguments: SearchManager.QUERY -> the phrase to search from
325 * -> language in which the phrase is written to -> to which
326 * language shall be translated
328 if ("com.hughes.action.ACTION_SEARCH_DICT".equals(intentAction)) {
329 String query = intent.getStringExtra(SearchManager.QUERY);
330 String from = intent.getStringExtra("from");
332 from = from.toLowerCase(Locale.US);
333 String to = intent.getStringExtra("to");
335 to = to.toLowerCase(Locale.US);
337 getIntent().putExtra(C.SEARCH_TOKEN, query);
339 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null)) {
340 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
341 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
342 for (DictionaryInfo info : dicts) {
343 boolean hasFrom = from == null;
344 boolean hasTo = to == null;
345 for (IndexInfo index : info.indexInfos) {
346 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
348 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
351 if (hasFrom && hasTo) {
354 for (; which_index < info.indexInfos.size(); ++which_index) {
355 if (info.indexInfos.get(which_index).shortName.toLowerCase(
356 Locale.US).equals(from))
359 intent.putExtra(C.INDEX_SHORT_NAME,
360 info.indexInfos.get(which_index).shortName);
363 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
372 @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
373 * simple query Arguments follow from android standard (see
376 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH)) {
377 String query = intent.getStringExtra(SearchManager.QUERY);
379 getIntent().putExtra(C.SEARCH_TOKEN, query);
381 if (intentAction != null && intentAction.equals(Intent.ACTION_SEND)) {
382 String query = intent.getStringExtra(Intent.EXTRA_TEXT);
384 getIntent().putExtra(C.SEARCH_TOKEN, query);
387 * This processes text on M+ devices where QuickDic shows up in the context menu.
389 if (intentAction != null && intentAction.equals(Intent.ACTION_PROCESS_TEXT)) {
390 String query = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
392 getIntent().putExtra(C.SEARCH_TOKEN, query);
395 // Support opening dictionary file directly
396 if (intentAction != null && intentAction.equals(Intent.ACTION_VIEW)) {
397 Uri uri = intent.getData();
398 intent.putExtra(C.DICT_FILE, uri.toString());
399 dictFileTitleName = uri.getLastPathSegment();
401 dictRaf = getContentResolver().openAssetFileDescriptor(uri, "r").createInputStream().getChannel();
402 } catch (Exception e) {
403 dictionaryOpenFail(e);
408 @author Dominik Köppl If no dictionary is chosen, use the default
409 * dictionary specified in the preferences If this step does
410 * fail (no default dictionary specified), show a toast and
413 if (intent.getStringExtra(C.DICT_FILE) == null) {
414 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
415 if (dictfile != null)
416 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
418 String dictFilename = intent.getStringExtra(C.DICT_FILE);
419 if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null) {
420 final List<DictionaryInfo> dics = application.getDictionariesOnDevice(null);
421 final String search = intent.getStringExtra(C.SEARCH_TOKEN);
422 String bestFname = null;
423 String bestIndex = null;
424 int bestMatchLen = 2; // ignore shorter matches
425 AtomicBoolean dummy = new AtomicBoolean();
426 for (int i = 0; dictFilename == null && i < dics.size(); ++i) {
428 Log.d(LOG, "Checking dictionary " + dics.get(i).uncompressedFilename);
429 final File dictfile = application.getPath(dics.get(i).uncompressedFilename);
430 Dictionary dic = new Dictionary(new RandomAccessFile(dictfile, "r").getChannel());
431 for (int j = 0; j < dic.indices.size(); ++j) {
432 Index idx = dic.indices.get(j);
433 Log.d(LOG, "Checking index " + idx.shortName);
434 if (idx.findExact(search) != null) {
435 Log.d(LOG, "Found exact match");
436 dictFilename = dictfile.toString();
437 intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
440 int matchLen = getMatchLen(search, idx.findInsertionPoint(search, dummy));
441 Log.d(LOG, "Found partial match length " + matchLen);
442 if (matchLen > bestMatchLen) {
443 bestFname = dictfile.toString();
444 bestIndex = idx.shortName;
445 bestMatchLen = matchLen;
448 } catch (Exception e) {}
450 if (dictFilename == null && bestFname != null) {
451 dictFilename = bestFname;
452 intent.putExtra(C.INDEX_SHORT_NAME, bestIndex);
456 if (dictFilename == null) {
458 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
459 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
464 dictFile = new File(dictFilename);
467 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
469 public void onInit(int status) {
471 updateTTSLanguage(indexIndex);
476 if (dictRaf == null) {
477 dictFileTitleName = application.getDictionaryName(dictFile.getName());
478 dictRaf = new RandomAccessFile(dictFile, "r").getChannel();
480 this.setTitle("QuickDic: " + dictFileTitleName);
481 dictionary = new Dictionary(dictRaf);
482 } catch (Exception e) {
483 dictionaryOpenFail(e);
486 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
487 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
488 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
491 for (int i = 0; i < dictionary.indices.size(); ++i) {
492 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
497 Log.d(LOG, "Loading index " + indexIndex);
498 index = dictionary.indices.get(indexIndex);
499 getListView().setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
500 getListView().setEmptyView(findViewById(android.R.id.empty));
501 getListView().setOnItemClickListener(new OnItemClickListener() {
503 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
504 onListItemClick(getListView(), view, row, id);
508 setListAdapter(new IndexAdapter(index));
510 // Pre-load the Transliterator (will spawn its own thread)
511 TransliteratorManager.init(new TransliteratorManager.Callback() {
513 public void onTransliteratorReady() {
514 uiHandler.post(new Runnable() {
517 onSearchTextChange(searchView.getQuery().toString());
521 }, DictionaryApplication.threadBackground);
523 // Pre-load the collators.
524 new Thread(new Runnable() {
526 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
527 final long startMillis = System.currentTimeMillis();
529 for (final Index index : dictionary.indices) {
530 final String searchToken = index.sortedIndexEntries.get(0).token;
531 final IndexEntry entry = index.findExact(searchToken);
532 if (entry == null || !searchToken.equals(entry.token)) {
533 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
536 indexPrepFinished = true;
537 } catch (Exception e) {
539 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
541 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
545 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
548 typeface = Typeface.DEFAULT;
551 typeface = Typeface.SERIF;
554 typeface = Typeface.SANS_SERIF;
557 typeface = Typeface.MONOSPACE;
560 if ("FreeSerif.ttf.jpg".equals(fontName)) {
561 fontName = "FreeSerif.otf.jpg";
564 typeface = Typeface.createFromAsset(getAssets(), fontName);
565 } catch (Exception e) {
566 Log.w(LOG, "Exception trying to use typeface, using default.", e);
568 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
569 Toast.LENGTH_LONG).show();
573 if (typeface == null) {
574 Log.w(LOG, "Unable to create typeface, using default.");
575 typeface = Typeface.DEFAULT;
577 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
579 fontSizeSp = Integer.parseInt(fontSize.trim());
580 } catch (NumberFormatException e) {
585 registerForContextMenu(getListView());
588 wordList = application.getWordListFile();
589 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
591 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
592 !getPackageManager().hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN));
593 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
595 onCreateSetupActionBarAndSearchView();
597 View floatSwapButton = findViewById(R.id.floatSwapButton);
598 floatSwapButton.setOnLongClickListener(new OnLongClickListener() {
600 public boolean onLongClick(View v) {
601 onLanguageButtonLongClick(v.getContext());
606 // Set the search text from the intent, then the saved state.
607 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
608 if (savedInstanceState != null) {
609 text = savedInstanceState.getString(C.SEARCH_TOKEN);
615 searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
617 public boolean onSuggestionSelect(int position) {
622 public boolean onSuggestionClick(int position) {
623 String h = searchHistory.get(position);
624 addToSearchHistory(h);
625 setSearchText(h, true);
629 searchView.setSuggestionsAdapter(new CursorAdapter(this, text.isEmpty() ? searchHistoryCursor : null, 0) {
631 public View newView(Context context, Cursor c, ViewGroup p) {
632 TextView v = new TextView(context);
633 v.setTextColor(textColorFg);
634 v.setTypeface(typeface);
635 v.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
639 public void bindView(View v, Context context, Cursor c) {
640 TextView t = (TextView)v;
641 t.setText(c.getString(1));
645 // Set up search history
646 ArrayList<String> savedHistory = null;
647 if (savedInstanceState != null) savedHistory = savedInstanceState.getStringArrayList(C.SEARCH_HISTORY);
648 if (savedHistory != null && !savedHistory.isEmpty()) {
650 savedHistory = new ArrayList<>();
651 for (int i = 0; i < MAX_SEARCH_HISTORY; i++) {
652 String h = prefs.getString("history" + i, null);
653 if (h == null) break;
657 for (int i = savedHistory.size() - 1; i >= 0; i--) {
658 addToSearchHistory(savedHistory.get(i));
660 addToSearchHistory(text);
662 setSearchText(text, true);
663 Log.d(LOG, "Trying to restore searchText=" + text);
665 setDictionaryPrefs(this, dictFile, index.shortName);
668 searchView.requestFocus();
670 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
671 // getListView().setCacheColorHint(0);
674 private void onCreateSetupActionBarAndSearchView() {
675 ActionBar actionBar = getSupportActionBar();
676 actionBar.setDisplayShowTitleEnabled(false);
677 actionBar.setDisplayShowHomeEnabled(false);
678 actionBar.setDisplayHomeAsUpEnabled(false);
680 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
682 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
683 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
684 customSearchView.setLayoutParams(layoutParams);
686 languageButton = new ImageButton(customSearchView.getContext());
687 languageButton.setId(R.id.languageButton);
688 languageButton.setScaleType(ScaleType.FIT_CENTER);
689 languageButton.setOnClickListener(new OnClickListener() {
691 public void onClick(View v) {
692 onLanguageButtonLongClick(v.getContext());
695 languageButton.setAdjustViewBounds(true);
696 LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
697 customSearchView.addView(languageButton, lpb);
699 searchView = new SearchView(getSupportActionBar().getThemedContext());
700 searchView.setId(R.id.searchView);
702 // Get rid of search icon, it takes up too much space.
703 // There is still text saying "search" in the search field.
704 searchView.setIconifiedByDefault(true);
705 searchView.setIconified(false);
707 searchView.setQueryHint(getString(R.string.searchText));
708 searchView.setSubmitButtonEnabled(false);
709 searchView.setInputType(InputType.TYPE_CLASS_TEXT);
710 searchView.setImeOptions(
711 EditorInfo.IME_ACTION_DONE |
712 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
713 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
715 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
716 onQueryTextListener = new OnQueryTextListener() {
718 public boolean onQueryTextSubmit(String query) {
719 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
720 addToSearchHistory();
726 public boolean onQueryTextChange(String newText) {
727 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
728 onSearchTextChange(searchView.getQuery().toString());
732 searchView.setOnQueryTextListener(onQueryTextListener);
733 searchView.setFocusable(true);
734 searchTextView = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
735 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
736 FrameLayout.LayoutParams.WRAP_CONTENT, 1);
737 customSearchView.addView(searchView, lp);
739 actionBar.setCustomView(customSearchView);
740 actionBar.setDisplayShowCustomEnabled(true);
742 // Avoid wasting space on large left inset
743 Toolbar tb = (Toolbar)customSearchView.getParent();
744 tb.setContentInsetsRelative(0, 0);
746 getListView().setNextFocusLeftId(R.id.searchView);
747 findViewById(R.id.floatSwapButton).setNextFocusRightId(R.id.languageButton);
748 languageButton.setNextFocusLeftId(R.id.floatSwapButton);
752 protected void onResume() {
753 Log.d(LOG, "onResume");
755 if (PreferenceActivity.prefsMightHaveChanged) {
756 PreferenceActivity.prefsMightHaveChanged = false;
758 startActivity(getIntent());
764 * Invoked when MyWebView returns, since the user might have clicked some
765 * hypertext in the MyWebView.
768 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
769 super.onActivityResult(requestCode, resultCode, result);
770 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
771 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
772 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
776 private static void setDictionaryPrefs(final Context context, final File dictFile,
777 final String indexShortName) {
778 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
780 if (dictFile != null) {
781 prefs.putString(C.DICT_FILE, dictFile.getPath());
782 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
784 prefs.remove(C.SEARCH_TOKEN); // Don't need to save search token.
789 protected void onPause() {
791 addToSearchHistory();
796 protected void onDestroy() {
798 if (dictRaf == null) {
802 final SearchOperation searchOperation = currentSearchOperation;
803 currentSearchOperation = null;
805 // Before we close the RAF, we have to wind the current search down.
806 if (searchOperation != null) {
807 Log.d(LOG, "Interrupting search to shut down.");
808 currentSearchOperation = null;
809 searchOperation.interrupted.set(true);
811 searchExecutor.shutdownNow();
812 textToSpeech.shutdown();
816 setListAdapter(null);
819 Log.d(LOG, "Closing RAF.");
821 } catch (IOException e) {
822 Log.e(LOG, "Failed to close dictionary", e);
827 // --------------------------------------------------------------------------
829 // --------------------------------------------------------------------------
831 private void showKeyboard() {
832 // For some reason, this doesn't always work the first time.
833 // One way to replicate the problem:
834 // Press the "task switch" button repeatedly to pause and resume
835 for (int delay = 1; delay <= 101; delay += 100) {
836 searchView.postDelayed(new Runnable() {
839 Log.d(LOG, "Trying to show soft keyboard.");
840 final boolean searchTextHadFocus = searchView.hasFocus();
841 searchView.requestFocusFromTouch();
842 searchTextView.requestFocus();
843 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
844 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
845 manager.showSoftInput(searchTextView, InputMethodManager.SHOW_IMPLICIT);
846 if (!searchTextHadFocus) {
852 searchView.post(new Runnable() {
855 searchTextView.setThreshold(0);
856 searchTextView.showDropDown();
861 private void hideKeyboard() {
862 Log.d(LOG, "Hide soft keyboard.");
863 searchView.clearFocus();
864 InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
865 manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
868 private void updateLangButton() {
869 final int flagId = IsoUtils.INSTANCE.getFlagIdForIsoCode(index.shortName);
871 languageButton.setImageResource(flagId);
873 if (indexIndex % 2 == 0) {
874 languageButton.setImageResource(android.R.drawable.ic_media_next);
876 languageButton.setImageResource(android.R.drawable.ic_media_previous);
879 updateTTSLanguage(indexIndex);
882 @SuppressWarnings("deprecation")
883 private void speak(String text) {
884 textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
887 private void updateTTSLanguage(int i) {
888 if (!ttsReady || index == null || textToSpeech == null) {
889 Log.d(LOG, "Can't updateTTSLanguage.");
892 final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
893 Log.d(LOG, "Setting TTS locale to: " + locale);
895 final int ttsResult = textToSpeech.setLanguage(locale);
896 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
897 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
898 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
900 } catch (Exception e) {
902 Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
906 public void onSearchButtonClick(View dummy) {
907 if (!searchView.hasFocus()) {
908 searchView.requestFocus();
910 if (searchView.getQuery().toString().length() > 0) {
911 addToSearchHistory();
912 searchView.setQuery("", false);
915 searchView.setIconified(false);
918 public void onLanguageButtonClick(View dummy) {
919 if (dictionary.indices.size() == 1) {
920 // No need to work to switch indices.
923 if (currentSearchOperation != null) {
924 currentSearchOperation.interrupted.set(true);
925 currentSearchOperation = null;
927 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
928 searchView.getQuery().toString(), false);
931 private void onLanguageButtonLongClick(final Context context) {
932 final Dialog dialog = new Dialog(context);
933 dialog.setContentView(R.layout.select_dictionary_dialog);
934 dialog.setTitle(R.string.selectDictionary);
936 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
938 ListView listView = dialog.findViewById(android.R.id.list);
939 final Button button = new Button(listView.getContext());
940 final String name = getString(R.string.dictionaryManager);
941 button.setText(name);
942 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
943 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
945 protected void onGo() {
947 DictionaryActivity.this.finish();
950 button.setOnClickListener(intentLauncher);
951 listView.addHeaderView(button);
953 listView.setItemsCanFocus(true);
954 listView.setAdapter(new BaseAdapter() {
956 public View getView(int position, View convertView, ViewGroup parent) {
957 final DictionaryInfo dictionaryInfo = getItem(position);
959 final LinearLayout result = new LinearLayout(parent.getContext());
961 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
962 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
963 final View button = IsoUtils.INSTANCE.createButton(parent.getContext(),
964 indexInfo, application.languageButtonPixels);
965 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
966 getLaunchIntent(getApplicationContext(),
967 application.getPath(dictionaryInfo.uncompressedFilename),
968 indexInfo.shortName, searchView.getQuery().toString())) {
970 protected void onGo() {
972 DictionaryActivity.this.finish();
975 button.setOnClickListener(intentLauncher);
976 if (i == indexIndex && dictFile != null &&
977 dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
978 button.setPressed(true);
980 result.addView(button);
983 final TextView nameView = new TextView(parent.getContext());
984 final String name = application
985 .getDictionaryName(dictionaryInfo.uncompressedFilename);
986 nameView.setText(name);
987 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
988 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
989 layoutParams.width = 0;
990 layoutParams.weight = 1.0f;
991 nameView.setLayoutParams(layoutParams);
992 nameView.setGravity(Gravity.CENTER_VERTICAL);
993 result.addView(nameView);
998 public long getItemId(int position) {
1003 public DictionaryInfo getItem(int position) {
1004 return installedDicts.get(position);
1008 public int getCount() {
1009 return installedDicts.size();
1015 private void onUpDownButton(final boolean up) {
1019 final int firstVisibleRow = getListView().getFirstVisiblePosition();
1020 final RowBase row = index.rows.get(firstVisibleRow);
1021 final TokenRow tokenRow = row.getTokenRow(true);
1022 final int destIndexEntry;
1024 if (row != tokenRow) {
1025 destIndexEntry = tokenRow.referenceIndex;
1027 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
1031 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
1033 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
1034 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
1035 setSearchText(dest.token, false);
1036 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
1037 defocusSearchText();
1040 private void onRandomWordButton() {
1041 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
1042 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
1043 setSearchText(dest.token, false);
1044 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
1045 defocusSearchText();
1048 // --------------------------------------------------------------------------
1050 // --------------------------------------------------------------------------
1053 public boolean onCreateOptionsMenu(final Menu menu) {
1055 if (PreferenceManager.getDefaultSharedPreferences(this)
1056 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
1058 nextWordMenuItem = menu.add(getString(R.string.nextWord))
1059 .setIcon(R.drawable.arrow_down_float);
1060 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
1061 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1063 public boolean onMenuItemClick(MenuItem item) {
1064 onUpDownButton(false);
1070 previousWordMenuItem = menu.add(getString(R.string.previousWord))
1071 .setIcon(R.drawable.arrow_up_float);
1072 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
1073 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1075 public boolean onMenuItemClick(MenuItem item) {
1076 onUpDownButton(true);
1082 final MenuItem randomWordMenuItem = menu.add(getString(R.string.randomWord));
1083 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1085 public boolean onMenuItemClick(MenuItem item) {
1086 onRandomWordButton();
1092 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
1093 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
1094 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1095 public boolean onMenuItemClick(final MenuItem menuItem) {
1096 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
1104 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
1105 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
1106 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1107 public boolean onMenuItemClick(final MenuItem menuItem) {
1108 final Context context = getListView().getContext();
1109 final Dialog dialog = new Dialog(context);
1110 dialog.setContentView(R.layout.about_dictionary_dialog);
1111 final TextView textView = dialog.findViewById(R.id.text);
1113 dialog.setTitle(dictFileTitleName);
1115 final StringBuilder builder = new StringBuilder();
1116 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
1117 if (dictionaryInfo != null) {
1119 dictionaryInfo.uncompressedBytes = dictRaf.size();
1120 } catch (IOException e) {
1122 builder.append(dictionaryInfo.dictInfo).append("\n\n");
1123 if (dictFile != null) {
1124 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
1128 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
1131 getString(R.string.dictionaryCreationTime,
1132 dictionaryInfo.creationMillis)).append("\n");
1133 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
1134 builder.append("\n");
1135 builder.append(getString(R.string.indexName, indexInfo.shortName))
1138 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
1141 builder.append("\n");
1142 builder.append(getString(R.string.sources)).append("\n");
1143 for (final EntrySource source : dictionary.sources) {
1145 getString(R.string.sourceInfo, source.getName(),
1146 source.getNumEntries())).append("\n");
1149 textView.setText(builder.toString());
1152 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
1153 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
1154 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
1155 dialog.getWindow().setAttributes(layoutParams);
1161 DictionaryApplication.onCreateGlobalOptionsMenu(this, menu);
1166 // --------------------------------------------------------------------------
1167 // Context Menu + clicks
1168 // --------------------------------------------------------------------------
1171 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1172 final AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
1173 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
1175 if (clickOpensContextMenu && (row instanceof HtmlEntry.Row ||
1176 (row instanceof TokenRow && ((TokenRow)row).getIndexEntry().htmlEntries.size() > 0))) {
1177 final List<HtmlEntry> html = row instanceof TokenRow ? ((TokenRow)row).getIndexEntry().htmlEntries : Collections.singletonList(((HtmlEntry.Row)row).getEntry());
1178 final String highlight = row instanceof HtmlEntry.Row ? row.getTokenRow(true).getToken() : null;
1179 final MenuItem open = menu.add("Open");
1180 open.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1181 public boolean onMenuItemClick(MenuItem item) {
1182 showHtml(html, highlight);
1188 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
1189 wordList.getName()));
1191 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1192 public boolean onMenuItemClick(android.view.MenuItem item) {
1193 onAppendToWordList(row);
1198 final android.view.MenuItem share = menu.add("Share");
1199 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1200 public boolean onMenuItemClick(android.view.MenuItem item) {
1201 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
1202 shareIntent.setType("text/plain");
1203 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
1205 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
1206 row.getRawText(saveOnlyFirstSubentry));
1207 startActivity(shareIntent);
1212 final android.view.MenuItem copy = menu.add(android.R.string.copy);
1213 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1214 public boolean onMenuItemClick(android.view.MenuItem item) {
1220 if (selectedSpannableText != null) {
1221 final String selectedText = selectedSpannableText;
1222 final android.view.MenuItem searchForSelection = menu.add(getString(
1223 R.string.searchForSelection,
1224 selectedSpannableText));
1226 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1227 public boolean onMenuItemClick(android.view.MenuItem item) {
1228 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
1232 // Rats, this won't be shown:
1233 //searchForSelection.setIcon(R.drawable.abs__ic_search);
1236 if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
1237 final android.view.MenuItem speak = menu.add(R.string.speak);
1238 final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
1239 updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
1240 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1242 public boolean onMenuItemClick(android.view.MenuItem item) {
1248 if (row instanceof PairEntry.Row && ttsReady) {
1249 final List<Pair> pairs = ((PairEntry.Row)row).getEntry().pairs;
1250 final MenuItem speakLeft = menu.add(R.string.speak_left);
1251 speakLeft.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1253 public boolean onMenuItemClick(android.view.MenuItem item) {
1254 int idx = index.swapPairEntries ? 1 : 0;
1255 updateTTSLanguage(idx);
1257 for (Pair p : pairs) text += p.get(idx);
1258 text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1263 final MenuItem speakRight = menu.add(R.string.speak_right);
1264 speakRight.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1266 public boolean onMenuItemClick(android.view.MenuItem item) {
1267 int idx = index.swapPairEntries ? 0 : 1;
1268 updateTTSLanguage(idx);
1270 for (Pair p : pairs) text += p.get(idx);
1271 text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1279 private void jumpToTextFromHyperLink(
1280 final String selectedText, final int defaultIndexToUse) {
1281 int indexToUse = -1;
1283 for (int i = 0; i < dictionary.indices.size(); ++i) {
1284 final Index index = dictionary.indices.get(i);
1285 if (indexPrepFinished) {
1286 System.out.println("Doing index lookup: on " + selectedText);
1287 final IndexEntry indexEntry = index.findExact(selectedText);
1288 if (indexEntry != null) {
1289 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1290 .getTokenRow(false);
1291 if (tokenRow != null && tokenRow.hasMainEntry) {
1297 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1300 if (numFound != 1) {
1301 indexToUse = defaultIndexToUse;
1303 // Without this extra delay, the call to jumpToRow that this
1304 // invokes doesn't always actually have any effect.
1305 final int actualIndexToUse = indexToUse;
1306 getListView().postDelayed(new Runnable() {
1309 setIndexAndSearchText(actualIndexToUse, selectedText, true);
1310 addToSearchHistory(selectedText);
1316 * Called when user clicks outside of search text, so that they can start
1317 * typing again immediately.
1319 private void defocusSearchText() {
1320 // Log.d(LOG, "defocusSearchText");
1321 // Request focus so that if we start typing again, it clears the text
1323 getListView().requestFocus();
1325 // Visual indication that a new keystroke will clear the search text.
1326 // Doesn't seem to work unless searchText has focus.
1327 // searchView.selectAll();
1330 private void onListItemClick(ListView l, View v, int rowIdx, long id) {
1331 defocusSearchText();
1332 if (clickOpensContextMenu && dictRaf != null) {
1335 final RowBase row = (RowBase)getListAdapter().getItem(rowIdx);
1336 if (!(row instanceof PairEntry.Row)) {
1342 @SuppressLint("SimpleDateFormat")
1343 private void onAppendToWordList(final RowBase row) {
1344 defocusSearchText();
1346 final StringBuilder rawText = new StringBuilder();
1347 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1348 rawText.append(index.longName).append("\t");
1349 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1350 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1351 Log.d(LOG, "Writing : " + rawText);
1354 wordList.getParentFile().mkdirs();
1355 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1356 out.println(rawText);
1358 } catch (Exception e) {
1359 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1361 Toast.makeText(this,
1362 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1363 Toast.LENGTH_LONG).show();
1367 @SuppressWarnings("deprecation")
1368 private void onCopy(final RowBase row) {
1369 defocusSearchText();
1371 Log.d(LOG, "Copy, row=" + row);
1372 final StringBuilder result = new StringBuilder();
1373 result.append(row.getRawText(false));
1374 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1375 clipboardManager.setText(result.toString());
1376 Log.d(LOG, "Copied: " + result);
1380 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1381 if (event.getUnicodeChar() != 0) {
1382 if (!searchView.hasFocus()) {
1383 setSearchText("" + (char) event.getUnicodeChar(), true);
1384 searchView.requestFocus();
1388 if (keyCode == KeyEvent.KEYCODE_BACK) {
1389 // Log.d(LOG, "Clearing dictionary prefs.");
1390 // Pretend that we just autolaunched so that we won't do it again.
1391 // DictionaryManagerActivity.lastAutoLaunchMillis =
1392 // System.currentTimeMillis();
1394 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1395 Log.d(LOG, "Trying to hide soft keyboard.");
1396 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1397 View focus = getCurrentFocus();
1398 if (inputManager != null && focus != null) {
1399 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1400 InputMethodManager.HIDE_NOT_ALWAYS);
1404 return super.onKeyDown(keyCode, event);
1407 private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
1408 Log.d(LOG, "Changing index to: " + newIndex);
1409 if (newIndex == -1) {
1410 Log.e(LOG, "Invalid index.");
1413 if (newIndex != indexIndex) {
1414 indexIndex = newIndex;
1415 index = dictionary.indices.get(indexIndex);
1416 indexAdapter = new IndexAdapter(index);
1417 setListAdapter(indexAdapter);
1418 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1419 setDictionaryPrefs(this, dictFile, index.shortName);
1422 setSearchText(newSearchText, true, hideKeyboard);
1425 private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
1426 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1427 // Disable the listener, because sometimes it doesn't work.
1428 searchView.setOnQueryTextListener(null);
1429 searchView.setQuery(text, false);
1430 searchView.setOnQueryTextListener(onQueryTextListener);
1432 if (triggerSearch) {
1433 onSearchTextChange(text);
1436 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1442 private void setSearchText(final String text, final boolean triggerSearch) {
1443 setSearchText(text, triggerSearch, true);
1446 // --------------------------------------------------------------------------
1448 // --------------------------------------------------------------------------
1450 private void searchFinished(final SearchOperation searchOperation) {
1451 if (searchOperation.interrupted.get()) {
1452 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1455 if (searchOperation != this.currentSearchOperation) {
1456 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1460 final Index.IndexEntry searchResult = searchOperation.searchResult;
1461 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1463 currentSearchOperation = null;
1464 // Note: it's important to post to the ListView, otherwise
1465 // the jumpToRow will randomly not work.
1466 getListView().post(new Runnable() {
1469 if (currentSearchOperation == null) {
1470 if (searchResult != null) {
1474 jumpToRow(searchResult.startRow);
1475 } else if (searchOperation.multiWordSearchResult != null) {
1476 // Multi-row search....
1477 setFiltered(searchOperation);
1479 throw new IllegalStateException("This should never happen.");
1482 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1488 private void jumpToRow(final int row) {
1489 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1490 // getListView().requestFocusFromTouch();
1491 getListView().setSelectionFromTop(row, 0);
1492 getListView().setSelected(true);
1495 private static final Pattern WHITESPACE = Pattern.compile("\\s+");
1497 final class SearchOperation implements Runnable {
1499 final AtomicBoolean interrupted = new AtomicBoolean(false);
1501 final String searchText;
1503 List<String> searchTokens; // filled in for multiWord.
1507 long searchStartMillis;
1509 Index.IndexEntry searchResult;
1511 List<RowBase> multiWordSearchResult;
1513 boolean done = false;
1515 SearchOperation(final String searchText, final Index index) {
1516 this.searchText = StringUtil.normalizeWhitespace(searchText);
1520 public String toString() {
1521 return String.format("SearchOperation(%s,%s)", searchText, interrupted);
1527 searchStartMillis = System.currentTimeMillis();
1528 final String[] searchTokenArray = WHITESPACE.split(searchText);
1529 if (searchTokenArray.length == 1) {
1530 searchResult = index.findInsertionPoint(searchText, interrupted);
1532 searchTokens = Arrays.asList(searchTokenArray);
1533 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1537 "searchText=" + searchText + ", searchDuration="
1538 + (System.currentTimeMillis() - searchStartMillis)
1539 + ", interrupted=" + interrupted.get());
1540 if (!interrupted.get()) {
1541 uiHandler.post(new Runnable() {
1544 searchFinished(SearchOperation.this);
1548 Log.d(LOG, "interrupted, skipping searchFinished.");
1550 } catch (Exception e) {
1551 Log.e(LOG, "Failure during search (can happen during Activity close): " + e.getMessage());
1553 synchronized (this) {
1561 // --------------------------------------------------------------------------
1563 // --------------------------------------------------------------------------
1565 private void showHtml(final List<HtmlEntry> htmlEntries, final String htmlTextToHighlight) {
1566 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1568 if (typeface == Typeface.SERIF) { style = "font-family: serif;"; }
1569 else if (typeface == Typeface.SANS_SERIF) { style = "font-family: sans-serif;"; }
1570 else if (typeface == Typeface.MONOSPACE) { style = "font-family: monospace;"; }
1571 if (application.getSelectedTheme() == DictionaryApplication.Theme.DEFAULT)
1572 style += "background-color: black; color: white;";
1573 // Log.d(LOG, "html=" + html);
1574 startActivityForResult(
1575 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1576 "<html><head><meta name=\"viewport\" content=\"width=device-width\"></head><body style=\"%s\">%s</body></html>", style, html),
1577 htmlTextToHighlight, false),
1581 final class IndexAdapter extends BaseAdapter {
1583 private static final float PADDING_DEFAULT_DP = 8;
1585 private static final float PADDING_LARGE_DP = 16;
1589 final List<RowBase> rows;
1591 final Set<String> toHighlight;
1593 private int mPaddingDefault;
1595 private int mPaddingLarge;
1597 IndexAdapter(final Index index) {
1600 this.toHighlight = null;
1604 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1607 this.toHighlight = new LinkedHashSet<>(toHighlight);
1611 private void getMetrics() {
1613 // Get the screen's density scale
1614 // The previous method getResources().getDisplayMetrics()
1615 // used to occasionally trigger a null pointer exception,
1616 // so try this instead.
1617 // As it still crashes, add a fallback
1619 DisplayMetrics dm = new DisplayMetrics();
1620 getWindowManager().getDefaultDisplay().getMetrics(dm);
1622 } catch (NullPointerException ignored)
1624 // Convert the dps to pixels, based on density scale
1625 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1626 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1630 public int getCount() {
1635 public RowBase getItem(int position) {
1636 return rows.get(position);
1640 public long getItemId(int position) {
1641 return getItem(position).index();
1645 public int getViewTypeCount() {
1650 public int getItemViewType(int position) {
1651 final RowBase row = getItem(position);
1652 if (row instanceof PairEntry.Row) {
1653 final PairEntry entry = ((PairEntry.Row)row).getEntry();
1654 final int rowCount = entry.pairs.size();
1655 return rowCount > 1 ? 1 : 0;
1656 } else if (row instanceof TokenRow) {
1657 final IndexEntry indexEntry = ((TokenRow)row).getIndexEntry();
1658 return indexEntry.htmlEntries.isEmpty() ? 2 : 3;
1659 } else if (row instanceof HtmlEntry.Row) {
1662 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1667 public View getView(int position, View convertView, ViewGroup parent) {
1668 final RowBase row = getItem(position);
1669 if (row instanceof PairEntry.Row) {
1670 return getView(position, (PairEntry.Row) row, parent, (TableLayout)convertView);
1671 } else if (row instanceof TokenRow) {
1672 return getView((TokenRow) row, parent, (TextView)convertView);
1673 } else if (row instanceof HtmlEntry.Row) {
1674 return getView((HtmlEntry.Row) row, parent, (TextView)convertView);
1676 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1680 private void addBoldSpans(String token, String col1Text, Spannable col1Spannable) {
1682 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1683 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1684 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1685 startPos += token.length();
1689 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1690 TableLayout result) {
1691 final Context context = parent.getContext();
1692 final PairEntry entry = row.getEntry();
1693 final int rowCount = entry.pairs.size();
1694 if (result == null) {
1695 result = new TableLayout(context);
1696 result.setStretchAllColumns(true);
1697 // Because we have a Button inside a ListView row:
1698 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1699 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1700 result.setClickable(true);
1701 result.setFocusable(false);
1702 result.setLongClickable(true);
1703 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1705 result.setBackgroundResource(theme.normalRowBg);
1706 } else if (result.getChildCount() > rowCount) {
1707 result.removeViews(rowCount, result.getChildCount() - rowCount);
1710 for (int r = result.getChildCount(); r < rowCount; ++r) {
1711 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
1712 layoutParams.leftMargin = mPaddingLarge;
1714 final TableRow tableRow = new TableRow(result.getContext());
1716 final TextView col1 = new TextView(tableRow.getContext());
1717 final TextView col2 = new TextView(tableRow.getContext());
1718 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1719 col1.setTextIsSelectable(true);
1720 col2.setTextIsSelectable(true);
1722 col1.setTextColor(textColorFg);
1723 col2.setTextColor(textColorFg);
1728 col1.setTypeface(typeface);
1729 col2.setTypeface(typeface);
1730 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1731 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1732 // col2.setBackgroundResource(theme.otherLangBg);
1734 if (index.swapPairEntries) {
1735 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1736 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1738 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1739 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1742 // Set the columns in the table.
1744 tableRow.addView(col1, layoutParams);
1745 tableRow.addView(col2, layoutParams);
1747 for (int i = 0; i < 2; i++) {
1748 final TextView bullet = new TextView(tableRow.getContext());
1749 bullet.setText(" • ");
1750 LinearLayout wrapped = new LinearLayout(context);
1751 wrapped.setOrientation(LinearLayout.HORIZONTAL);
1752 LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0);
1753 wrapped.addView(bullet, p1);
1754 LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
1755 wrapped.addView(i == 0 ? col1 : col2, p2);
1756 tableRow.addView(wrapped, layoutParams);
1760 result.addView(tableRow);
1763 for (int r = 0; r < rowCount; ++r) {
1764 final TableRow tableRow = (TableRow)result.getChildAt(r);
1765 View left = tableRow.getChildAt(0);
1766 View right = tableRow.getChildAt(1);
1768 left = ((ViewGroup)left).getChildAt(1);
1769 right = ((ViewGroup)right).getChildAt(1);
1771 final TextView col1 = (TextView)left;
1772 final TextView col2 = (TextView)right;
1774 // Set what's in the columns.
1775 final Pair pair = entry.pairs.get(r);
1776 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1777 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1778 final Spannable col1Spannable = new SpannableString(col1Text);
1779 final Spannable col2Spannable = new SpannableString(col2Text);
1781 // Bold the token instances in col1.
1782 if (toHighlight != null) {
1783 for (final String token : toHighlight) {
1784 addBoldSpans(token, col1Text, col1Spannable);
1787 addBoldSpans(row.getTokenRow(true).getToken(), col1Text, col1Spannable);
1789 createTokenLinkSpans(col1, col1Spannable, col1Text);
1790 createTokenLinkSpans(col2, col2Spannable, col2Text);
1792 col1.setText(col1Spannable);
1793 col2.setText(col2Spannable);
1796 result.setOnClickListener(new TextView.OnClickListener() {
1798 public void onClick(View v) {
1799 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1806 private TextView getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1807 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1808 final String htmlTextToHighlight, ViewGroup parent, TextView textView) {
1809 final Context context = parent.getContext();
1810 if (textView == null) {
1811 textView = new TextView(context);
1812 // set up things invariant across one ItemViewType
1813 // ItemViewTypes handled here are:
1814 // 2: isTokenRow == true, htmlEntries.isEmpty() == true
1815 // 3: isTokenRow == true, htmlEntries.isEmpty() == false
1816 // 4: isTokenRow == false, htmlEntries.isEmpty() == false
1817 textView.setPadding(isTokenRow ? mPaddingDefault : mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1818 textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1819 textView.setLongClickable(true);
1821 textView.setTypeface(typeface);
1823 textView.setTextAppearance(context, theme.tokenRowFg);
1824 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1826 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1828 textView.setTextColor(textColorFg);
1829 if (!htmlEntries.isEmpty()) {
1830 textView.setClickable(true);
1831 textView.setMovementMethod(LinkMovementMethod.getInstance());
1835 textView.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1836 : theme.tokenRowOtherBg);
1838 // Make it so we can long-click on these token rows, too:
1839 final Spannable textSpannable = new SpannableString(text);
1840 createTokenLinkSpans(textView, textSpannable, text);
1842 if (!htmlEntries.isEmpty()) {
1843 final ClickableSpan clickableSpan = new ClickableSpan() {
1845 public void onClick(View widget) {
1848 textSpannable.setSpan(clickableSpan, 0, text.length(),
1849 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1850 textView.setOnClickListener(new OnClickListener() {
1852 public void onClick(View v) {
1853 showHtml(htmlEntries, htmlTextToHighlight);
1857 textView.setText(textSpannable);
1861 private TextView getView(TokenRow row, ViewGroup parent, final TextView result) {
1862 final IndexEntry indexEntry = row.getIndexEntry();
1863 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1864 indexEntry.htmlEntries, null, parent, result);
1867 private TextView getView(HtmlEntry.Row row, ViewGroup parent, final TextView result) {
1868 final HtmlEntry htmlEntry = row.getEntry();
1869 final TokenRow tokenRow = row.getTokenRow(true);
1870 return getPossibleLinkToHtmlEntryView(false,
1871 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1872 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1878 private static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1880 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1881 final String text) {
1882 // Saw from the source code that LinkMovementMethod sets the selection!
1883 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1884 textView.setMovementMethod(LinkMovementMethod.getInstance());
1885 final Matcher matcher = CHAR_DASH.matcher(text);
1886 while (matcher.find()) {
1887 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(),
1889 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1893 private String selectedSpannableText = null;
1895 private int selectedSpannableIndex = -1;
1898 public boolean onTouchEvent(MotionEvent event) {
1899 selectedSpannableText = null;
1900 selectedSpannableIndex = -1;
1901 return super.onTouchEvent(event);
1904 private class TextViewLongClickListener implements OnLongClickListener {
1907 private TextViewLongClickListener(final int index) {
1912 public boolean onLongClick(final View v) {
1913 final TextView textView = (TextView) v;
1914 final int start = textView.getSelectionStart();
1915 final int end = textView.getSelectionEnd();
1916 if (start >= 0 && end >= 0) {
1917 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1918 selectedSpannableIndex = index;
1924 private final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1927 private final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1930 // --------------------------------------------------------------------------
1932 // --------------------------------------------------------------------------
1934 private void onSearchTextChange(final String text) {
1935 if ("thadolina".equals(text)) {
1936 final Dialog dialog = new Dialog(getListView().getContext());
1937 dialog.setContentView(R.layout.thadolina_dialog);
1938 dialog.setTitle("Ti amo, amore mio!");
1939 final ImageView imageView = dialog.findViewById(R.id.thadolina_image);
1940 imageView.setOnClickListener(new OnClickListener() {
1942 public void onClick(View v) {
1943 final Intent intent = new Intent(Intent.ACTION_VIEW);
1944 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1945 startActivity(intent);
1950 if (dictRaf == null) {
1951 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1955 // if (!searchView.hasFocus()) {
1956 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1959 Log.d(LOG, "onSearchTextChange: " + text);
1960 if (currentSearchOperation != null) {
1961 Log.d(LOG, "Interrupting currentSearchOperation.");
1962 currentSearchOperation.interrupted.set(true);
1964 currentSearchOperation = new SearchOperation(text, index);
1965 searchExecutor.execute(currentSearchOperation);
1966 ((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
1967 searchView.getSuggestionsAdapter().swapCursor(text.isEmpty() ? searchHistoryCursor : null);
1968 searchView.getSuggestionsAdapter().notifyDataSetChanged();
1971 // --------------------------------------------------------------------------
1972 // Filtered results.
1973 // --------------------------------------------------------------------------
1975 private boolean isFiltered() {
1976 return rowsToShow != null;
1979 private void setFiltered(final SearchOperation searchOperation) {
1980 if (nextWordMenuItem != null) {
1981 nextWordMenuItem.setEnabled(false);
1982 previousWordMenuItem.setEnabled(false);
1984 rowsToShow = searchOperation.multiWordSearchResult;
1985 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1988 private void clearFiltered() {
1989 if (nextWordMenuItem != null) {
1990 nextWordMenuItem.setEnabled(true);
1991 previousWordMenuItem.setEnabled(true);
1993 setListAdapter(new IndexAdapter(index));