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());
225 outState.putStringArrayList(C.SEARCH_HISTORY, searchHistory);
228 private int getMatchLen(String search, Index.IndexEntry e) {
229 if (e == null) return 0;
230 for (int i = 0; i < search.length(); ++i) {
231 String a = search.substring(0, i + 1);
232 String b = e.token.substring(0, i + 1);
233 if (!a.equalsIgnoreCase(b))
236 return search.length();
239 private void dictionaryOpenFail(Exception e) {
240 Log.e(LOG, "Unable to load dictionary.", e);
241 if (dictRaf != null) {
243 setListAdapter(null);
246 } catch (IOException e1) {
247 Log.e(LOG, "Unable to close dictRaf.", e1);
252 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
253 Toast.LENGTH_LONG).show();
254 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
258 private void saveSearchHistory() {
259 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
260 final SharedPreferences.Editor ed = prefs.edit();
261 for (int i = 0; i < searchHistory.size(); i++) {
262 ed.putString("history" + i, searchHistory.get(i));
264 ed.remove("history" + searchHistory.size());
268 private void addToSearchHistory(String text) {
269 if (text == null || text.isEmpty()) return;
270 int exists = searchHistory.indexOf(text);
271 if (exists >= 0) searchHistory.remove(exists);
272 else if (searchHistory.size() >= MAX_SEARCH_HISTORY) searchHistory.remove(searchHistory.size() - 1);
273 searchHistory.add(0, text);
274 searchHistoryCursor = new MatrixCursor(new String[] {"_id", "search"});
275 for (int i = 0; i < searchHistory.size(); i++) {
276 final Object[] row = {i, searchHistory.get(i)};
277 searchHistoryCursor.addRow(row);
279 if (searchView.getSuggestionsAdapter().getCursor() != null) {
280 searchView.getSuggestionsAdapter().swapCursor(searchHistoryCursor);
281 searchView.getSuggestionsAdapter().notifyDataSetChanged();
286 public void onCreate(Bundle savedInstanceState) {
287 DictionaryApplication.INSTANCE.init(getApplicationContext());
288 application = DictionaryApplication.INSTANCE;
289 // This needs to be before super.onCreate, otherwise ActionbarSherlock
290 // doesn't makes the background of the actionbar white when you're
291 // in the dark theme.
292 setTheme(application.getSelectedTheme().themeId);
294 Log.d(LOG, "onCreate:" + this);
295 super.onCreate(savedInstanceState);
297 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
299 // Don't auto-launch if this fails.
300 prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
302 setContentView(R.layout.dictionary_activity);
304 theme = application.getSelectedTheme();
305 textColorFg = getResources().getColor(theme.tokenRowFgColor);
307 if (dictRaf != null) {
310 } catch (IOException e) {
311 Log.e(LOG, "Failed to close dictionary", e);
316 final Intent intent = getIntent();
317 String intentAction = intent.getAction();
319 @author Dominik Köppl Querying the Intent
320 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
321 * Arguments: SearchManager.QUERY -> the phrase to search from
322 * -> language in which the phrase is written to -> to which
323 * language shall be translated
325 if ("com.hughes.action.ACTION_SEARCH_DICT".equals(intentAction)) {
326 String query = intent.getStringExtra(SearchManager.QUERY);
327 String from = intent.getStringExtra("from");
329 from = from.toLowerCase(Locale.US);
330 String to = intent.getStringExtra("to");
332 to = to.toLowerCase(Locale.US);
334 getIntent().putExtra(C.SEARCH_TOKEN, query);
336 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null)) {
337 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
338 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
339 for (DictionaryInfo info : dicts) {
340 boolean hasFrom = from == null;
341 boolean hasTo = to == null;
342 for (IndexInfo index : info.indexInfos) {
343 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
345 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
348 if (hasFrom && hasTo) {
351 for (; which_index < info.indexInfos.size(); ++which_index) {
352 if (info.indexInfos.get(which_index).shortName.toLowerCase(
353 Locale.US).equals(from))
356 intent.putExtra(C.INDEX_SHORT_NAME,
357 info.indexInfos.get(which_index).shortName);
360 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
369 @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
370 * simple query Arguments follow from android standard (see
373 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH)) {
374 String query = intent.getStringExtra(SearchManager.QUERY);
376 getIntent().putExtra(C.SEARCH_TOKEN, query);
378 if (intentAction != null && intentAction.equals(Intent.ACTION_SEND)) {
379 String query = intent.getStringExtra(Intent.EXTRA_TEXT);
381 getIntent().putExtra(C.SEARCH_TOKEN, query);
384 * This processes text on M+ devices where QuickDic shows up in the context menu.
386 if (intentAction != null && intentAction.equals(Intent.ACTION_PROCESS_TEXT)) {
387 String query = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
389 getIntent().putExtra(C.SEARCH_TOKEN, query);
392 // Support opening dictionary file directly
393 if (intentAction != null && intentAction.equals(Intent.ACTION_VIEW)) {
394 Uri uri = intent.getData();
395 intent.putExtra(C.DICT_FILE, uri.toString());
396 dictFileTitleName = uri.getLastPathSegment();
398 dictRaf = getContentResolver().openAssetFileDescriptor(uri, "r").createInputStream().getChannel();
399 } catch (Exception e) {
400 dictionaryOpenFail(e);
405 @author Dominik Köppl If no dictionary is chosen, use the default
406 * dictionary specified in the preferences If this step does
407 * fail (no default dictionary specified), show a toast and
410 if (intent.getStringExtra(C.DICT_FILE) == null) {
411 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
412 if (dictfile != null)
413 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
415 String dictFilename = intent.getStringExtra(C.DICT_FILE);
416 if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null) {
417 final List<DictionaryInfo> dics = application.getDictionariesOnDevice(null);
418 final String search = intent.getStringExtra(C.SEARCH_TOKEN);
419 String bestFname = null;
420 String bestIndex = null;
421 int bestMatchLen = 2; // ignore shorter matches
422 AtomicBoolean dummy = new AtomicBoolean();
423 for (int i = 0; dictFilename == null && i < dics.size(); ++i) {
425 Log.d(LOG, "Checking dictionary " + dics.get(i).uncompressedFilename);
426 final File dictfile = application.getPath(dics.get(i).uncompressedFilename);
427 Dictionary dic = new Dictionary(new RandomAccessFile(dictfile, "r").getChannel());
428 for (int j = 0; j < dic.indices.size(); ++j) {
429 Index idx = dic.indices.get(j);
430 Log.d(LOG, "Checking index " + idx.shortName);
431 if (idx.findExact(search) != null) {
432 Log.d(LOG, "Found exact match");
433 dictFilename = dictfile.toString();
434 intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
437 int matchLen = getMatchLen(search, idx.findInsertionPoint(search, dummy));
438 Log.d(LOG, "Found partial match length " + matchLen);
439 if (matchLen > bestMatchLen) {
440 bestFname = dictfile.toString();
441 bestIndex = idx.shortName;
442 bestMatchLen = matchLen;
445 } catch (Exception e) {}
447 if (dictFilename == null && bestFname != null) {
448 dictFilename = bestFname;
449 intent.putExtra(C.INDEX_SHORT_NAME, bestIndex);
453 if (dictFilename == null) {
455 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
456 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
461 dictFile = new File(dictFilename);
464 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
466 public void onInit(int status) {
468 updateTTSLanguage(indexIndex);
473 if (dictRaf == null) {
474 dictFileTitleName = application.getDictionaryName(dictFile.getName());
475 dictRaf = new RandomAccessFile(dictFile, "r").getChannel();
477 this.setTitle("QuickDic: " + dictFileTitleName);
478 dictionary = new Dictionary(dictRaf);
479 } catch (Exception e) {
480 dictionaryOpenFail(e);
483 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
484 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
485 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
488 for (int i = 0; i < dictionary.indices.size(); ++i) {
489 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
494 Log.d(LOG, "Loading index " + indexIndex);
495 index = dictionary.indices.get(indexIndex);
496 getListView().setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
497 getListView().setEmptyView(findViewById(android.R.id.empty));
498 getListView().setOnItemClickListener(new OnItemClickListener() {
500 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
501 onListItemClick(getListView(), view, row, id);
505 setListAdapter(new IndexAdapter(index));
507 // Pre-load the Transliterator (will spawn its own thread)
508 TransliteratorManager.init(new TransliteratorManager.Callback() {
510 public void onTransliteratorReady() {
511 uiHandler.post(new Runnable() {
514 onSearchTextChange(searchView.getQuery().toString());
518 }, DictionaryApplication.threadBackground);
520 // Pre-load the collators.
521 new Thread(new Runnable() {
523 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
524 final long startMillis = System.currentTimeMillis();
526 for (final Index index : dictionary.indices) {
527 final String searchToken = index.sortedIndexEntries.get(0).token;
528 final IndexEntry entry = index.findExact(searchToken);
529 if (entry == null || !searchToken.equals(entry.token)) {
530 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
533 indexPrepFinished = true;
534 } catch (Exception e) {
536 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
538 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
542 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
545 typeface = Typeface.DEFAULT;
548 typeface = Typeface.SERIF;
551 typeface = Typeface.SANS_SERIF;
554 typeface = Typeface.MONOSPACE;
557 if ("FreeSerif.ttf.jpg".equals(fontName)) {
558 fontName = "FreeSerif.otf.jpg";
561 typeface = Typeface.createFromAsset(getAssets(), fontName);
562 } catch (Exception e) {
563 Log.w(LOG, "Exception trying to use typeface, using default.", e);
565 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
566 Toast.LENGTH_LONG).show();
570 if (typeface == null) {
571 Log.w(LOG, "Unable to create typeface, using default.");
572 typeface = Typeface.DEFAULT;
574 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
576 fontSizeSp = Integer.parseInt(fontSize.trim());
577 } catch (NumberFormatException e) {
582 registerForContextMenu(getListView());
585 wordList = application.getWordListFile();
586 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
588 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
589 !getPackageManager().hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN));
590 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
592 onCreateSetupActionBarAndSearchView();
594 View floatSwapButton = findViewById(R.id.floatSwapButton);
595 floatSwapButton.setOnLongClickListener(new OnLongClickListener() {
597 public boolean onLongClick(View v) {
598 onLanguageButtonLongClick(v.getContext());
603 // Set the search text from the intent, then the saved state.
604 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
605 if (savedInstanceState != null) {
606 text = savedInstanceState.getString(C.SEARCH_TOKEN);
612 searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
614 public boolean onSuggestionSelect(int position) {
619 public boolean onSuggestionClick(int position) {
620 setSearchText(searchHistory.get(position), true);
624 searchView.setSuggestionsAdapter(new CursorAdapter(this, text.isEmpty() ? searchHistoryCursor : null, 0) {
626 public View newView(Context context, Cursor c, ViewGroup p) {
627 TextView v = new TextView(context);
628 v.setTextColor(textColorFg);
629 v.setTypeface(typeface);
630 v.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
634 public void bindView(View v, Context context, Cursor c) {
635 TextView t = (TextView)v;
636 t.setText(c.getString(1));
640 // Set up search history
641 ArrayList<String> savedHistory = null;
642 if (savedInstanceState != null) savedHistory = savedInstanceState.getStringArrayList(C.SEARCH_HISTORY);
643 if (savedHistory != null && !savedHistory.isEmpty()) {
645 savedHistory = new ArrayList<>();
646 for (int i = 0; i < MAX_SEARCH_HISTORY; i++) {
647 String h = prefs.getString("history" + i, null);
648 if (h == null) break;
652 for (int i = savedHistory.size() - 1; i >= 0; i--) {
653 addToSearchHistory(savedHistory.get(i));
656 setSearchText(text, true);
657 Log.d(LOG, "Trying to restore searchText=" + text);
659 setDictionaryPrefs(this, dictFile, index.shortName);
662 searchView.requestFocus();
664 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
665 // getListView().setCacheColorHint(0);
668 private void onCreateSetupActionBarAndSearchView() {
669 ActionBar actionBar = getSupportActionBar();
670 actionBar.setDisplayShowTitleEnabled(false);
671 actionBar.setDisplayShowHomeEnabled(false);
672 actionBar.setDisplayHomeAsUpEnabled(false);
674 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
676 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
677 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
678 customSearchView.setLayoutParams(layoutParams);
680 languageButton = new ImageButton(customSearchView.getContext());
681 languageButton.setId(R.id.languageButton);
682 languageButton.setScaleType(ScaleType.FIT_CENTER);
683 languageButton.setOnClickListener(new OnClickListener() {
685 public void onClick(View v) {
686 onLanguageButtonLongClick(v.getContext());
689 languageButton.setAdjustViewBounds(true);
690 LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
691 customSearchView.addView(languageButton, lpb);
693 searchView = new SearchView(getSupportActionBar().getThemedContext());
694 searchView.setId(R.id.searchView);
696 // Get rid of search icon, it takes up too much space.
697 // There is still text saying "search" in the search field.
698 searchView.setIconifiedByDefault(true);
699 searchView.setIconified(false);
701 searchView.setQueryHint(getString(R.string.searchText));
702 searchView.setSubmitButtonEnabled(false);
703 searchView.setInputType(InputType.TYPE_CLASS_TEXT);
704 searchView.setImeOptions(
705 EditorInfo.IME_ACTION_DONE |
706 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
707 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
709 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
710 onQueryTextListener = new OnQueryTextListener() {
712 public boolean onQueryTextSubmit(String query) {
713 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
714 addToSearchHistory(searchView.getQuery().toString());
720 public boolean onQueryTextChange(String newText) {
721 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
722 onSearchTextChange(searchView.getQuery().toString());
726 searchView.setOnQueryTextListener(onQueryTextListener);
727 searchView.setFocusable(true);
728 searchTextView = (AutoCompleteTextView)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
729 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
730 FrameLayout.LayoutParams.WRAP_CONTENT, 1);
731 customSearchView.addView(searchView, lp);
733 actionBar.setCustomView(customSearchView);
734 actionBar.setDisplayShowCustomEnabled(true);
736 // Avoid wasting space on large left inset
737 Toolbar tb = (Toolbar)customSearchView.getParent();
738 tb.setContentInsetsRelative(0, 0);
740 getListView().setNextFocusLeftId(R.id.searchView);
741 findViewById(R.id.floatSwapButton).setNextFocusRightId(R.id.languageButton);
742 languageButton.setNextFocusLeftId(R.id.floatSwapButton);
746 protected void onResume() {
747 Log.d(LOG, "onResume");
749 if (PreferenceActivity.prefsMightHaveChanged) {
750 PreferenceActivity.prefsMightHaveChanged = false;
752 startActivity(getIntent());
758 * Invoked when MyWebView returns, since the user might have clicked some
759 * hypertext in the MyWebView.
762 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
763 super.onActivityResult(requestCode, resultCode, result);
764 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
765 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
766 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
770 private static void setDictionaryPrefs(final Context context, final File dictFile,
771 final String indexShortName) {
772 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
774 if (dictFile != null) {
775 prefs.putString(C.DICT_FILE, dictFile.getPath());
776 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
778 prefs.remove(C.SEARCH_TOKEN); // Don't need to save search token.
783 protected void onPause() {
789 protected void onDestroy() {
791 if (dictRaf == null) {
795 final SearchOperation searchOperation = currentSearchOperation;
796 currentSearchOperation = null;
798 // Before we close the RAF, we have to wind the current search down.
799 if (searchOperation != null) {
800 Log.d(LOG, "Interrupting search to shut down.");
801 currentSearchOperation = null;
802 searchOperation.interrupted.set(true);
804 searchExecutor.shutdownNow();
805 textToSpeech.shutdown();
809 setListAdapter(null);
812 Log.d(LOG, "Closing RAF.");
814 } catch (IOException e) {
815 Log.e(LOG, "Failed to close dictionary", e);
820 // --------------------------------------------------------------------------
822 // --------------------------------------------------------------------------
824 private void showKeyboard() {
825 // For some reason, this doesn't always work the first time.
826 // One way to replicate the problem:
827 // Press the "task switch" button repeatedly to pause and resume
828 for (int delay = 1; delay <= 101; delay += 100) {
829 searchView.postDelayed(new Runnable() {
832 Log.d(LOG, "Trying to show soft keyboard.");
833 final boolean searchTextHadFocus = searchView.hasFocus();
834 searchView.requestFocusFromTouch();
835 searchTextView.requestFocus();
836 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
837 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
838 manager.showSoftInput(searchTextView, InputMethodManager.SHOW_IMPLICIT);
839 if (!searchTextHadFocus) {
845 searchView.post(new Runnable() {
848 searchTextView.setThreshold(0);
849 searchTextView.showDropDown();
854 private void hideKeyboard() {
855 Log.d(LOG, "Hide soft keyboard.");
856 searchView.clearFocus();
857 InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
858 manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
861 private void updateLangButton() {
862 final int flagId = IsoUtils.INSTANCE.getFlagIdForIsoCode(index.shortName);
864 languageButton.setImageResource(flagId);
866 if (indexIndex % 2 == 0) {
867 languageButton.setImageResource(android.R.drawable.ic_media_next);
869 languageButton.setImageResource(android.R.drawable.ic_media_previous);
872 updateTTSLanguage(indexIndex);
875 private void updateTTSLanguage(int i) {
876 if (!ttsReady || index == null || textToSpeech == null) {
877 Log.d(LOG, "Can't updateTTSLanguage.");
880 final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
881 Log.d(LOG, "Setting TTS locale to: " + locale);
883 final int ttsResult = textToSpeech.setLanguage(locale);
884 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
885 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
886 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
888 } catch (Exception e) {
890 Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
894 public void onSearchButtonClick(View dummy) {
895 if (!searchView.hasFocus()) {
896 searchView.requestFocus();
898 if (searchView.getQuery().toString().length() > 0) {
899 searchView.setQuery("", false);
902 searchView.setIconified(false);
905 public void onLanguageButtonClick(View dummy) {
906 if (dictionary.indices.size() == 1) {
907 // No need to work to switch indices.
910 if (currentSearchOperation != null) {
911 currentSearchOperation.interrupted.set(true);
912 currentSearchOperation = null;
914 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
915 searchView.getQuery().toString(), false);
918 private void onLanguageButtonLongClick(final Context context) {
919 final Dialog dialog = new Dialog(context);
920 dialog.setContentView(R.layout.select_dictionary_dialog);
921 dialog.setTitle(R.string.selectDictionary);
923 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
925 ListView listView = dialog.findViewById(android.R.id.list);
926 final Button button = new Button(listView.getContext());
927 final String name = getString(R.string.dictionaryManager);
928 button.setText(name);
929 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
930 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
932 protected void onGo() {
934 DictionaryActivity.this.finish();
937 button.setOnClickListener(intentLauncher);
938 listView.addHeaderView(button);
940 listView.setItemsCanFocus(true);
941 listView.setAdapter(new BaseAdapter() {
943 public View getView(int position, View convertView, ViewGroup parent) {
944 final DictionaryInfo dictionaryInfo = getItem(position);
946 final LinearLayout result = new LinearLayout(parent.getContext());
948 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
949 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
950 final View button = IsoUtils.INSTANCE.createButton(parent.getContext(),
951 indexInfo, application.languageButtonPixels);
952 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
953 getLaunchIntent(getApplicationContext(),
954 application.getPath(dictionaryInfo.uncompressedFilename),
955 indexInfo.shortName, searchView.getQuery().toString())) {
957 protected void onGo() {
959 DictionaryActivity.this.finish();
962 button.setOnClickListener(intentLauncher);
963 if (i == indexIndex && dictFile != null &&
964 dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
965 button.setPressed(true);
967 result.addView(button);
970 final TextView nameView = new TextView(parent.getContext());
971 final String name = application
972 .getDictionaryName(dictionaryInfo.uncompressedFilename);
973 nameView.setText(name);
974 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
975 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
976 layoutParams.width = 0;
977 layoutParams.weight = 1.0f;
978 nameView.setLayoutParams(layoutParams);
979 nameView.setGravity(Gravity.CENTER_VERTICAL);
980 result.addView(nameView);
985 public long getItemId(int position) {
990 public DictionaryInfo getItem(int position) {
991 return installedDicts.get(position);
995 public int getCount() {
996 return installedDicts.size();
1002 private void onUpDownButton(final boolean up) {
1006 final int firstVisibleRow = getListView().getFirstVisiblePosition();
1007 final RowBase row = index.rows.get(firstVisibleRow);
1008 final TokenRow tokenRow = row.getTokenRow(true);
1009 final int destIndexEntry;
1011 if (row != tokenRow) {
1012 destIndexEntry = tokenRow.referenceIndex;
1014 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
1018 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
1020 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
1021 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
1022 setSearchText(dest.token, false);
1023 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
1024 defocusSearchText();
1027 private void onRandomWordButton() {
1028 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
1029 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
1030 setSearchText(dest.token, false);
1031 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
1032 defocusSearchText();
1035 // --------------------------------------------------------------------------
1037 // --------------------------------------------------------------------------
1040 public boolean onCreateOptionsMenu(final Menu menu) {
1042 if (PreferenceManager.getDefaultSharedPreferences(this)
1043 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
1045 nextWordMenuItem = menu.add(getString(R.string.nextWord))
1046 .setIcon(R.drawable.arrow_down_float);
1047 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
1048 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1050 public boolean onMenuItemClick(MenuItem item) {
1051 onUpDownButton(false);
1057 previousWordMenuItem = menu.add(getString(R.string.previousWord))
1058 .setIcon(R.drawable.arrow_up_float);
1059 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
1060 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1062 public boolean onMenuItemClick(MenuItem item) {
1063 onUpDownButton(true);
1069 final MenuItem randomWordMenuItem = menu.add(getString(R.string.randomWord));
1070 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1072 public boolean onMenuItemClick(MenuItem item) {
1073 onRandomWordButton();
1079 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
1080 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
1081 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1082 public boolean onMenuItemClick(final MenuItem menuItem) {
1083 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
1091 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
1092 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
1093 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1094 public boolean onMenuItemClick(final MenuItem menuItem) {
1095 final Context context = getListView().getContext();
1096 final Dialog dialog = new Dialog(context);
1097 dialog.setContentView(R.layout.about_dictionary_dialog);
1098 final TextView textView = dialog.findViewById(R.id.text);
1100 dialog.setTitle(dictFileTitleName);
1102 final StringBuilder builder = new StringBuilder();
1103 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
1104 if (dictionaryInfo != null) {
1106 dictionaryInfo.uncompressedBytes = dictRaf.size();
1107 } catch (IOException e) {
1109 builder.append(dictionaryInfo.dictInfo).append("\n\n");
1110 if (dictFile != null) {
1111 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
1115 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
1118 getString(R.string.dictionaryCreationTime,
1119 dictionaryInfo.creationMillis)).append("\n");
1120 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
1121 builder.append("\n");
1122 builder.append(getString(R.string.indexName, indexInfo.shortName))
1125 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
1128 builder.append("\n");
1129 builder.append(getString(R.string.sources)).append("\n");
1130 for (final EntrySource source : dictionary.sources) {
1132 getString(R.string.sourceInfo, source.getName(),
1133 source.getNumEntries())).append("\n");
1136 textView.setText(builder.toString());
1139 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
1140 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
1141 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
1142 dialog.getWindow().setAttributes(layoutParams);
1148 DictionaryApplication.onCreateGlobalOptionsMenu(this, menu);
1153 // --------------------------------------------------------------------------
1154 // Context Menu + clicks
1155 // --------------------------------------------------------------------------
1158 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1159 final AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
1160 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
1162 if (clickOpensContextMenu && (row instanceof HtmlEntry.Row ||
1163 (row instanceof TokenRow && ((TokenRow)row).getIndexEntry().htmlEntries.size() > 0))) {
1164 final List<HtmlEntry> html = row instanceof TokenRow ? ((TokenRow)row).getIndexEntry().htmlEntries : Collections.singletonList(((HtmlEntry.Row)row).getEntry());
1165 final String highlight = row instanceof HtmlEntry.Row ? row.getTokenRow(true).getToken() : null;
1166 final MenuItem open = menu.add("Open");
1167 open.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1168 public boolean onMenuItemClick(MenuItem item) {
1169 showHtml(html, highlight);
1175 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
1176 wordList.getName()));
1178 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1179 public boolean onMenuItemClick(android.view.MenuItem item) {
1180 onAppendToWordList(row);
1185 final android.view.MenuItem share = menu.add("Share");
1186 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1187 public boolean onMenuItemClick(android.view.MenuItem item) {
1188 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
1189 shareIntent.setType("text/plain");
1190 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
1192 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
1193 row.getRawText(saveOnlyFirstSubentry));
1194 startActivity(shareIntent);
1199 final android.view.MenuItem copy = menu.add(android.R.string.copy);
1200 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1201 public boolean onMenuItemClick(android.view.MenuItem item) {
1207 if (selectedSpannableText != null) {
1208 final String selectedText = selectedSpannableText;
1209 final android.view.MenuItem searchForSelection = menu.add(getString(
1210 R.string.searchForSelection,
1211 selectedSpannableText));
1213 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1214 public boolean onMenuItemClick(android.view.MenuItem item) {
1215 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
1219 // Rats, this won't be shown:
1220 //searchForSelection.setIcon(R.drawable.abs__ic_search);
1223 if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
1224 final android.view.MenuItem speak = menu.add(R.string.speak);
1225 final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
1226 updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
1227 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1229 public boolean onMenuItemClick(android.view.MenuItem item) {
1230 textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
1231 new HashMap<String, String>());
1236 if (row instanceof PairEntry.Row && ttsReady) {
1237 final List<Pair> pairs = ((PairEntry.Row)row).getEntry().pairs;
1238 final MenuItem speakLeft = menu.add(R.string.speak_left);
1239 speakLeft.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1241 public boolean onMenuItemClick(android.view.MenuItem item) {
1242 int idx = index.swapPairEntries ? 1 : 0;
1243 updateTTSLanguage(idx);
1245 for (Pair p : pairs) text += p.get(idx);
1246 text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1247 textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
1248 new HashMap<String, String>());
1252 final MenuItem speakRight = menu.add(R.string.speak_right);
1253 speakRight.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1255 public boolean onMenuItemClick(android.view.MenuItem item) {
1256 int idx = index.swapPairEntries ? 0 : 1;
1257 updateTTSLanguage(idx);
1259 for (Pair p : pairs) text += p.get(idx);
1260 text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1261 textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
1262 new HashMap<String, String>());
1269 private void jumpToTextFromHyperLink(
1270 final String selectedText, final int defaultIndexToUse) {
1271 int indexToUse = -1;
1273 for (int i = 0; i < dictionary.indices.size(); ++i) {
1274 final Index index = dictionary.indices.get(i);
1275 if (indexPrepFinished) {
1276 System.out.println("Doing index lookup: on " + selectedText);
1277 final IndexEntry indexEntry = index.findExact(selectedText);
1278 if (indexEntry != null) {
1279 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1280 .getTokenRow(false);
1281 if (tokenRow != null && tokenRow.hasMainEntry) {
1287 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1290 if (numFound != 1) {
1291 indexToUse = defaultIndexToUse;
1293 // Without this extra delay, the call to jumpToRow that this
1294 // invokes doesn't always actually have any effect.
1295 final int actualIndexToUse = indexToUse;
1296 getListView().postDelayed(new Runnable() {
1299 setIndexAndSearchText(actualIndexToUse, selectedText, true);
1305 * Called when user clicks outside of search text, so that they can start
1306 * typing again immediately.
1308 private void defocusSearchText() {
1309 // Log.d(LOG, "defocusSearchText");
1310 // Request focus so that if we start typing again, it clears the text
1312 getListView().requestFocus();
1314 // Visual indication that a new keystroke will clear the search text.
1315 // Doesn't seem to work unless searchText has focus.
1316 // searchView.selectAll();
1319 private void onListItemClick(ListView l, View v, int rowIdx, long id) {
1320 defocusSearchText();
1321 if (clickOpensContextMenu && dictRaf != null) {
1324 final RowBase row = (RowBase)getListAdapter().getItem(rowIdx);
1325 if (!(row instanceof PairEntry.Row)) {
1331 @SuppressLint("SimpleDateFormat")
1332 private void onAppendToWordList(final RowBase row) {
1333 defocusSearchText();
1335 final StringBuilder rawText = new StringBuilder();
1336 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1337 rawText.append(index.longName).append("\t");
1338 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1339 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1340 Log.d(LOG, "Writing : " + rawText);
1343 wordList.getParentFile().mkdirs();
1344 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1345 out.println(rawText);
1347 } catch (Exception e) {
1348 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1350 Toast.makeText(this,
1351 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1352 Toast.LENGTH_LONG).show();
1356 @SuppressWarnings("deprecation")
1357 private void onCopy(final RowBase row) {
1358 defocusSearchText();
1360 Log.d(LOG, "Copy, row=" + row);
1361 final StringBuilder result = new StringBuilder();
1362 result.append(row.getRawText(false));
1363 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1364 clipboardManager.setText(result.toString());
1365 Log.d(LOG, "Copied: " + result);
1369 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1370 if (event.getUnicodeChar() != 0) {
1371 if (!searchView.hasFocus()) {
1372 setSearchText("" + (char) event.getUnicodeChar(), true);
1373 searchView.requestFocus();
1377 if (keyCode == KeyEvent.KEYCODE_BACK) {
1378 // Log.d(LOG, "Clearing dictionary prefs.");
1379 // Pretend that we just autolaunched so that we won't do it again.
1380 // DictionaryManagerActivity.lastAutoLaunchMillis =
1381 // System.currentTimeMillis();
1383 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1384 Log.d(LOG, "Trying to hide soft keyboard.");
1385 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1386 View focus = getCurrentFocus();
1387 if (inputManager != null && focus != null) {
1388 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1389 InputMethodManager.HIDE_NOT_ALWAYS);
1393 return super.onKeyDown(keyCode, event);
1396 private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
1397 Log.d(LOG, "Changing index to: " + newIndex);
1398 if (newIndex == -1) {
1399 Log.e(LOG, "Invalid index.");
1402 if (newIndex != indexIndex) {
1403 indexIndex = newIndex;
1404 index = dictionary.indices.get(indexIndex);
1405 indexAdapter = new IndexAdapter(index);
1406 setListAdapter(indexAdapter);
1407 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1408 setDictionaryPrefs(this, dictFile, index.shortName);
1411 setSearchText(newSearchText, true, hideKeyboard);
1414 private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
1415 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1416 // Disable the listener, because sometimes it doesn't work.
1417 searchView.setOnQueryTextListener(null);
1418 searchView.setQuery(text, false);
1419 searchView.setOnQueryTextListener(onQueryTextListener);
1421 if (triggerSearch) {
1422 onSearchTextChange(text);
1425 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1429 addToSearchHistory(text);
1432 private void setSearchText(final String text, final boolean triggerSearch) {
1433 setSearchText(text, triggerSearch, true);
1436 // --------------------------------------------------------------------------
1438 // --------------------------------------------------------------------------
1440 private void searchFinished(final SearchOperation searchOperation) {
1441 if (searchOperation.interrupted.get()) {
1442 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1445 if (searchOperation != this.currentSearchOperation) {
1446 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1450 final Index.IndexEntry searchResult = searchOperation.searchResult;
1451 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1453 currentSearchOperation = null;
1454 // Note: it's important to post to the ListView, otherwise
1455 // the jumpToRow will randomly not work.
1456 getListView().post(new Runnable() {
1459 if (currentSearchOperation == null) {
1460 if (searchResult != null) {
1464 jumpToRow(searchResult.startRow);
1465 } else if (searchOperation.multiWordSearchResult != null) {
1466 // Multi-row search....
1467 setFiltered(searchOperation);
1469 throw new IllegalStateException("This should never happen.");
1472 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1478 private void jumpToRow(final int row) {
1479 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1480 // getListView().requestFocusFromTouch();
1481 getListView().setSelectionFromTop(row, 0);
1482 getListView().setSelected(true);
1485 private static final Pattern WHITESPACE = Pattern.compile("\\s+");
1487 final class SearchOperation implements Runnable {
1489 final AtomicBoolean interrupted = new AtomicBoolean(false);
1491 final String searchText;
1493 List<String> searchTokens; // filled in for multiWord.
1497 long searchStartMillis;
1499 Index.IndexEntry searchResult;
1501 List<RowBase> multiWordSearchResult;
1503 boolean done = false;
1505 SearchOperation(final String searchText, final Index index) {
1506 this.searchText = StringUtil.normalizeWhitespace(searchText);
1510 public String toString() {
1511 return String.format("SearchOperation(%s,%s)", searchText, interrupted);
1517 searchStartMillis = System.currentTimeMillis();
1518 final String[] searchTokenArray = WHITESPACE.split(searchText);
1519 if (searchTokenArray.length == 1) {
1520 searchResult = index.findInsertionPoint(searchText, interrupted);
1522 searchTokens = Arrays.asList(searchTokenArray);
1523 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1527 "searchText=" + searchText + ", searchDuration="
1528 + (System.currentTimeMillis() - searchStartMillis)
1529 + ", interrupted=" + interrupted.get());
1530 if (!interrupted.get()) {
1531 uiHandler.post(new Runnable() {
1534 searchFinished(SearchOperation.this);
1538 Log.d(LOG, "interrupted, skipping searchFinished.");
1540 } catch (Exception e) {
1541 Log.e(LOG, "Failure during search (can happen during Activity close): " + e.getMessage());
1543 synchronized (this) {
1551 // --------------------------------------------------------------------------
1553 // --------------------------------------------------------------------------
1555 private void showHtml(final List<HtmlEntry> htmlEntries, final String htmlTextToHighlight) {
1556 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1558 if (typeface == Typeface.SERIF) { style = "font-family: serif;"; }
1559 else if (typeface == Typeface.SANS_SERIF) { style = "font-family: sans-serif;"; }
1560 else if (typeface == Typeface.MONOSPACE) { style = "font-family: monospace;"; }
1561 if (application.getSelectedTheme() == DictionaryApplication.Theme.DEFAULT)
1562 style += "background-color: black; color: white;";
1563 // Log.d(LOG, "html=" + html);
1564 startActivityForResult(
1565 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1566 "<html><head><meta name=\"viewport\" content=\"width=device-width\"></head><body style=\"%s\">%s</body></html>", style, html),
1567 htmlTextToHighlight, false),
1571 final class IndexAdapter extends BaseAdapter {
1573 private static final float PADDING_DEFAULT_DP = 8;
1575 private static final float PADDING_LARGE_DP = 16;
1579 final List<RowBase> rows;
1581 final Set<String> toHighlight;
1583 private int mPaddingDefault;
1585 private int mPaddingLarge;
1587 IndexAdapter(final Index index) {
1590 this.toHighlight = null;
1594 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1597 this.toHighlight = new LinkedHashSet<>(toHighlight);
1601 private void getMetrics() {
1603 // Get the screen's density scale
1604 // The previous method getResources().getDisplayMetrics()
1605 // used to occasionally trigger a null pointer exception,
1606 // so try this instead.
1607 // As it still crashes, add a fallback
1609 DisplayMetrics dm = new DisplayMetrics();
1610 getWindowManager().getDefaultDisplay().getMetrics(dm);
1612 } catch (NullPointerException ignored)
1614 // Convert the dps to pixels, based on density scale
1615 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1616 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1620 public int getCount() {
1625 public RowBase getItem(int position) {
1626 return rows.get(position);
1630 public long getItemId(int position) {
1631 return getItem(position).index();
1635 public int getViewTypeCount() {
1640 public int getItemViewType(int position) {
1641 final RowBase row = getItem(position);
1642 if (row instanceof PairEntry.Row) {
1643 final PairEntry entry = ((PairEntry.Row)row).getEntry();
1644 final int rowCount = entry.pairs.size();
1645 return rowCount > 1 ? 1 : 0;
1646 } else if (row instanceof TokenRow) {
1647 final IndexEntry indexEntry = ((TokenRow)row).getIndexEntry();
1648 return indexEntry.htmlEntries.isEmpty() ? 2 : 3;
1649 } else if (row instanceof HtmlEntry.Row) {
1652 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1657 public View getView(int position, View convertView, ViewGroup parent) {
1658 final RowBase row = getItem(position);
1659 if (row instanceof PairEntry.Row) {
1660 return getView(position, (PairEntry.Row) row, parent, (TableLayout)convertView);
1661 } else if (row instanceof TokenRow) {
1662 return getView((TokenRow) row, parent, (TextView)convertView);
1663 } else if (row instanceof HtmlEntry.Row) {
1664 return getView((HtmlEntry.Row) row, parent, (TextView)convertView);
1666 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1670 private void addBoldSpans(String token, String col1Text, Spannable col1Spannable) {
1672 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1673 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1674 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1675 startPos += token.length();
1679 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1680 TableLayout result) {
1681 final Context context = parent.getContext();
1682 final PairEntry entry = row.getEntry();
1683 final int rowCount = entry.pairs.size();
1684 if (result == null) {
1685 result = new TableLayout(context);
1686 result.setStretchAllColumns(true);
1687 // Because we have a Button inside a ListView row:
1688 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1689 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1690 result.setClickable(true);
1691 result.setFocusable(false);
1692 result.setLongClickable(true);
1693 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1695 result.setBackgroundResource(theme.normalRowBg);
1696 } else if (result.getChildCount() > rowCount) {
1697 result.removeViews(rowCount, result.getChildCount() - rowCount);
1700 for (int r = result.getChildCount(); r < rowCount; ++r) {
1701 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
1702 layoutParams.leftMargin = mPaddingLarge;
1704 final TableRow tableRow = new TableRow(result.getContext());
1706 final TextView col1 = new TextView(tableRow.getContext());
1707 final TextView col2 = new TextView(tableRow.getContext());
1708 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1709 col1.setTextIsSelectable(true);
1710 col2.setTextIsSelectable(true);
1712 col1.setTextColor(textColorFg);
1713 col2.setTextColor(textColorFg);
1718 col1.setTypeface(typeface);
1719 col2.setTypeface(typeface);
1720 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1721 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1722 // col2.setBackgroundResource(theme.otherLangBg);
1724 if (index.swapPairEntries) {
1725 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1726 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1728 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1729 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1732 // Set the columns in the table.
1734 tableRow.addView(col1, layoutParams);
1735 tableRow.addView(col2, layoutParams);
1737 for (int i = 0; i < 2; i++) {
1738 final TextView bullet = new TextView(tableRow.getContext());
1739 bullet.setText(" • ");
1740 LinearLayout wrapped = new LinearLayout(context);
1741 wrapped.setOrientation(LinearLayout.HORIZONTAL);
1742 LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0);
1743 wrapped.addView(bullet, p1);
1744 LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
1745 wrapped.addView(i == 0 ? col1 : col2, p2);
1746 tableRow.addView(wrapped, layoutParams);
1750 result.addView(tableRow);
1753 for (int r = 0; r < rowCount; ++r) {
1754 final TableRow tableRow = (TableRow)result.getChildAt(r);
1755 View left = tableRow.getChildAt(0);
1756 View right = tableRow.getChildAt(1);
1758 left = ((ViewGroup)left).getChildAt(1);
1759 right = ((ViewGroup)right).getChildAt(1);
1761 final TextView col1 = (TextView)left;
1762 final TextView col2 = (TextView)right;
1764 // Set what's in the columns.
1765 final Pair pair = entry.pairs.get(r);
1766 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1767 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1768 final Spannable col1Spannable = new SpannableString(col1Text);
1769 final Spannable col2Spannable = new SpannableString(col2Text);
1771 // Bold the token instances in col1.
1772 if (toHighlight != null) {
1773 for (final String token : toHighlight) {
1774 addBoldSpans(token, col1Text, col1Spannable);
1777 addBoldSpans(row.getTokenRow(true).getToken(), col1Text, col1Spannable);
1779 createTokenLinkSpans(col1, col1Spannable, col1Text);
1780 createTokenLinkSpans(col2, col2Spannable, col2Text);
1782 col1.setText(col1Spannable);
1783 col2.setText(col2Spannable);
1786 result.setOnClickListener(new TextView.OnClickListener() {
1788 public void onClick(View v) {
1789 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1796 private TextView getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1797 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1798 final String htmlTextToHighlight, ViewGroup parent, TextView textView) {
1799 final Context context = parent.getContext();
1800 if (textView == null) {
1801 textView = new TextView(context);
1802 // set up things invariant across one ItemViewType
1803 // ItemViewTypes handled here are:
1804 // 2: isTokenRow == true, htmlEntries.isEmpty() == true
1805 // 3: isTokenRow == true, htmlEntries.isEmpty() == false
1806 // 4: isTokenRow == false, htmlEntries.isEmpty() == false
1807 textView.setPadding(isTokenRow ? mPaddingDefault : mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1808 textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1809 textView.setLongClickable(true);
1811 textView.setTypeface(typeface);
1813 textView.setTextAppearance(context, theme.tokenRowFg);
1814 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1816 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1818 textView.setTextColor(textColorFg);
1819 if (!htmlEntries.isEmpty()) {
1820 textView.setClickable(true);
1821 textView.setMovementMethod(LinkMovementMethod.getInstance());
1825 textView.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1826 : theme.tokenRowOtherBg);
1828 // Make it so we can long-click on these token rows, too:
1829 final Spannable textSpannable = new SpannableString(text);
1830 createTokenLinkSpans(textView, textSpannable, text);
1832 if (!htmlEntries.isEmpty()) {
1833 final ClickableSpan clickableSpan = new ClickableSpan() {
1835 public void onClick(View widget) {
1838 textSpannable.setSpan(clickableSpan, 0, text.length(),
1839 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1840 textView.setOnClickListener(new OnClickListener() {
1842 public void onClick(View v) {
1843 showHtml(htmlEntries, htmlTextToHighlight);
1847 textView.setText(textSpannable);
1851 private TextView getView(TokenRow row, ViewGroup parent, final TextView result) {
1852 final IndexEntry indexEntry = row.getIndexEntry();
1853 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1854 indexEntry.htmlEntries, null, parent, result);
1857 private TextView getView(HtmlEntry.Row row, ViewGroup parent, final TextView result) {
1858 final HtmlEntry htmlEntry = row.getEntry();
1859 final TokenRow tokenRow = row.getTokenRow(true);
1860 return getPossibleLinkToHtmlEntryView(false,
1861 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1862 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1868 private static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1870 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1871 final String text) {
1872 // Saw from the source code that LinkMovementMethod sets the selection!
1873 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1874 textView.setMovementMethod(LinkMovementMethod.getInstance());
1875 final Matcher matcher = CHAR_DASH.matcher(text);
1876 while (matcher.find()) {
1877 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(),
1879 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1883 private String selectedSpannableText = null;
1885 private int selectedSpannableIndex = -1;
1888 public boolean onTouchEvent(MotionEvent event) {
1889 selectedSpannableText = null;
1890 selectedSpannableIndex = -1;
1891 return super.onTouchEvent(event);
1894 private class TextViewLongClickListener implements OnLongClickListener {
1897 private TextViewLongClickListener(final int index) {
1902 public boolean onLongClick(final View v) {
1903 final TextView textView = (TextView) v;
1904 final int start = textView.getSelectionStart();
1905 final int end = textView.getSelectionEnd();
1906 if (start >= 0 && end >= 0) {
1907 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1908 selectedSpannableIndex = index;
1914 private final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1917 private final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1920 // --------------------------------------------------------------------------
1922 // --------------------------------------------------------------------------
1924 private void onSearchTextChange(final String text) {
1925 if ("thadolina".equals(text)) {
1926 final Dialog dialog = new Dialog(getListView().getContext());
1927 dialog.setContentView(R.layout.thadolina_dialog);
1928 dialog.setTitle("Ti amo, amore mio!");
1929 final ImageView imageView = dialog.findViewById(R.id.thadolina_image);
1930 imageView.setOnClickListener(new OnClickListener() {
1932 public void onClick(View v) {
1933 final Intent intent = new Intent(Intent.ACTION_VIEW);
1934 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1935 startActivity(intent);
1940 if (dictRaf == null) {
1941 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1945 // if (!searchView.hasFocus()) {
1946 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1949 Log.d(LOG, "onSearchTextChange: " + text);
1950 if (currentSearchOperation != null) {
1951 Log.d(LOG, "Interrupting currentSearchOperation.");
1952 currentSearchOperation.interrupted.set(true);
1954 currentSearchOperation = new SearchOperation(text, index);
1955 searchExecutor.execute(currentSearchOperation);
1956 ((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
1957 searchView.getSuggestionsAdapter().swapCursor(text.isEmpty() ? searchHistoryCursor : null);
1958 searchView.getSuggestionsAdapter().notifyDataSetChanged();
1961 // --------------------------------------------------------------------------
1962 // Filtered results.
1963 // --------------------------------------------------------------------------
1965 private boolean isFiltered() {
1966 return rowsToShow != null;
1969 private void setFiltered(final SearchOperation searchOperation) {
1970 if (nextWordMenuItem != null) {
1971 nextWordMenuItem.setEnabled(false);
1972 previousWordMenuItem.setEnabled(false);
1974 rowsToShow = searchOperation.multiWordSearchResult;
1975 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1978 private void clearFiltered() {
1979 if (nextWordMenuItem != null) {
1980 nextWordMenuItem.setEnabled(true);
1981 previousWordMenuItem.setEnabled(true);
1983 setListAdapter(new IndexAdapter(index));