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 private void updateTTSLanguage(int i) {
884 if (!ttsReady || index == null || textToSpeech == null) {
885 Log.d(LOG, "Can't updateTTSLanguage.");
888 final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
889 Log.d(LOG, "Setting TTS locale to: " + locale);
891 final int ttsResult = textToSpeech.setLanguage(locale);
892 if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
893 ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
894 Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
896 } catch (Exception e) {
898 Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
902 public void onSearchButtonClick(View dummy) {
903 if (!searchView.hasFocus()) {
904 searchView.requestFocus();
906 if (searchView.getQuery().toString().length() > 0) {
907 addToSearchHistory();
908 searchView.setQuery("", false);
911 searchView.setIconified(false);
914 public void onLanguageButtonClick(View dummy) {
915 if (dictionary.indices.size() == 1) {
916 // No need to work to switch indices.
919 if (currentSearchOperation != null) {
920 currentSearchOperation.interrupted.set(true);
921 currentSearchOperation = null;
923 setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
924 searchView.getQuery().toString(), false);
927 private void onLanguageButtonLongClick(final Context context) {
928 final Dialog dialog = new Dialog(context);
929 dialog.setContentView(R.layout.select_dictionary_dialog);
930 dialog.setTitle(R.string.selectDictionary);
932 final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
934 ListView listView = dialog.findViewById(android.R.id.list);
935 final Button button = new Button(listView.getContext());
936 final String name = getString(R.string.dictionaryManager);
937 button.setText(name);
938 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
939 DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
941 protected void onGo() {
943 DictionaryActivity.this.finish();
946 button.setOnClickListener(intentLauncher);
947 listView.addHeaderView(button);
949 listView.setItemsCanFocus(true);
950 listView.setAdapter(new BaseAdapter() {
952 public View getView(int position, View convertView, ViewGroup parent) {
953 final DictionaryInfo dictionaryInfo = getItem(position);
955 final LinearLayout result = new LinearLayout(parent.getContext());
957 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
958 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
959 final View button = IsoUtils.INSTANCE.createButton(parent.getContext(),
960 indexInfo, application.languageButtonPixels);
961 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
962 getLaunchIntent(getApplicationContext(),
963 application.getPath(dictionaryInfo.uncompressedFilename),
964 indexInfo.shortName, searchView.getQuery().toString())) {
966 protected void onGo() {
968 DictionaryActivity.this.finish();
971 button.setOnClickListener(intentLauncher);
972 if (i == indexIndex && dictFile != null &&
973 dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
974 button.setPressed(true);
976 result.addView(button);
979 final TextView nameView = new TextView(parent.getContext());
980 final String name = application
981 .getDictionaryName(dictionaryInfo.uncompressedFilename);
982 nameView.setText(name);
983 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
984 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
985 layoutParams.width = 0;
986 layoutParams.weight = 1.0f;
987 nameView.setLayoutParams(layoutParams);
988 nameView.setGravity(Gravity.CENTER_VERTICAL);
989 result.addView(nameView);
994 public long getItemId(int position) {
999 public DictionaryInfo getItem(int position) {
1000 return installedDicts.get(position);
1004 public int getCount() {
1005 return installedDicts.size();
1011 private void onUpDownButton(final boolean up) {
1015 final int firstVisibleRow = getListView().getFirstVisiblePosition();
1016 final RowBase row = index.rows.get(firstVisibleRow);
1017 final TokenRow tokenRow = row.getTokenRow(true);
1018 final int destIndexEntry;
1020 if (row != tokenRow) {
1021 destIndexEntry = tokenRow.referenceIndex;
1023 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
1027 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
1029 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
1030 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
1031 setSearchText(dest.token, false);
1032 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
1033 defocusSearchText();
1036 private void onRandomWordButton() {
1037 int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
1038 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
1039 setSearchText(dest.token, false);
1040 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
1041 defocusSearchText();
1044 // --------------------------------------------------------------------------
1046 // --------------------------------------------------------------------------
1049 public boolean onCreateOptionsMenu(final Menu menu) {
1051 if (PreferenceManager.getDefaultSharedPreferences(this)
1052 .getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
1054 nextWordMenuItem = menu.add(getString(R.string.nextWord))
1055 .setIcon(R.drawable.arrow_down_float);
1056 MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
1057 nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1059 public boolean onMenuItemClick(MenuItem item) {
1060 onUpDownButton(false);
1066 previousWordMenuItem = menu.add(getString(R.string.previousWord))
1067 .setIcon(R.drawable.arrow_up_float);
1068 MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
1069 previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1071 public boolean onMenuItemClick(MenuItem item) {
1072 onUpDownButton(true);
1078 final MenuItem randomWordMenuItem = menu.add(getString(R.string.randomWord));
1079 randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1081 public boolean onMenuItemClick(MenuItem item) {
1082 onRandomWordButton();
1088 final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
1089 MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
1090 dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1091 public boolean onMenuItemClick(final MenuItem menuItem) {
1092 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
1100 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
1101 MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
1102 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
1103 public boolean onMenuItemClick(final MenuItem menuItem) {
1104 final Context context = getListView().getContext();
1105 final Dialog dialog = new Dialog(context);
1106 dialog.setContentView(R.layout.about_dictionary_dialog);
1107 final TextView textView = dialog.findViewById(R.id.text);
1109 dialog.setTitle(dictFileTitleName);
1111 final StringBuilder builder = new StringBuilder();
1112 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
1113 if (dictionaryInfo != null) {
1115 dictionaryInfo.uncompressedBytes = dictRaf.size();
1116 } catch (IOException e) {
1118 builder.append(dictionaryInfo.dictInfo).append("\n\n");
1119 if (dictFile != null) {
1120 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
1124 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
1127 getString(R.string.dictionaryCreationTime,
1128 dictionaryInfo.creationMillis)).append("\n");
1129 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
1130 builder.append("\n");
1131 builder.append(getString(R.string.indexName, indexInfo.shortName))
1134 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
1137 builder.append("\n");
1138 builder.append(getString(R.string.sources)).append("\n");
1139 for (final EntrySource source : dictionary.sources) {
1141 getString(R.string.sourceInfo, source.getName(),
1142 source.getNumEntries())).append("\n");
1145 textView.setText(builder.toString());
1148 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
1149 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
1150 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
1151 dialog.getWindow().setAttributes(layoutParams);
1157 DictionaryApplication.onCreateGlobalOptionsMenu(this, menu);
1162 // --------------------------------------------------------------------------
1163 // Context Menu + clicks
1164 // --------------------------------------------------------------------------
1167 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1168 final AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
1169 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
1171 if (clickOpensContextMenu && (row instanceof HtmlEntry.Row ||
1172 (row instanceof TokenRow && ((TokenRow)row).getIndexEntry().htmlEntries.size() > 0))) {
1173 final List<HtmlEntry> html = row instanceof TokenRow ? ((TokenRow)row).getIndexEntry().htmlEntries : Collections.singletonList(((HtmlEntry.Row)row).getEntry());
1174 final String highlight = row instanceof HtmlEntry.Row ? row.getTokenRow(true).getToken() : null;
1175 final MenuItem open = menu.add("Open");
1176 open.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1177 public boolean onMenuItemClick(MenuItem item) {
1178 showHtml(html, highlight);
1184 final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
1185 wordList.getName()));
1187 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1188 public boolean onMenuItemClick(android.view.MenuItem item) {
1189 onAppendToWordList(row);
1194 final android.view.MenuItem share = menu.add("Share");
1195 share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1196 public boolean onMenuItemClick(android.view.MenuItem item) {
1197 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
1198 shareIntent.setType("text/plain");
1199 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
1201 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
1202 row.getRawText(saveOnlyFirstSubentry));
1203 startActivity(shareIntent);
1208 final android.view.MenuItem copy = menu.add(android.R.string.copy);
1209 copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1210 public boolean onMenuItemClick(android.view.MenuItem item) {
1216 if (selectedSpannableText != null) {
1217 final String selectedText = selectedSpannableText;
1218 final android.view.MenuItem searchForSelection = menu.add(getString(
1219 R.string.searchForSelection,
1220 selectedSpannableText));
1222 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1223 public boolean onMenuItemClick(android.view.MenuItem item) {
1224 jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
1228 // Rats, this won't be shown:
1229 //searchForSelection.setIcon(R.drawable.abs__ic_search);
1232 if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
1233 final android.view.MenuItem speak = menu.add(R.string.speak);
1234 final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
1235 updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
1236 speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1238 public boolean onMenuItemClick(android.view.MenuItem item) {
1239 textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
1240 new HashMap<String, String>());
1245 if (row instanceof PairEntry.Row && ttsReady) {
1246 final List<Pair> pairs = ((PairEntry.Row)row).getEntry().pairs;
1247 final MenuItem speakLeft = menu.add(R.string.speak_left);
1248 speakLeft.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1250 public boolean onMenuItemClick(android.view.MenuItem item) {
1251 int idx = index.swapPairEntries ? 1 : 0;
1252 updateTTSLanguage(idx);
1254 for (Pair p : pairs) text += p.get(idx);
1255 text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1256 textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
1257 new HashMap<String, String>());
1261 final MenuItem speakRight = menu.add(R.string.speak_right);
1262 speakRight.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
1264 public boolean onMenuItemClick(android.view.MenuItem item) {
1265 int idx = index.swapPairEntries ? 0 : 1;
1266 updateTTSLanguage(idx);
1268 for (Pair p : pairs) text += p.get(idx);
1269 text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
1270 textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
1271 new HashMap<String, String>());
1278 private void jumpToTextFromHyperLink(
1279 final String selectedText, final int defaultIndexToUse) {
1280 int indexToUse = -1;
1282 for (int i = 0; i < dictionary.indices.size(); ++i) {
1283 final Index index = dictionary.indices.get(i);
1284 if (indexPrepFinished) {
1285 System.out.println("Doing index lookup: on " + selectedText);
1286 final IndexEntry indexEntry = index.findExact(selectedText);
1287 if (indexEntry != null) {
1288 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
1289 .getTokenRow(false);
1290 if (tokenRow != null && tokenRow.hasMainEntry) {
1296 Log.w(LOG, "Skipping findExact on index " + index.shortName);
1299 if (numFound != 1) {
1300 indexToUse = defaultIndexToUse;
1302 // Without this extra delay, the call to jumpToRow that this
1303 // invokes doesn't always actually have any effect.
1304 final int actualIndexToUse = indexToUse;
1305 getListView().postDelayed(new Runnable() {
1308 setIndexAndSearchText(actualIndexToUse, selectedText, true);
1309 addToSearchHistory(selectedText);
1315 * Called when user clicks outside of search text, so that they can start
1316 * typing again immediately.
1318 private void defocusSearchText() {
1319 // Log.d(LOG, "defocusSearchText");
1320 // Request focus so that if we start typing again, it clears the text
1322 getListView().requestFocus();
1324 // Visual indication that a new keystroke will clear the search text.
1325 // Doesn't seem to work unless searchText has focus.
1326 // searchView.selectAll();
1329 private void onListItemClick(ListView l, View v, int rowIdx, long id) {
1330 defocusSearchText();
1331 if (clickOpensContextMenu && dictRaf != null) {
1334 final RowBase row = (RowBase)getListAdapter().getItem(rowIdx);
1335 if (!(row instanceof PairEntry.Row)) {
1341 @SuppressLint("SimpleDateFormat")
1342 private void onAppendToWordList(final RowBase row) {
1343 defocusSearchText();
1345 final StringBuilder rawText = new StringBuilder();
1346 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
1347 rawText.append(index.longName).append("\t");
1348 rawText.append(row.getTokenRow(true).getToken()).append("\t");
1349 rawText.append(row.getRawText(saveOnlyFirstSubentry));
1350 Log.d(LOG, "Writing : " + rawText);
1353 wordList.getParentFile().mkdirs();
1354 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
1355 out.println(rawText);
1357 } catch (Exception e) {
1358 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
1360 Toast.makeText(this,
1361 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
1362 Toast.LENGTH_LONG).show();
1366 @SuppressWarnings("deprecation")
1367 private void onCopy(final RowBase row) {
1368 defocusSearchText();
1370 Log.d(LOG, "Copy, row=" + row);
1371 final StringBuilder result = new StringBuilder();
1372 result.append(row.getRawText(false));
1373 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1374 clipboardManager.setText(result.toString());
1375 Log.d(LOG, "Copied: " + result);
1379 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
1380 if (event.getUnicodeChar() != 0) {
1381 if (!searchView.hasFocus()) {
1382 setSearchText("" + (char) event.getUnicodeChar(), true);
1383 searchView.requestFocus();
1387 if (keyCode == KeyEvent.KEYCODE_BACK) {
1388 // Log.d(LOG, "Clearing dictionary prefs.");
1389 // Pretend that we just autolaunched so that we won't do it again.
1390 // DictionaryManagerActivity.lastAutoLaunchMillis =
1391 // System.currentTimeMillis();
1393 if (keyCode == KeyEvent.KEYCODE_ENTER) {
1394 Log.d(LOG, "Trying to hide soft keyboard.");
1395 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1396 View focus = getCurrentFocus();
1397 if (inputManager != null && focus != null) {
1398 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
1399 InputMethodManager.HIDE_NOT_ALWAYS);
1403 return super.onKeyDown(keyCode, event);
1406 private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
1407 Log.d(LOG, "Changing index to: " + newIndex);
1408 if (newIndex == -1) {
1409 Log.e(LOG, "Invalid index.");
1412 if (newIndex != indexIndex) {
1413 indexIndex = newIndex;
1414 index = dictionary.indices.get(indexIndex);
1415 indexAdapter = new IndexAdapter(index);
1416 setListAdapter(indexAdapter);
1417 Log.d(LOG, "changingIndex, newLang=" + index.longName);
1418 setDictionaryPrefs(this, dictFile, index.shortName);
1421 setSearchText(newSearchText, true, hideKeyboard);
1424 private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
1425 Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
1426 // Disable the listener, because sometimes it doesn't work.
1427 searchView.setOnQueryTextListener(null);
1428 searchView.setQuery(text, false);
1429 searchView.setOnQueryTextListener(onQueryTextListener);
1431 if (triggerSearch) {
1432 onSearchTextChange(text);
1435 // We don't want to show virtual keyboard when we're changing searchView text programatically:
1441 private void setSearchText(final String text, final boolean triggerSearch) {
1442 setSearchText(text, triggerSearch, true);
1445 // --------------------------------------------------------------------------
1447 // --------------------------------------------------------------------------
1449 private void searchFinished(final SearchOperation searchOperation) {
1450 if (searchOperation.interrupted.get()) {
1451 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
1454 if (searchOperation != this.currentSearchOperation) {
1455 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
1459 final Index.IndexEntry searchResult = searchOperation.searchResult;
1460 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
1462 currentSearchOperation = null;
1463 // Note: it's important to post to the ListView, otherwise
1464 // the jumpToRow will randomly not work.
1465 getListView().post(new Runnable() {
1468 if (currentSearchOperation == null) {
1469 if (searchResult != null) {
1473 jumpToRow(searchResult.startRow);
1474 } else if (searchOperation.multiWordSearchResult != null) {
1475 // Multi-row search....
1476 setFiltered(searchOperation);
1478 throw new IllegalStateException("This should never happen.");
1481 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
1487 private void jumpToRow(final int row) {
1488 Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
1489 // getListView().requestFocusFromTouch();
1490 getListView().setSelectionFromTop(row, 0);
1491 getListView().setSelected(true);
1494 private static final Pattern WHITESPACE = Pattern.compile("\\s+");
1496 final class SearchOperation implements Runnable {
1498 final AtomicBoolean interrupted = new AtomicBoolean(false);
1500 final String searchText;
1502 List<String> searchTokens; // filled in for multiWord.
1506 long searchStartMillis;
1508 Index.IndexEntry searchResult;
1510 List<RowBase> multiWordSearchResult;
1512 boolean done = false;
1514 SearchOperation(final String searchText, final Index index) {
1515 this.searchText = StringUtil.normalizeWhitespace(searchText);
1519 public String toString() {
1520 return String.format("SearchOperation(%s,%s)", searchText, interrupted);
1526 searchStartMillis = System.currentTimeMillis();
1527 final String[] searchTokenArray = WHITESPACE.split(searchText);
1528 if (searchTokenArray.length == 1) {
1529 searchResult = index.findInsertionPoint(searchText, interrupted);
1531 searchTokens = Arrays.asList(searchTokenArray);
1532 multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
1536 "searchText=" + searchText + ", searchDuration="
1537 + (System.currentTimeMillis() - searchStartMillis)
1538 + ", interrupted=" + interrupted.get());
1539 if (!interrupted.get()) {
1540 uiHandler.post(new Runnable() {
1543 searchFinished(SearchOperation.this);
1547 Log.d(LOG, "interrupted, skipping searchFinished.");
1549 } catch (Exception e) {
1550 Log.e(LOG, "Failure during search (can happen during Activity close): " + e.getMessage());
1552 synchronized (this) {
1560 // --------------------------------------------------------------------------
1562 // --------------------------------------------------------------------------
1564 private void showHtml(final List<HtmlEntry> htmlEntries, final String htmlTextToHighlight) {
1565 String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
1567 if (typeface == Typeface.SERIF) { style = "font-family: serif;"; }
1568 else if (typeface == Typeface.SANS_SERIF) { style = "font-family: sans-serif;"; }
1569 else if (typeface == Typeface.MONOSPACE) { style = "font-family: monospace;"; }
1570 if (application.getSelectedTheme() == DictionaryApplication.Theme.DEFAULT)
1571 style += "background-color: black; color: white;";
1572 // Log.d(LOG, "html=" + html);
1573 startActivityForResult(
1574 HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
1575 "<html><head><meta name=\"viewport\" content=\"width=device-width\"></head><body style=\"%s\">%s</body></html>", style, html),
1576 htmlTextToHighlight, false),
1580 final class IndexAdapter extends BaseAdapter {
1582 private static final float PADDING_DEFAULT_DP = 8;
1584 private static final float PADDING_LARGE_DP = 16;
1588 final List<RowBase> rows;
1590 final Set<String> toHighlight;
1592 private int mPaddingDefault;
1594 private int mPaddingLarge;
1596 IndexAdapter(final Index index) {
1599 this.toHighlight = null;
1603 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1606 this.toHighlight = new LinkedHashSet<>(toHighlight);
1610 private void getMetrics() {
1612 // Get the screen's density scale
1613 // The previous method getResources().getDisplayMetrics()
1614 // used to occasionally trigger a null pointer exception,
1615 // so try this instead.
1616 // As it still crashes, add a fallback
1618 DisplayMetrics dm = new DisplayMetrics();
1619 getWindowManager().getDefaultDisplay().getMetrics(dm);
1621 } catch (NullPointerException ignored)
1623 // Convert the dps to pixels, based on density scale
1624 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1625 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1629 public int getCount() {
1634 public RowBase getItem(int position) {
1635 return rows.get(position);
1639 public long getItemId(int position) {
1640 return getItem(position).index();
1644 public int getViewTypeCount() {
1649 public int getItemViewType(int position) {
1650 final RowBase row = getItem(position);
1651 if (row instanceof PairEntry.Row) {
1652 final PairEntry entry = ((PairEntry.Row)row).getEntry();
1653 final int rowCount = entry.pairs.size();
1654 return rowCount > 1 ? 1 : 0;
1655 } else if (row instanceof TokenRow) {
1656 final IndexEntry indexEntry = ((TokenRow)row).getIndexEntry();
1657 return indexEntry.htmlEntries.isEmpty() ? 2 : 3;
1658 } else if (row instanceof HtmlEntry.Row) {
1661 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1666 public View getView(int position, View convertView, ViewGroup parent) {
1667 final RowBase row = getItem(position);
1668 if (row instanceof PairEntry.Row) {
1669 return getView(position, (PairEntry.Row) row, parent, (TableLayout)convertView);
1670 } else if (row instanceof TokenRow) {
1671 return getView((TokenRow) row, parent, (TextView)convertView);
1672 } else if (row instanceof HtmlEntry.Row) {
1673 return getView((HtmlEntry.Row) row, parent, (TextView)convertView);
1675 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1679 private void addBoldSpans(String token, String col1Text, Spannable col1Spannable) {
1681 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1682 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1683 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1684 startPos += token.length();
1688 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1689 TableLayout result) {
1690 final Context context = parent.getContext();
1691 final PairEntry entry = row.getEntry();
1692 final int rowCount = entry.pairs.size();
1693 if (result == null) {
1694 result = new TableLayout(context);
1695 result.setStretchAllColumns(true);
1696 // Because we have a Button inside a ListView row:
1697 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1698 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1699 result.setClickable(true);
1700 result.setFocusable(false);
1701 result.setLongClickable(true);
1702 // result.setBackgroundResource(android.R.drawable.menuitem_background);
1704 result.setBackgroundResource(theme.normalRowBg);
1705 } else if (result.getChildCount() > rowCount) {
1706 result.removeViews(rowCount, result.getChildCount() - rowCount);
1709 for (int r = result.getChildCount(); r < rowCount; ++r) {
1710 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
1711 layoutParams.leftMargin = mPaddingLarge;
1713 final TableRow tableRow = new TableRow(result.getContext());
1715 final TextView col1 = new TextView(tableRow.getContext());
1716 final TextView col2 = new TextView(tableRow.getContext());
1717 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1718 col1.setTextIsSelectable(true);
1719 col2.setTextIsSelectable(true);
1721 col1.setTextColor(textColorFg);
1722 col2.setTextColor(textColorFg);
1727 col1.setTypeface(typeface);
1728 col2.setTypeface(typeface);
1729 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1730 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1731 // col2.setBackgroundResource(theme.otherLangBg);
1733 if (index.swapPairEntries) {
1734 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1735 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1737 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1738 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1741 // Set the columns in the table.
1743 tableRow.addView(col1, layoutParams);
1744 tableRow.addView(col2, layoutParams);
1746 for (int i = 0; i < 2; i++) {
1747 final TextView bullet = new TextView(tableRow.getContext());
1748 bullet.setText(" • ");
1749 LinearLayout wrapped = new LinearLayout(context);
1750 wrapped.setOrientation(LinearLayout.HORIZONTAL);
1751 LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0);
1752 wrapped.addView(bullet, p1);
1753 LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
1754 wrapped.addView(i == 0 ? col1 : col2, p2);
1755 tableRow.addView(wrapped, layoutParams);
1759 result.addView(tableRow);
1762 for (int r = 0; r < rowCount; ++r) {
1763 final TableRow tableRow = (TableRow)result.getChildAt(r);
1764 View left = tableRow.getChildAt(0);
1765 View right = tableRow.getChildAt(1);
1767 left = ((ViewGroup)left).getChildAt(1);
1768 right = ((ViewGroup)right).getChildAt(1);
1770 final TextView col1 = (TextView)left;
1771 final TextView col2 = (TextView)right;
1773 // Set what's in the columns.
1774 final Pair pair = entry.pairs.get(r);
1775 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1776 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1777 final Spannable col1Spannable = new SpannableString(col1Text);
1778 final Spannable col2Spannable = new SpannableString(col2Text);
1780 // Bold the token instances in col1.
1781 if (toHighlight != null) {
1782 for (final String token : toHighlight) {
1783 addBoldSpans(token, col1Text, col1Spannable);
1786 addBoldSpans(row.getTokenRow(true).getToken(), col1Text, col1Spannable);
1788 createTokenLinkSpans(col1, col1Spannable, col1Text);
1789 createTokenLinkSpans(col2, col2Spannable, col2Text);
1791 col1.setText(col1Spannable);
1792 col2.setText(col2Spannable);
1795 result.setOnClickListener(new TextView.OnClickListener() {
1797 public void onClick(View v) {
1798 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1805 private TextView getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
1806 final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
1807 final String htmlTextToHighlight, ViewGroup parent, TextView textView) {
1808 final Context context = parent.getContext();
1809 if (textView == null) {
1810 textView = new TextView(context);
1811 // set up things invariant across one ItemViewType
1812 // ItemViewTypes handled here are:
1813 // 2: isTokenRow == true, htmlEntries.isEmpty() == true
1814 // 3: isTokenRow == true, htmlEntries.isEmpty() == false
1815 // 4: isTokenRow == false, htmlEntries.isEmpty() == false
1816 textView.setPadding(isTokenRow ? mPaddingDefault : mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
1817 textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
1818 textView.setLongClickable(true);
1820 textView.setTypeface(typeface);
1822 textView.setTextAppearance(context, theme.tokenRowFg);
1823 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
1825 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1827 textView.setTextColor(textColorFg);
1828 if (!htmlEntries.isEmpty()) {
1829 textView.setClickable(true);
1830 textView.setMovementMethod(LinkMovementMethod.getInstance());
1834 textView.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
1835 : theme.tokenRowOtherBg);
1837 // Make it so we can long-click on these token rows, too:
1838 final Spannable textSpannable = new SpannableString(text);
1839 createTokenLinkSpans(textView, textSpannable, text);
1841 if (!htmlEntries.isEmpty()) {
1842 final ClickableSpan clickableSpan = new ClickableSpan() {
1844 public void onClick(View widget) {
1847 textSpannable.setSpan(clickableSpan, 0, text.length(),
1848 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1849 textView.setOnClickListener(new OnClickListener() {
1851 public void onClick(View v) {
1852 showHtml(htmlEntries, htmlTextToHighlight);
1856 textView.setText(textSpannable);
1860 private TextView getView(TokenRow row, ViewGroup parent, final TextView result) {
1861 final IndexEntry indexEntry = row.getIndexEntry();
1862 return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
1863 indexEntry.htmlEntries, null, parent, result);
1866 private TextView getView(HtmlEntry.Row row, ViewGroup parent, final TextView result) {
1867 final HtmlEntry htmlEntry = row.getEntry();
1868 final TokenRow tokenRow = row.getTokenRow(true);
1869 return getPossibleLinkToHtmlEntryView(false,
1870 getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
1871 false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
1877 private static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1879 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1880 final String text) {
1881 // Saw from the source code that LinkMovementMethod sets the selection!
1882 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1883 textView.setMovementMethod(LinkMovementMethod.getInstance());
1884 final Matcher matcher = CHAR_DASH.matcher(text);
1885 while (matcher.find()) {
1886 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(),
1888 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1892 private String selectedSpannableText = null;
1894 private int selectedSpannableIndex = -1;
1897 public boolean onTouchEvent(MotionEvent event) {
1898 selectedSpannableText = null;
1899 selectedSpannableIndex = -1;
1900 return super.onTouchEvent(event);
1903 private class TextViewLongClickListener implements OnLongClickListener {
1906 private TextViewLongClickListener(final int index) {
1911 public boolean onLongClick(final View v) {
1912 final TextView textView = (TextView) v;
1913 final int start = textView.getSelectionStart();
1914 final int end = textView.getSelectionEnd();
1915 if (start >= 0 && end >= 0) {
1916 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1917 selectedSpannableIndex = index;
1923 private final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1926 private final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1929 // --------------------------------------------------------------------------
1931 // --------------------------------------------------------------------------
1933 private void onSearchTextChange(final String text) {
1934 if ("thadolina".equals(text)) {
1935 final Dialog dialog = new Dialog(getListView().getContext());
1936 dialog.setContentView(R.layout.thadolina_dialog);
1937 dialog.setTitle("Ti amo, amore mio!");
1938 final ImageView imageView = dialog.findViewById(R.id.thadolina_image);
1939 imageView.setOnClickListener(new OnClickListener() {
1941 public void onClick(View v) {
1942 final Intent intent = new Intent(Intent.ACTION_VIEW);
1943 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1944 startActivity(intent);
1949 if (dictRaf == null) {
1950 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1954 // if (!searchView.hasFocus()) {
1955 // Log.d(LOG, "searchText changed without focus, doing nothing.");
1958 Log.d(LOG, "onSearchTextChange: " + text);
1959 if (currentSearchOperation != null) {
1960 Log.d(LOG, "Interrupting currentSearchOperation.");
1961 currentSearchOperation.interrupted.set(true);
1963 currentSearchOperation = new SearchOperation(text, index);
1964 searchExecutor.execute(currentSearchOperation);
1965 ((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
1966 searchView.getSuggestionsAdapter().swapCursor(text.isEmpty() ? searchHistoryCursor : null);
1967 searchView.getSuggestionsAdapter().notifyDataSetChanged();
1970 // --------------------------------------------------------------------------
1971 // Filtered results.
1972 // --------------------------------------------------------------------------
1974 private boolean isFiltered() {
1975 return rowsToShow != null;
1978 private void setFiltered(final SearchOperation searchOperation) {
1979 if (nextWordMenuItem != null) {
1980 nextWordMenuItem.setEnabled(false);
1981 previousWordMenuItem.setEnabled(false);
1983 rowsToShow = searchOperation.multiWordSearchResult;
1984 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1987 private void clearFiltered() {
1988 if (nextWordMenuItem != null) {
1989 nextWordMenuItem.setEnabled(true);
1990 previousWordMenuItem.setEnabled(true);
1992 setListAdapter(new IndexAdapter(index));