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.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() {
269 addToSearchHistory(searchView.getQuery().toString());
272 private void addToSearchHistory(String text) {
273 if (text == null || text.isEmpty()) return;
274 int exists = searchHistory.indexOf(text);
275 if (exists >= 0) searchHistory.remove(exists);
276 else if (searchHistory.size() >= MAX_SEARCH_HISTORY) searchHistory.remove(searchHistory.size() - 1);
277 searchHistory.add(0, text);
278 searchHistoryCursor = new MatrixCursor(new String[] {"_id", "search"});
279 for (int i = 0; i < searchHistory.size(); i++) {
280 final Object[] row = {i, searchHistory.get(i)};
281 searchHistoryCursor.addRow(row);
283 if (searchView.getSuggestionsAdapter().getCursor() != null) {
284 searchView.getSuggestionsAdapter().swapCursor(searchHistoryCursor);
285 searchView.getSuggestionsAdapter().notifyDataSetChanged();
290 public void onCreate(Bundle savedInstanceState) {
291 DictionaryApplication.INSTANCE.init(getApplicationContext());
292 application = DictionaryApplication.INSTANCE;
293 // This needs to be before super.onCreate, otherwise ActionbarSherlock
294 // doesn't makes the background of the actionbar white when you're
295 // in the dark theme.
296 setTheme(application.getSelectedTheme().themeId);
298 Log.d(LOG, "onCreate:" + this);
299 super.onCreate(savedInstanceState);
301 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
303 // Don't auto-launch if this fails.
304 prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
306 setContentView(R.layout.dictionary_activity);
308 theme = application.getSelectedTheme();
309 textColorFg = getResources().getColor(theme.tokenRowFgColor);
311 if (dictRaf != null) {
314 } catch (IOException e) {
315 Log.e(LOG, "Failed to close dictionary", e);
320 final Intent intent = getIntent();
321 String intentAction = intent.getAction();
323 @author Dominik Köppl Querying the Intent
324 * com.hughes.action.ACTION_SEARCH_DICT is the advanced query
325 * Arguments: SearchManager.QUERY -> the phrase to search from
326 * -> language in which the phrase is written to -> to which
327 * language shall be translated
329 if ("com.hughes.action.ACTION_SEARCH_DICT".equals(intentAction)) {
330 String query = intent.getStringExtra(SearchManager.QUERY);
331 String from = intent.getStringExtra("from");
333 from = from.toLowerCase(Locale.US);
334 String to = intent.getStringExtra("to");
336 to = to.toLowerCase(Locale.US);
338 getIntent().putExtra(C.SEARCH_TOKEN, query);
340 if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null)) {
341 Log.d(LOG, "DictSearch: from: " + from + " to " + to);
342 List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
343 for (DictionaryInfo info : dicts) {
344 boolean hasFrom = from == null;
345 boolean hasTo = to == null;
346 for (IndexInfo index : info.indexInfos) {
347 if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
349 if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
352 if (hasFrom && hasTo) {
355 for (; which_index < info.indexInfos.size(); ++which_index) {
356 if (info.indexInfos.get(which_index).shortName.toLowerCase(
357 Locale.US).equals(from))
360 intent.putExtra(C.INDEX_SHORT_NAME,
361 info.indexInfos.get(which_index).shortName);
364 intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
373 @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
374 * simple query Arguments follow from android standard (see
377 if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH)) {
378 String query = intent.getStringExtra(SearchManager.QUERY);
380 getIntent().putExtra(C.SEARCH_TOKEN, query);
382 if (intentAction != null && intentAction.equals(Intent.ACTION_SEND)) {
383 String query = intent.getStringExtra(Intent.EXTRA_TEXT);
385 getIntent().putExtra(C.SEARCH_TOKEN, query);
388 * This processes text on M+ devices where QuickDic shows up in the context menu.
390 if (intentAction != null && intentAction.equals(Intent.ACTION_PROCESS_TEXT)) {
391 String query = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
393 getIntent().putExtra(C.SEARCH_TOKEN, query);
396 // Support opening dictionary file directly
397 if (intentAction != null && intentAction.equals(Intent.ACTION_VIEW)) {
398 Uri uri = intent.getData();
399 intent.putExtra(C.DICT_FILE, uri.toString());
400 dictFileTitleName = uri.getLastPathSegment();
402 dictRaf = getContentResolver().openAssetFileDescriptor(uri, "r").createInputStream().getChannel();
403 } catch (Exception e) {
404 dictionaryOpenFail(e);
409 @author Dominik Köppl If no dictionary is chosen, use the default
410 * dictionary specified in the preferences If this step does
411 * fail (no default dictionary specified), show a toast and
414 if (intent.getStringExtra(C.DICT_FILE) == null) {
415 String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
416 if (dictfile != null)
417 intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
419 String dictFilename = intent.getStringExtra(C.DICT_FILE);
420 if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null) {
421 final List<DictionaryInfo> dics = application.getDictionariesOnDevice(null);
422 final String search = intent.getStringExtra(C.SEARCH_TOKEN);
423 String bestFname = null;
424 String bestIndex = null;
425 int bestMatchLen = 2; // ignore shorter matches
426 AtomicBoolean dummy = new AtomicBoolean();
427 for (int i = 0; dictFilename == null && i < dics.size(); ++i) {
429 Log.d(LOG, "Checking dictionary " + dics.get(i).uncompressedFilename);
430 final File dictfile = application.getPath(dics.get(i).uncompressedFilename);
431 Dictionary dic = new Dictionary(new RandomAccessFile(dictfile, "r").getChannel());
432 for (int j = 0; j < dic.indices.size(); ++j) {
433 Index idx = dic.indices.get(j);
434 Log.d(LOG, "Checking index " + idx.shortName);
435 if (idx.findExact(search) != null) {
436 Log.d(LOG, "Found exact match");
437 dictFilename = dictfile.toString();
438 intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
441 int matchLen = getMatchLen(search, idx.findInsertionPoint(search, dummy));
442 Log.d(LOG, "Found partial match length " + matchLen);
443 if (matchLen > bestMatchLen) {
444 bestFname = dictfile.toString();
445 bestIndex = idx.shortName;
446 bestMatchLen = matchLen;
449 } catch (Exception e) {}
451 if (dictFilename == null && bestFname != null) {
452 dictFilename = bestFname;
453 intent.putExtra(C.INDEX_SHORT_NAME, bestIndex);
457 if (dictFilename == null) {
459 Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
460 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
465 dictFile = new File(dictFilename);
468 textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
470 public void onInit(int status) {
472 updateTTSLanguage(indexIndex);
477 if (dictRaf == null) {
478 dictFileTitleName = application.getDictionaryName(dictFile.getName());
479 dictRaf = new RandomAccessFile(dictFile, "r").getChannel();
481 this.setTitle("QuickDic: " + dictFileTitleName);
482 dictionary = new Dictionary(dictRaf);
483 } catch (Exception e) {
484 dictionaryOpenFail(e);
487 String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
488 if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
489 targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
492 for (int i = 0; i < dictionary.indices.size(); ++i) {
493 if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
498 Log.d(LOG, "Loading index " + indexIndex);
499 index = dictionary.indices.get(indexIndex);
500 getListView().setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
501 getListView().setEmptyView(findViewById(android.R.id.empty));
502 getListView().setOnItemClickListener(new OnItemClickListener() {
504 public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
505 onListItemClick(getListView(), view, row, id);
509 setListAdapter(new IndexAdapter(index));
511 // Pre-load the Transliterator (will spawn its own thread)
512 TransliteratorManager.init(new TransliteratorManager.Callback() {
514 public void onTransliteratorReady() {
515 uiHandler.post(new Runnable() {
518 onSearchTextChange(searchView.getQuery().toString());
522 }, DictionaryApplication.threadBackground);
524 // Pre-load the collators.
525 new Thread(new Runnable() {
527 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
528 final long startMillis = System.currentTimeMillis();
530 for (final Index index : dictionary.indices) {
531 final String searchToken = index.sortedIndexEntries.get(0).token;
532 final IndexEntry entry = index.findExact(searchToken);
533 if (entry == null || !searchToken.equals(entry.token)) {
534 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
537 indexPrepFinished = true;
538 } catch (Exception e) {
540 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
542 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
546 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
549 typeface = Typeface.DEFAULT;
552 typeface = Typeface.SERIF;
555 typeface = Typeface.SANS_SERIF;
558 typeface = Typeface.MONOSPACE;
561 if ("FreeSerif.ttf.jpg".equals(fontName)) {
562 fontName = "FreeSerif.otf.jpg";
565 typeface = Typeface.createFromAsset(getAssets(), fontName);
566 } catch (Exception e) {
567 Log.w(LOG, "Exception trying to use typeface, using default.", e);
569 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
570 Toast.LENGTH_LONG).show();
574 if (typeface == null) {
575 Log.w(LOG, "Unable to create typeface, using default.");
576 typeface = Typeface.DEFAULT;
578 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
580 fontSizeSp = Integer.parseInt(fontSize.trim());
581 } catch (NumberFormatException e) {
586 registerForContextMenu(getListView());
589 wordList = application.getWordListFile();
590 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
592 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
593 !getPackageManager().hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN));
594 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
596 onCreateSetupActionBarAndSearchView();
598 View floatSwapButton = findViewById(R.id.floatSwapButton);
599 floatSwapButton.setOnLongClickListener(new OnLongClickListener() {
601 public boolean onLongClick(View v) {
602 onLanguageButtonLongClick(v.getContext());
607 // Set the search text from the intent, then the saved state.
608 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
609 if (savedInstanceState != null) {
610 text = savedInstanceState.getString(C.SEARCH_TOKEN);
616 searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
618 public boolean onSuggestionSelect(int position) {
623 public boolean onSuggestionClick(int position) {
624 String h = searchHistory.get(position);
625 addToSearchHistory(h);
626 setSearchText(h, true);
630 searchView.setSuggestionsAdapter(new CursorAdapter(this, text.isEmpty() ? searchHistoryCursor : null, 0) {
632 public View newView(Context context, Cursor c, ViewGroup p) {
633 TextView v = new TextView(context);
634 v.setTextColor(textColorFg);
635 v.setTypeface(typeface);
636 v.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
640 public void bindView(View v, Context context, Cursor c) {
641 TextView t = (TextView)v;
642 t.setText(c.getString(1));
646 // Set up search history
647 ArrayList<String> savedHistory = null;
648 if (savedInstanceState != null) savedHistory = savedInstanceState.getStringArrayList(C.SEARCH_HISTORY);
649 if (savedHistory != null && !savedHistory.isEmpty()) {
651 savedHistory = new ArrayList<>();
652 for (int i = 0; i < MAX_SEARCH_HISTORY; i++) {
653 String h = prefs.getString("history" + i, null);
654 if (h == null) break;
658 for (int i = savedHistory.size() - 1; i >= 0; i--) {
659 addToSearchHistory(savedHistory.get(i));
661 addToSearchHistory(text);
663 setSearchText(text, true);
664 Log.d(LOG, "Trying to restore searchText=" + text);
666 setDictionaryPrefs(this, dictFile, index.shortName);
669 searchView.requestFocus();
671 // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
672 // getListView().setCacheColorHint(0);
675 private void onCreateSetupActionBarAndSearchView() {
676 ActionBar actionBar = getSupportActionBar();
677 actionBar.setDisplayShowTitleEnabled(false);
678 actionBar.setDisplayShowHomeEnabled(false);
679 actionBar.setDisplayHomeAsUpEnabled(false);
681 final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
683 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
684 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
685 customSearchView.setLayoutParams(layoutParams);
687 languageButton = new ImageButton(customSearchView.getContext());
688 languageButton.setId(R.id.languageButton);
689 languageButton.setScaleType(ScaleType.FIT_CENTER);
690 languageButton.setOnClickListener(new OnClickListener() {
692 public void onClick(View v) {
693 onLanguageButtonLongClick(v.getContext());
696 languageButton.setAdjustViewBounds(true);
697 LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
698 customSearchView.addView(languageButton, lpb);
700 searchView = new SearchView(getSupportActionBar().getThemedContext());
701 searchView.setId(R.id.searchView);
703 // Get rid of search icon, it takes up too much space.
704 // There is still text saying "search" in the search field.
705 searchView.setIconifiedByDefault(true);
706 searchView.setIconified(false);
708 searchView.setQueryHint(getString(R.string.searchText));
709 searchView.setSubmitButtonEnabled(false);
710 searchView.setInputType(InputType.TYPE_CLASS_TEXT);
711 searchView.setImeOptions(
712 EditorInfo.IME_ACTION_DONE |
713 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
714 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
716 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
717 onQueryTextListener = new OnQueryTextListener() {
719 public boolean onQueryTextSubmit(String query) {
720 Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
721 addToSearchHistory();
727 public boolean onQueryTextChange(String newText) {
728 Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
729 onSearchTextChange(searchView.getQuery().toString());
733 searchView.setOnQueryTextListener(onQueryTextListener);
734 searchView.setFocusable(true);
735 searchTextView = (AutoCompleteTextView)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
736 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
737 FrameLayout.LayoutParams.WRAP_CONTENT, 1);
738 customSearchView.addView(searchView, lp);
740 actionBar.setCustomView(customSearchView);
741 actionBar.setDisplayShowCustomEnabled(true);
743 // Avoid wasting space on large left inset
744 Toolbar tb = (Toolbar)customSearchView.getParent();
745 tb.setContentInsetsRelative(0, 0);
747 getListView().setNextFocusLeftId(R.id.searchView);
748 findViewById(R.id.floatSwapButton).setNextFocusRightId(R.id.languageButton);
749 languageButton.setNextFocusLeftId(R.id.floatSwapButton);
753 protected void onResume() {
754 Log.d(LOG, "onResume");
756 if (PreferenceActivity.prefsMightHaveChanged) {
757 PreferenceActivity.prefsMightHaveChanged = false;
759 startActivity(getIntent());
765 * Invoked when MyWebView returns, since the user might have clicked some
766 * hypertext in the MyWebView.
769 protected void onActivityResult(int requestCode, int resultCode, Intent result) {
770 super.onActivityResult(requestCode, resultCode, result);
771 if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
772 Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
773 jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
777 private static void setDictionaryPrefs(final Context context, final File dictFile,
778 final String indexShortName) {
779 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
781 if (dictFile != null) {
782 prefs.putString(C.DICT_FILE, dictFile.getPath());
783 prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
785 prefs.remove(C.SEARCH_TOKEN); // Don't need to save search token.
790 protected void onPause() {
792 addToSearchHistory();
797 protected void onDestroy() {
799 if (dictRaf == null) {
803 final SearchOperation searchOperation = currentSearchOperation;
804 currentSearchOperation = null;
806 // Before we close the RAF, we have to wind the current search down.
807 if (searchOperation != null) {
808 Log.d(LOG, "Interrupting search to shut down.");
809 currentSearchOperation = null;
810 searchOperation.interrupted.set(true);
812 searchExecutor.shutdownNow();
813 textToSpeech.shutdown();
817 setListAdapter(null);
820 Log.d(LOG, "Closing RAF.");
822 } catch (IOException e) {
823 Log.e(LOG, "Failed to close dictionary", e);
828 // --------------------------------------------------------------------------
830 // --------------------------------------------------------------------------
832 private void showKeyboard() {
833 // For some reason, this doesn't always work the first time.
834 // One way to replicate the problem:
835 // Press the "task switch" button repeatedly to pause and resume
836 for (int delay = 1; delay <= 101; delay += 100) {
837 searchView.postDelayed(new Runnable() {
840 Log.d(LOG, "Trying to show soft keyboard.");
841 final boolean searchTextHadFocus = searchView.hasFocus();
842 searchView.requestFocusFromTouch();
843 searchTextView.requestFocus();
844 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
845 manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
846 manager.showSoftInput(searchTextView, InputMethodManager.SHOW_IMPLICIT);
847 if (!searchTextHadFocus) {
853 searchView.post(new Runnable() {
856 searchTextView.setThreshold(0);
857 searchTextView.showDropDown();
862 private void hideKeyboard() {
863 Log.d(LOG, "Hide soft keyboard.");
864 searchView.clearFocus();
865 InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
866 manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
869 private void updateLangButton() {
870 final int flagId = IsoUtils.INSTANCE.getFlagIdForIsoCode(index.shortName);
872 languageButton.setImageResource(flagId);
874 if (indexIndex % 2 == 0) {
875 languageButton.setImageResource(android.R.drawable.ic_media_next);
877 languageButton.setImageResource(android.R.drawable.ic_media_previous);
880 updateTTSLanguage(indexIndex);
883 @SuppressWarnings("deprecation")
884 private void speak(String text) {
885 textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
888 private void updateTTSLanguage(int i) {
889 if (!ttsReady || index == null || textToSpeech == null) {
890 Log.d(LOG, "Can't updateTTSLanguage.");
893 final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
894 Log.d(LOG, "Setting TTS locale to: " + locale);
896 final int ttsResult = textToSpeech.setLanguage(locale);
897 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
898 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
899 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
901 } catch (Exception e) {
903 Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
907 public void onSearchButtonClick(View dummy) {
908 if (!searchView.hasFocus()) {
909 searchView.requestFocus();
911 if (searchView.getQuery().toString().length() > 0) {
912 addToSearchHistory();
913 searchView.setQuery("", false);
916 searchView.setIconified(false);
919 public void onLanguageButtonClick(View dummy) {
920 if (dictionary.indices.size() == 1) {
921 // No need to work to switch indices.
924 if (currentSearchOperation != null) {
925 currentSearchOperation.interrupted.set(true);
926 currentSearchOperation = null;
928 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
929 searchView.getQuery().toString(), false);
932 private void onLanguageButtonLongClick(final Context context) {
933 final Dialog dialog = new Dialog(context);
934 dialog.setContentView(R.layout.select_dictionary_dialog);
935 dialog.setTitle(R.string.selectDictionary);
937 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
939 ListView listView = dialog.findViewById(android.R.id.list);
940 final Button button = new Button(listView.getContext());
941 final String name = getString(R.string.dictionaryManager);
942 button.setText(name);
943 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
944 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
946 protected void onGo() {
948 DictionaryActivity.this.finish();
951 button.setOnClickListener(intentLauncher);
952 listView.addHeaderView(button);
954 listView.setItemsCanFocus(true);
955 listView.setAdapter(new BaseAdapter() {
957 public View getView(int position, View convertView, ViewGroup parent) {
958 final DictionaryInfo dictionaryInfo = getItem(position);
960 final LinearLayout result = new LinearLayout(parent.getContext());
962 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
963 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
964 final View button = IsoUtils.INSTANCE.createButton(parent.getContext(),
965 indexInfo, application.languageButtonPixels);
966 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
967 getLaunchIntent(getApplicationContext(),
968 application.getPath(dictionaryInfo.uncompressedFilename),
969 indexInfo.shortName, searchView.getQuery().toString())) {
971 protected void onGo() {
973 DictionaryActivity.this.finish();
976 button.setOnClickListener(intentLauncher);
977 if (i == indexIndex && dictFile != null &&
978 dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
979 button.setPressed(true);
981 result.addView(button);
984 final TextView nameView = new TextView(parent.getContext());
985 final String name = application
986 .getDictionaryName(dictionaryInfo.uncompressedFilename);
987 nameView.setText(name);
988 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
989 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
990 layoutParams.width = 0;
991 layoutParams.weight = 1.0f;
992 nameView.setLayoutParams(layoutParams);
993 nameView.setGravity(Gravity.CENTER_VERTICAL);
994 result.addView(nameView);
999 public long getItemId(int position) {
1004 public DictionaryInfo getItem(int position) {
1005 return installedDicts.get(position);
1009 public int getCount() {
1010 return installedDicts.size();
1016 private void onUpDownButton(final boolean up) {
1020 final int firstVisibleRow = getListView().getFirstVisiblePosition();
1021 final RowBase row = index.rows.get(firstVisibleRow);
1022 final TokenRow tokenRow = row.getTokenRow(true);
1023 final int destIndexEntry;
1025 if (row != tokenRow) {
1026 destIndexEntry = tokenRow.referenceIndex;
1028 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
1032 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
1034 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
1035 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
1036 setSearchText(dest.token, false);
1037 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
1038 defocusSearchText();
1041 private void onRandomWordButton() {
1042 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
1043 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
1044 setSearchText(dest.token, false);
1045 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
1046 defocusSearchText();
1049 // --------------------------------------------------------------------------
1051 // --------------------------------------------------------------------------
1054 public boolean onCreateOptionsMenu(final Menu menu) {
1056 if (PreferenceManager.getDefaultSharedPreferences(this)
1057 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
1059 nextWordMenuItem = menu.add(getString(R.string.nextWord))
1060 .setIcon(R.drawable.arrow_down_float);
1061 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
1062 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1064 public boolean onMenuItemClick(MenuItem item) {
1065 onUpDownButton(false);
1071 previousWordMenuItem = menu.add(getString(R.string.previousWord))
1072 .setIcon(R.drawable.arrow_up_float);
1073 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
1074 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1076 public boolean onMenuItemClick(MenuItem item) {
1077 onUpDownButton(true);
1083 final MenuItem randomWordMenuItem = menu.add(getString(R.string.randomWord));
1084 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1086 public boolean onMenuItemClick(MenuItem item) {
1087 onRandomWordButton();
1093 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
1094 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
1095 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1096 public boolean onMenuItemClick(final MenuItem menuItem) {
1097 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
1105 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
1106 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
1107 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1108 public boolean onMenuItemClick(final MenuItem menuItem) {
1109 final Context context = getListView().getContext();
1110 final Dialog dialog = new Dialog(context);
1111 dialog.setContentView(R.layout.about_dictionary_dialog);
1112 final TextView textView = dialog.findViewById(R.id.text);
1114 dialog.setTitle(dictFileTitleName);
1116 final StringBuilder builder = new StringBuilder();
1117 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
1118 if (dictionaryInfo != null) {
1120 dictionaryInfo.uncompressedBytes = dictRaf.size();
1121 } catch (IOException e) {
1123 builder.append(dictionaryInfo.dictInfo).append("\n\n");
1124 if (dictFile != null) {
1125 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
1129 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
1132 getString(R.string.dictionaryCreationTime,
1133 dictionaryInfo.creationMillis)).append("\n");
1134 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
1135 builder.append("\n");
1136 builder.append(getString(R.string.indexName, indexInfo.shortName))
1139 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
1142 builder.append("\n");
1143 builder.append(getString(R.string.sources)).append("\n");
1144 for (final EntrySource source : dictionary.sources) {
1146 getString(R.string.sourceInfo, source.getName(),
1147 source.getNumEntries())).append("\n");
1150 textView.setText(builder.toString());
1153 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
1154 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
1155 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
1156 dialog.getWindow().setAttributes(layoutParams);
1162 DictionaryApplication.onCreateGlobalOptionsMenu(this, menu);
1167 // --------------------------------------------------------------------------
1168 // Context Menu + clicks
1169 // --------------------------------------------------------------------------
1172 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1173 final AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
1174 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
1176 if (clickOpensContextMenu && (row instanceof HtmlEntry.Row ||
1177 (row instanceof TokenRow && ((TokenRow)row).getIndexEntry().htmlEntries.size() > 0))) {
1178 final List<HtmlEntry> html = row instanceof TokenRow ? ((TokenRow)row).getIndexEntry().htmlEntries : Collections.singletonList(((HtmlEntry.Row)row).getEntry());
1179 final String highlight = row instanceof HtmlEntry.Row ? row.getTokenRow(true).getToken() : null;
1180 final MenuItem open = menu.add("Open");
1181 open.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1182 public boolean onMenuItemClick(MenuItem item) {
1183 showHtml(html, highlight);
1189 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
1190 wordList.getName()));
1192 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1193 public boolean onMenuItemClick(android.view.MenuItem item) {
1194 onAppendToWordList(row);
1199 final android.view.MenuItem share = menu.add("Share");
1200 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1201 public boolean onMenuItemClick(android.view.MenuItem item) {
1202 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
1203 shareIntent.setType("text/plain");
1204 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
1206 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
1207 row.getRawText(saveOnlyFirstSubentry));
1208 startActivity(shareIntent);
1213 final android.view.MenuItem copy = menu.add(android.R.string.copy);
1214 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1215 public boolean onMenuItemClick(android.view.MenuItem item) {
1221 if (selectedSpannableText != null) {
1222 final String selectedText = selectedSpannableText;
1223 final android.view.MenuItem searchForSelection = menu.add(getString(
1224 R.string.searchForSelection,
1225 selectedSpannableText));
1227 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1228 public boolean onMenuItemClick(android.view.MenuItem item) {
1229 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
1233 // Rats, this won't be shown:
1234 //searchForSelection.setIcon(R.drawable.abs__ic_search);
1237 if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
1238 final android.view.MenuItem speak = menu.add(R.string.speak);
1239 final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
1240 updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
1241 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1243 public boolean onMenuItemClick(android.view.MenuItem item) {
1249 if (row instanceof PairEntry.Row && ttsReady) {
1250 final List<Pair> pairs = ((PairEntry.Row)row).getEntry().pairs;
1251 final MenuItem speakLeft = menu.add(R.string.speak_left);
1252 speakLeft.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1254 public boolean onMenuItemClick(android.view.MenuItem item) {
1255 int idx = index.swapPairEntries ? 1 : 0;
1256 updateTTSLanguage(idx);
1258 for (Pair p : pairs) text += p.get(idx);
1259 text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1264 final MenuItem speakRight = menu.add(R.string.speak_right);
1265 speakRight.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1267 public boolean onMenuItemClick(android.view.MenuItem item) {
1268 int idx = index.swapPairEntries ? 0 : 1;
1269 updateTTSLanguage(idx);
1271 for (Pair p : pairs) text += p.get(idx);
1272 text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1280 private void jumpToTextFromHyperLink(
1281 final String selectedText, final int defaultIndexToUse) {
1282 int indexToUse = -1;
1284 for (int i = 0; i < dictionary.indices.size(); ++i) {
1285 final Index index = dictionary.indices.get(i);
1286 if (indexPrepFinished) {
1287 System.out.println("Doing index lookup: on " + selectedText);
1288 final IndexEntry indexEntry = index.findExact(selectedText);
1289 if (indexEntry != null) {
1290 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1291 .getTokenRow(false);
1292 if (tokenRow != null && tokenRow.hasMainEntry) {
1298 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1301 if (numFound != 1) {
1302 indexToUse = defaultIndexToUse;
1304 // Without this extra delay, the call to jumpToRow that this
1305 // invokes doesn't always actually have any effect.
1306 final int actualIndexToUse = indexToUse;
1307 getListView().postDelayed(new Runnable() {
1310 setIndexAndSearchText(actualIndexToUse, selectedText, true);
1311 addToSearchHistory(selectedText);
1317 * Called when user clicks outside of search text, so that they can start
1318 * typing again immediately.
1320 private void defocusSearchText() {
1321 // Log.d(LOG, "defocusSearchText");
1322 // Request focus so that if we start typing again, it clears the text
1324 getListView().requestFocus();
1326 // Visual indication that a new keystroke will clear the search text.
1327 // Doesn't seem to work unless searchText has focus.
1328 // searchView.selectAll();
1331 private void onListItemClick(ListView l, View v, int rowIdx, long id) {
1332 defocusSearchText();
1333 if (clickOpensContextMenu && dictRaf != null) {
1336 final RowBase row = (RowBase)getListAdapter().getItem(rowIdx);
1337 if (!(row instanceof PairEntry.Row)) {
1343 @SuppressLint("SimpleDateFormat")
1344 private void onAppendToWordList(final RowBase row) {
1345 defocusSearchText();
1347 final StringBuilder rawText = new StringBuilder();
1348 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1349 rawText.append(index.longName).append("\t");
1350 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1351 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1352 Log.d(LOG, "Writing : " + rawText);
1355 wordList.getParentFile().mkdirs();
1356 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1357 out.println(rawText);
1359 } catch (Exception e) {
1360 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1362 Toast.makeText(this,
1363 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1364 Toast.LENGTH_LONG).show();
1368 @SuppressWarnings("deprecation")
1369 private void onCopy(final RowBase row) {
1370 defocusSearchText();
1372 Log.d(LOG, "Copy, row=" + row);
1373 final StringBuilder result = new StringBuilder();
1374 result.append(row.getRawText(false));
1375 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1376 clipboardManager.setText(result.toString());
1377 Log.d(LOG, "Copied: " + result);
1381 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1382 if (event.getUnicodeChar() != 0) {
1383 if (!searchView.hasFocus()) {
1384 setSearchText("" + (char) event.getUnicodeChar(), true);
1385 searchView.requestFocus();
1389 if (keyCode == KeyEvent.KEYCODE_BACK) {
1390 // Log.d(LOG, "Clearing dictionary prefs.");
1391 // Pretend that we just autolaunched so that we won't do it again.
1392 // DictionaryManagerActivity.lastAutoLaunchMillis =
1393 // System.currentTimeMillis();
1395 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1396 Log.d(LOG, "Trying to hide soft keyboard.");
1397 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1398 View focus = getCurrentFocus();
1399 if (inputManager != null && focus != null) {
1400 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1401 InputMethodManager.HIDE_NOT_ALWAYS);
1405 return super.onKeyDown(keyCode, event);
1408 private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
1409 Log.d(LOG, "Changing index to: " + newIndex);
1410 if (newIndex == -1) {
1411 Log.e(LOG, "Invalid index.");
1414 if (newIndex != indexIndex) {
1415 indexIndex = newIndex;
1416 index = dictionary.indices.get(indexIndex);
1417 indexAdapter = new IndexAdapter(index);
1418 setListAdapter(indexAdapter);
1419 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1420 setDictionaryPrefs(this, dictFile, index.shortName);
1423 setSearchText(newSearchText, true, hideKeyboard);
1426 private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
1427 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1428 // Disable the listener, because sometimes it doesn't work.
1429 searchView.setOnQueryTextListener(null);
1430 searchView.setQuery(text, false);
1431 searchView.setOnQueryTextListener(onQueryTextListener);
1433 if (triggerSearch) {
1434 onSearchTextChange(text);
1437 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1443 private void setSearchText(final String text, final boolean triggerSearch) {
1444 setSearchText(text, triggerSearch, true);
1447 // --------------------------------------------------------------------------
1449 // --------------------------------------------------------------------------
1451 private void searchFinished(final SearchOperation searchOperation) {
1452 if (searchOperation.interrupted.get()) {
1453 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1456 if (searchOperation != this.currentSearchOperation) {
1457 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1461 final Index.IndexEntry searchResult = searchOperation.searchResult;
1462 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1464 currentSearchOperation = null;
1465 // Note: it's important to post to the ListView, otherwise
1466 // the jumpToRow will randomly not work.
1467 getListView().post(new Runnable() {
1470 if (currentSearchOperation == null) {
1471 if (searchResult != null) {
1475 jumpToRow(searchResult.startRow);
1476 } else if (searchOperation.multiWordSearchResult != null) {
1477 // Multi-row search....
1478 setFiltered(searchOperation);
1480 throw new IllegalStateException("This should never happen.");
1483 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1489 private void jumpToRow(final int row) {
1490 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1491 // getListView().requestFocusFromTouch();
1492 getListView().setSelectionFromTop(row, 0);
1493 getListView().setSelected(true);
1496 private static final Pattern WHITESPACE = Pattern.compile("\\s+");
1498 final class SearchOperation implements Runnable {
1500 final AtomicBoolean interrupted = new AtomicBoolean(false);
1502 final String searchText;
1504 List<String> searchTokens; // filled in for multiWord.
1508 long searchStartMillis;
1510 Index.IndexEntry searchResult;
1512 List<RowBase> multiWordSearchResult;
1514 boolean done = false;
1516 SearchOperation(final String searchText, final Index index) {
1517 this.searchText = StringUtil.normalizeWhitespace(searchText);
1521 public String toString() {
1522 return String.format("SearchOperation(%s,%s)", searchText, interrupted);
1528 searchStartMillis = System.currentTimeMillis();
1529 final String[] searchTokenArray = WHITESPACE.split(searchText);
1530 if (searchTokenArray.length == 1) {
1531 searchResult = index.findInsertionPoint(searchText, interrupted);
1533 searchTokens = Arrays.asList(searchTokenArray);
1534 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1538 "searchText=" + searchText + ", searchDuration="
1539 + (System.currentTimeMillis() - searchStartMillis)
1540 + ", interrupted=" + interrupted.get());
1541 if (!interrupted.get()) {
1542 uiHandler.post(new Runnable() {
1545 searchFinished(SearchOperation.this);
1549 Log.d(LOG, "interrupted, skipping searchFinished.");
1551 } catch (Exception e) {
1552 Log.e(LOG, "Failure during search (can happen during Activity close): " + e.getMessage());
1554 synchronized (this) {
1562 // --------------------------------------------------------------------------
1564 // --------------------------------------------------------------------------
1566 private void showHtml(final List<HtmlEntry> htmlEntries, final String htmlTextToHighlight) {
1567 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1569 if (typeface == Typeface.SERIF) { style = "font-family: serif;"; }
1570 else if (typeface == Typeface.SANS_SERIF) { style = "font-family: sans-serif;"; }
1571 else if (typeface == Typeface.MONOSPACE) { style = "font-family: monospace;"; }
1572 if (application.getSelectedTheme() == DictionaryApplication.Theme.DEFAULT)
1573 style += "background-color: black; color: white;";
1574 // Log.d(LOG, "html=" + html);
1575 startActivityForResult(
1576 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1577 "<html><head><meta name=\"viewport\" content=\"width=device-width\"></head><body style=\"%s\">%s</body></html>", style, html),
1578 htmlTextToHighlight, false),
1582 final class IndexAdapter extends BaseAdapter {
1584 private static final float PADDING_DEFAULT_DP = 8;
1586 private static final float PADDING_LARGE_DP = 16;
1590 final List<RowBase> rows;
1592 final Set<String> toHighlight;
1594 private int mPaddingDefault;
1596 private int mPaddingLarge;
1598 IndexAdapter(final Index index) {
1601 this.toHighlight = null;
1605 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1608 this.toHighlight = new LinkedHashSet<>(toHighlight);
1612 private void getMetrics() {
1614 // Get the screen's density scale
1615 // The previous method getResources().getDisplayMetrics()
1616 // used to occasionally trigger a null pointer exception,
1617 // so try this instead.
1618 // As it still crashes, add a fallback
1620 DisplayMetrics dm = new DisplayMetrics();
1621 getWindowManager().getDefaultDisplay().getMetrics(dm);
1623 } catch (NullPointerException ignored)
1625 // Convert the dps to pixels, based on density scale
1626 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1627 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1631 public int getCount() {
1636 public RowBase getItem(int position) {
1637 return rows.get(position);
1641 public long getItemId(int position) {
1642 return getItem(position).index();
1646 public int getViewTypeCount() {
1651 public int getItemViewType(int position) {
1652 final RowBase row = getItem(position);
1653 if (row instanceof PairEntry.Row) {
1654 final PairEntry entry = ((PairEntry.Row)row).getEntry();
1655 final int rowCount = entry.pairs.size();
1656 return rowCount > 1 ? 1 : 0;
1657 } else if (row instanceof TokenRow) {
1658 final IndexEntry indexEntry = ((TokenRow)row).getIndexEntry();
1659 return indexEntry.htmlEntries.isEmpty() ? 2 : 3;
1660 } else if (row instanceof HtmlEntry.Row) {
1663 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1668 public View getView(int position, View convertView, ViewGroup parent) {
1669 final RowBase row = getItem(position);
1670 if (row instanceof PairEntry.Row) {
1671 return getView(position, (PairEntry.Row) row, parent, (TableLayout)convertView);
1672 } else if (row instanceof TokenRow) {
1673 return getView((TokenRow) row, parent, (TextView)convertView);
1674 } else if (row instanceof HtmlEntry.Row) {
1675 return getView((HtmlEntry.Row) row, parent, (TextView)convertView);
1677 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1681 private void addBoldSpans(String token, String col1Text, Spannable col1Spannable) {
1683 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1684 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1685 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1686 startPos += token.length();
1690 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1691 TableLayout result) {
1692 final Context context = parent.getContext();
1693 final PairEntry entry = row.getEntry();
1694 final int rowCount = entry.pairs.size();
1695 if (result == null) {
1696 result = new TableLayout(context);
1697 result.setStretchAllColumns(true);
1698 // Because we have a Button inside a ListView row:
1699 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1700 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1701 result.setClickable(true);
1702 result.setFocusable(false);
1703 result.setLongClickable(true);
1704 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1706 result.setBackgroundResource(theme.normalRowBg);
1707 } else if (result.getChildCount() > rowCount) {
1708 result.removeViews(rowCount, result.getChildCount() - rowCount);
1711 for (int r = result.getChildCount(); r < rowCount; ++r) {
1712 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
1713 layoutParams.leftMargin = mPaddingLarge;
1715 final TableRow tableRow = new TableRow(result.getContext());
1717 final TextView col1 = new TextView(tableRow.getContext());
1718 final TextView col2 = new TextView(tableRow.getContext());
1719 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1720 col1.setTextIsSelectable(true);
1721 col2.setTextIsSelectable(true);
1723 col1.setTextColor(textColorFg);
1724 col2.setTextColor(textColorFg);
1729 col1.setTypeface(typeface);
1730 col2.setTypeface(typeface);
1731 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1732 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1733 // col2.setBackgroundResource(theme.otherLangBg);
1735 if (index.swapPairEntries) {
1736 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1737 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1739 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1740 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1743 // Set the columns in the table.
1745 tableRow.addView(col1, layoutParams);
1746 tableRow.addView(col2, layoutParams);
1748 for (int i = 0; i < 2; i++) {
1749 final TextView bullet = new TextView(tableRow.getContext());
1750 bullet.setText(" • ");
1751 LinearLayout wrapped = new LinearLayout(context);
1752 wrapped.setOrientation(LinearLayout.HORIZONTAL);
1753 LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0);
1754 wrapped.addView(bullet, p1);
1755 LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
1756 wrapped.addView(i == 0 ? col1 : col2, p2);
1757 tableRow.addView(wrapped, layoutParams);
1761 result.addView(tableRow);
1764 for (int r = 0; r < rowCount; ++r) {
1765 final TableRow tableRow = (TableRow)result.getChildAt(r);
1766 View left = tableRow.getChildAt(0);
1767 View right = tableRow.getChildAt(1);
1769 left = ((ViewGroup)left).getChildAt(1);
1770 right = ((ViewGroup)right).getChildAt(1);
1772 final TextView col1 = (TextView)left;
1773 final TextView col2 = (TextView)right;
1775 // Set what's in the columns.
1776 final Pair pair = entry.pairs.get(r);
1777 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1778 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1779 final Spannable col1Spannable = new SpannableString(col1Text);
1780 final Spannable col2Spannable = new SpannableString(col2Text);
1782 // Bold the token instances in col1.
1783 if (toHighlight != null) {
1784 for (final String token : toHighlight) {
1785 addBoldSpans(token, col1Text, col1Spannable);
1788 addBoldSpans(row.getTokenRow(true).getToken(), col1Text, col1Spannable);
1790 createTokenLinkSpans(col1, col1Spannable, col1Text);
1791 createTokenLinkSpans(col2, col2Spannable, col2Text);
1793 col1.setText(col1Spannable);
1794 col2.setText(col2Spannable);
1797 result.setOnClickListener(new TextView.OnClickListener() {
1799 public void onClick(View v) {
1800 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1807 private TextView getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1808 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1809 final String htmlTextToHighlight, ViewGroup parent, TextView textView) {
1810 final Context context = parent.getContext();
1811 if (textView == null) {
1812 textView = new TextView(context);
1813 // set up things invariant across one ItemViewType
1814 // ItemViewTypes handled here are:
1815 // 2: isTokenRow == true, htmlEntries.isEmpty() == true
1816 // 3: isTokenRow == true, htmlEntries.isEmpty() == false
1817 // 4: isTokenRow == false, htmlEntries.isEmpty() == false
1818 textView.setPadding(isTokenRow ? mPaddingDefault : mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1819 textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1820 textView.setLongClickable(true);
1822 textView.setTypeface(typeface);
1824 textView.setTextAppearance(context, theme.tokenRowFg);
1825 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1827 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1829 textView.setTextColor(textColorFg);
1830 if (!htmlEntries.isEmpty()) {
1831 textView.setClickable(true);
1832 textView.setMovementMethod(LinkMovementMethod.getInstance());
1836 textView.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1837 : theme.tokenRowOtherBg);
1839 // Make it so we can long-click on these token rows, too:
1840 final Spannable textSpannable = new SpannableString(text);
1841 createTokenLinkSpans(textView, textSpannable, text);
1843 if (!htmlEntries.isEmpty()) {
1844 final ClickableSpan clickableSpan = new ClickableSpan() {
1846 public void onClick(View widget) {
1849 textSpannable.setSpan(clickableSpan, 0, text.length(),
1850 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1851 textView.setOnClickListener(new OnClickListener() {
1853 public void onClick(View v) {
1854 showHtml(htmlEntries, htmlTextToHighlight);
1858 textView.setText(textSpannable);
1862 private TextView getView(TokenRow row, ViewGroup parent, final TextView result) {
1863 final IndexEntry indexEntry = row.getIndexEntry();
1864 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1865 indexEntry.htmlEntries, null, parent, result);
1868 private TextView getView(HtmlEntry.Row row, ViewGroup parent, final TextView result) {
1869 final HtmlEntry htmlEntry = row.getEntry();
1870 final TokenRow tokenRow = row.getTokenRow(true);
1871 return getPossibleLinkToHtmlEntryView(false,
1872 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1873 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1879 private static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1881 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1882 final String text) {
1883 // Saw from the source code that LinkMovementMethod sets the selection!
1884 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1885 textView.setMovementMethod(LinkMovementMethod.getInstance());
1886 final Matcher matcher = CHAR_DASH.matcher(text);
1887 while (matcher.find()) {
1888 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(),
1890 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1894 private String selectedSpannableText = null;
1896 private int selectedSpannableIndex = -1;
1899 public boolean onTouchEvent(MotionEvent event) {
1900 selectedSpannableText = null;
1901 selectedSpannableIndex = -1;
1902 return super.onTouchEvent(event);
1905 private class TextViewLongClickListener implements OnLongClickListener {
1908 private TextViewLongClickListener(final int index) {
1913 public boolean onLongClick(final View v) {
1914 final TextView textView = (TextView) v;
1915 final int start = textView.getSelectionStart();
1916 final int end = textView.getSelectionEnd();
1917 if (start >= 0 && end >= 0) {
1918 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1919 selectedSpannableIndex = index;
1925 private final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1928 private final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1931 // --------------------------------------------------------------------------
1933 // --------------------------------------------------------------------------
1935 private void onSearchTextChange(final String text) {
1936 if ("thadolina".equals(text)) {
1937 final Dialog dialog = new Dialog(getListView().getContext());
1938 dialog.setContentView(R.layout.thadolina_dialog);
1939 dialog.setTitle("Ti amo, amore mio!");
1940 final ImageView imageView = dialog.findViewById(R.id.thadolina_image);
1941 imageView.setOnClickListener(new OnClickListener() {
1943 public void onClick(View v) {
1944 final Intent intent = new Intent(Intent.ACTION_VIEW);
1945 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1946 startActivity(intent);
1951 if (dictRaf == null) {
1952 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1956 // if (!searchView.hasFocus()) {
1957 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1960 Log.d(LOG, "onSearchTextChange: " + text);
1961 if (currentSearchOperation != null) {
1962 Log.d(LOG, "Interrupting currentSearchOperation.");
1963 currentSearchOperation.interrupted.set(true);
1965 currentSearchOperation = new SearchOperation(text, index);
1966 searchExecutor.execute(currentSearchOperation);
1967 ((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
1968 searchView.getSuggestionsAdapter().swapCursor(text.isEmpty() ? searchHistoryCursor : null);
1969 searchView.getSuggestionsAdapter().notifyDataSetChanged();
1972 // --------------------------------------------------------------------------
1973 // Filtered results.
1974 // --------------------------------------------------------------------------
1976 private boolean isFiltered() {
1977 return rowsToShow != null;
1980 private void setFiltered(final SearchOperation searchOperation) {
1981 if (nextWordMenuItem != null) {
1982 nextWordMenuItem.setEnabled(false);
1983 previousWordMenuItem.setEnabled(false);
1985 rowsToShow = searchOperation.multiWordSearchResult;
1986 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1989 private void clearFiltered() {
1990 if (nextWordMenuItem != null) {
1991 nextWordMenuItem.setEnabled(true);
1992 previousWordMenuItem.setEnabled(true);
1994 setListAdapter(new IndexAdapter(index));