1 // Copyright 2011 Google Inc. All Rights Reserved.
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 com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
18 import com.hughes.android.dictionary.engine.Dictionary;
19 import com.hughes.android.dictionary.engine.EntrySource;
20 import com.hughes.android.dictionary.engine.HtmlEntry;
21 import com.hughes.android.dictionary.engine.Index;
22 import com.hughes.android.dictionary.engine.Index.IndexEntry;
23 import com.hughes.android.dictionary.engine.PairEntry;
24 import com.hughes.android.dictionary.engine.PairEntry.Pair;
25 import com.hughes.android.dictionary.engine.RowBase;
26 import com.hughes.android.dictionary.engine.TokenRow;
27 import com.hughes.android.dictionary.engine.TransliteratorManager;
28 import com.hughes.android.util.IntentLauncher;
29 import com.hughes.android.util.NonLinkClickableSpan;
31 import android.app.Dialog;
32 import android.app.ListActivity;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.SharedPreferences;
36 import android.graphics.Typeface;
37 import android.net.Uri;
38 import android.os.Bundle;
39 import android.os.Handler;
40 import android.preference.PreferenceManager;
41 import android.text.ClipboardManager;
42 import android.text.Editable;
43 import android.text.Selection;
44 import android.text.Spannable;
45 import android.text.TextWatcher;
46 import android.text.method.LinkMovementMethod;
47 import android.text.style.StyleSpan;
48 import android.util.Log;
49 import android.util.TypedValue;
50 import android.view.ContextMenu;
51 import android.view.ContextMenu.ContextMenuInfo;
52 import android.view.KeyEvent;
53 import android.view.Menu;
54 import android.view.MenuItem;
55 import android.view.MenuItem.OnMenuItemClickListener;
56 import android.view.MotionEvent;
57 import android.view.View;
58 import android.view.View.OnClickListener;
59 import android.view.View.OnLongClickListener;
60 import android.view.ViewGroup;
61 import android.view.WindowManager;
62 import android.view.inputmethod.InputMethodManager;
63 import android.widget.AdapterView;
64 import android.widget.AdapterView.AdapterContextMenuInfo;
65 import android.widget.BaseAdapter;
66 import android.widget.Button;
67 import android.widget.EditText;
68 import android.widget.ImageView;
69 import android.widget.LinearLayout;
70 import android.widget.ListAdapter;
71 import android.widget.ListView;
72 import android.widget.TableLayout;
73 import android.widget.TableRow;
74 import android.widget.TextView;
75 import android.widget.Toast;
78 import java.io.FileWriter;
79 import java.io.IOException;
80 import java.io.PrintWriter;
81 import java.io.RandomAccessFile;
82 import java.text.SimpleDateFormat;
83 import java.util.Arrays;
84 import java.util.Collections;
85 import java.util.Date;
86 import java.util.LinkedHashSet;
87 import java.util.List;
88 import java.util.Random;
90 import java.util.concurrent.Executor;
91 import java.util.concurrent.Executors;
92 import java.util.concurrent.ThreadFactory;
93 import java.util.concurrent.atomic.AtomicBoolean;
94 import java.util.regex.Matcher;
95 import java.util.regex.Pattern;
97 public class DictionaryActivity extends ListActivity {
99 static final String LOG = "QuickDic";
101 private String initialSearchText;
103 DictionaryApplication application;
105 File dictFile = null;
107 RandomAccessFile dictRaf = null;
109 Dictionary dictionary = null;
115 List<RowBase> rowsToShow = null; // if not null, just show these rows.
118 final Handler uiHandler = new Handler();
120 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
122 public Thread newThread(Runnable r) {
123 return new Thread(r, "searchExecutor");
127 private SearchOperation currentSearchOperation = null;
129 C.Theme theme = C.Theme.LIGHT;
140 private File wordList = null;
142 private boolean saveOnlyFirstSubentry = false;
144 private boolean clickOpensContextMenu = false;
146 // Visible for testing.
147 ListAdapter indexAdapter = null;
149 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
152 * For some languages, loading the transliterators used in this search takes
153 * a long time, so we fire it up on a different thread, and don't invoke it
154 * from the main thread until it's already finished once.
156 private volatile boolean indexPrepFinished = false;
158 public DictionaryActivity() {
161 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
162 final String searchToken) {
163 final Intent intent = new Intent();
164 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
165 DictionaryActivity.class.getName());
166 intent.putExtra(C.DICT_FILE, dictFile.getPath());
167 intent.putExtra(C.INDEX_INDEX, indexIndex);
168 intent.putExtra(C.SEARCH_TOKEN, searchToken);
173 protected void onSaveInstanceState(final Bundle outState) {
174 super.onSaveInstanceState(outState);
175 Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
176 outState.putInt(C.INDEX_INDEX, indexIndex);
177 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
181 protected void onRestoreInstanceState(final Bundle outState) {
182 super.onRestoreInstanceState(outState);
183 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
188 public void onCreate(Bundle savedInstanceState) {
189 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
190 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
193 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
195 Log.d(LOG, "onCreate:" + this);
196 super.onCreate(savedInstanceState);
198 application = (DictionaryApplication) getApplication();
199 theme = application.getSelectedTheme();
201 final Intent intent = getIntent();
202 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
205 final String name = application.getDictionaryName(dictFile.getName());
206 this.setTitle("QuickDic: " + name);
207 dictRaf = new RandomAccessFile(dictFile, "r");
208 dictionary = new Dictionary(dictRaf);
209 } catch (Exception e) {
210 Log.e(LOG, "Unable to load dictionary.", e);
211 if (dictRaf != null) {
214 } catch (IOException e1) {
215 Log.e(LOG, "Unable to close dictRaf.", e1);
219 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
220 Toast.LENGTH_LONG).show();
221 startActivity(DictionaryManagerActivity.getLaunchIntent());
225 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
226 if (savedInstanceState != null) {
227 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
229 indexIndex %= dictionary.indices.size();
230 Log.d(LOG, "Loading index " + indexIndex);
231 index = dictionary.indices.get(indexIndex);
232 setListAdapter(new IndexAdapter(index));
234 // Pre-load the collators.
235 new Thread(new Runnable() {
237 final long startMillis = System.currentTimeMillis();
239 TransliteratorManager.init(new TransliteratorManager.Callback() {
241 public void onTransliteratorReady() {
242 uiHandler.post(new Runnable() {
245 onSearchTextChange(searchText.getText().toString());
251 for (final Index index : dictionary.indices) {
252 final String searchToken = index.sortedIndexEntries.get(0).token;
253 final IndexEntry entry = index.findExact(searchToken);
254 if (!searchToken.equals(entry.token)) {
255 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
258 indexPrepFinished = true;
259 } catch (Exception e) {
261 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
263 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
267 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
268 if ("SYSTEM".equals(fontName)) {
269 typeface = Typeface.DEFAULT;
272 typeface = Typeface.createFromAsset(getAssets(), fontName);
273 } catch (Exception e) {
274 Log.w(LOG, "Exception trying to use typeface, using default.", e);
275 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
276 Toast.LENGTH_LONG).show();
279 // if (!"SYSTEM".equals(fontName)) {
280 // throw new RuntimeException("Test force using system font: " +
283 if (typeface == null) {
284 Log.w(LOG, "Unable to create typeface, using default.");
285 typeface = Typeface.DEFAULT;
287 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
289 fontSizeSp = Integer.parseInt(fontSize.trim());
290 } catch (NumberFormatException e) {
294 setContentView(R.layout.dictionary_activity);
295 searchText = (EditText) findViewById(R.id.SearchText);
297 langButton = (Button) findViewById(R.id.LangButton);
299 searchText.requestFocus();
300 searchText.addTextChangedListener(searchTextWatcher);
302 // Set the search text from the intent, then the saved state.
303 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
304 if (savedInstanceState != null) {
305 text = savedInstanceState.getString(C.SEARCH_TOKEN);
310 setSearchText(text, true);
311 Log.d(LOG, "Trying to restore searchText=" + text);
313 final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
314 clearSearchTextButton.setOnClickListener(new OnClickListener() {
315 public void onClick(View v) {
316 onClearSearchTextButton();
319 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
320 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
323 final Button langButton = (Button) findViewById(R.id.LangButton);
324 langButton.setOnClickListener(new OnClickListener() {
325 public void onClick(View v) {
329 langButton.setOnLongClickListener(new OnLongClickListener() {
331 public boolean onLongClick(View v) {
332 onLanguageButtonLongClick(v.getContext());
338 final Button upButton = (Button) findViewById(R.id.UpButton);
339 upButton.setOnClickListener(new OnClickListener() {
340 public void onClick(View v) {
341 onUpDownButton(true);
344 final Button downButton = (Button) findViewById(R.id.DownButton);
345 downButton.setOnClickListener(new OnClickListener() {
346 public void onClick(View v) {
347 onUpDownButton(false);
351 getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
353 public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
355 if (!searchText.isFocused()) {
357 final RowBase row = (RowBase) getListAdapter().getItem(position);
358 Log.d(LOG, "onItemSelected: " + row.index());
359 final TokenRow tokenRow = row.getTokenRow(true);
360 searchText.setText(tokenRow.getToken());
366 public void onNothingSelected(AdapterView<?> arg0) {
371 registerForContextMenu(getListView());
374 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
375 getString(R.string.wordListFileDefault)));
376 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
378 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
380 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
382 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
384 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
386 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
390 protected void onResume() {
392 if (PreferenceActivity.prefsMightHaveChanged) {
393 PreferenceActivity.prefsMightHaveChanged = false;
395 startActivity(getIntent());
397 if (initialSearchText != null) {
398 setSearchText(initialSearchText, true);
403 protected void onPause() {
407 private static void setDictionaryPrefs(final Context context, final File dictFile,
408 final int indexIndex, final String searchToken) {
409 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
411 prefs.putString(C.DICT_FILE, dictFile.getPath());
412 prefs.putInt(C.INDEX_INDEX, indexIndex);
413 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
418 protected void onDestroy() {
420 if (dictRaf == null) {
424 final SearchOperation searchOperation = currentSearchOperation;
425 currentSearchOperation = null;
427 // Before we close the RAF, we have to wind the current search down.
428 if (searchOperation != null) {
429 Log.d(LOG, "Interrupting search to shut down.");
430 currentSearchOperation = null;
431 searchOperation.interrupted.set(true);
435 Log.d(LOG, "Closing RAF.");
437 } catch (IOException e) {
438 Log.e(LOG, "Failed to close dictionary", e);
443 // --------------------------------------------------------------------------
445 // --------------------------------------------------------------------------
447 private void onClearSearchTextButton() {
448 setSearchText("", true);
449 Log.d(LOG, "Trying to show soft keyboard.");
450 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
451 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
454 void updateLangButton() {
455 // final LanguageResources languageResources =
456 // Language.isoCodeToResources.get(index.shortName);
457 // if (languageResources != null && languageResources.flagId != 0) {
458 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
459 // languageResources.flagId, 0);
461 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
462 langButton.setText(index.shortName);
466 void onLanguageButton() {
467 if (currentSearchOperation != null) {
468 currentSearchOperation.interrupted.set(true);
469 currentSearchOperation = null;
471 changeIndexGetFocusAndResearch((indexIndex + 1) % dictionary.indices.size());
474 void onLanguageButtonLongClick(final Context context) {
475 final Dialog dialog = new Dialog(context);
476 dialog.setContentView(R.layout.select_dictionary_dialog);
477 dialog.setTitle(R.string.selectDictionary);
479 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
482 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
484 // final LinearLayout.LayoutParams layoutParams = new
485 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
486 // ViewGroup.LayoutParams.WRAP_CONTENT);
487 // layoutParams.width = 0;
488 // layoutParams.weight = 1.0f;
490 final Button button = new Button(listView.getContext());
491 final String name = getString(R.string.dictionaryManager);
492 button.setText(name);
493 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
494 DictionaryManagerActivity.getLaunchIntent()) {
496 protected void onGo() {
498 DictionaryActivity.this.finish();
501 button.setOnClickListener(intentLauncher);
502 // button.setLayoutParams(layoutParams);
503 listView.addHeaderView(button);
504 // listView.setHeaderDividersEnabled(true);
506 listView.setAdapter(new BaseAdapter() {
508 public View getView(int position, View convertView, ViewGroup parent) {
509 final LinearLayout result = new LinearLayout(parent.getContext());
511 final DictionaryInfo dictionaryInfo = getItem(position);
512 final Button button = new Button(parent.getContext());
513 final String name = application
514 .getDictionaryName(dictionaryInfo.uncompressedFilename);
515 button.setText(name);
516 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
517 getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
518 0, searchText.getText().toString())) {
520 protected void onGo() {
522 DictionaryActivity.this.finish();
525 button.setOnClickListener(intentLauncher);
526 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
527 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
528 layoutParams.width = 0;
529 layoutParams.weight = 1.0f;
530 button.setLayoutParams(layoutParams);
531 result.addView(button);
536 public long getItemId(int position) {
541 public DictionaryInfo getItem(int position) {
542 return installedDicts.get(position);
546 public int getCount() {
547 return installedDicts.size();
554 private void changeIndexGetFocusAndResearch(final int newIndex) {
555 indexIndex = newIndex;
556 index = dictionary.indices.get(indexIndex);
557 indexAdapter = new IndexAdapter(index);
558 Log.d(LOG, "changingIndex, newLang=" + index.longName);
559 setListAdapter(indexAdapter);
561 searchText.requestFocus(); // Otherwise, nothing may happen.
562 onSearchTextChange(searchText.getText().toString());
563 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
566 void onUpDownButton(final boolean up) {
570 final int firstVisibleRow = getListView().getFirstVisiblePosition();
571 final RowBase row = index.rows.get(firstVisibleRow);
572 final TokenRow tokenRow = row.getTokenRow(true);
573 final int destIndexEntry;
575 if (row != tokenRow) {
576 destIndexEntry = tokenRow.referenceIndex;
578 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
582 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
584 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
585 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
586 searchText.removeTextChangedListener(searchTextWatcher);
587 searchText.setText(dest.token);
588 if (searchText.getLayout() != null) {
589 // Surprising, but this can otherwise crash sometimes...
590 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
592 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
593 searchText.addTextChangedListener(searchTextWatcher);
596 // --------------------------------------------------------------------------
598 // --------------------------------------------------------------------------
600 final Random random = new Random();
603 public boolean onCreateOptionsMenu(final Menu menu) {
604 application.onCreateGlobalOptionsMenu(this, menu);
607 final MenuItem randomWord = menu.add(getString(R.string.randomWord));
608 randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
609 public boolean onMenuItemClick(final MenuItem menuItem) {
610 final String word = index.sortedIndexEntries.get(random
611 .nextInt(index.sortedIndexEntries.size())).token;
612 setSearchText(word, true);
619 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
620 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
621 public boolean onMenuItemClick(final MenuItem menuItem) {
622 startActivity(DictionaryManagerActivity.getLaunchIntent());
630 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
631 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
632 public boolean onMenuItemClick(final MenuItem menuItem) {
633 final Context context = getListView().getContext();
634 final Dialog dialog = new Dialog(context);
635 dialog.setContentView(R.layout.about_dictionary_dialog);
636 final TextView textView = (TextView) dialog.findViewById(R.id.text);
638 final String name = application.getDictionaryName(dictFile.getName());
639 dialog.setTitle(name);
641 final StringBuilder builder = new StringBuilder();
642 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
643 dictionaryInfo.uncompressedBytes = dictFile.length();
644 if (dictionaryInfo != null) {
645 builder.append(dictionaryInfo.dictInfo).append("\n\n");
646 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
649 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
652 getString(R.string.dictionaryCreationTime,
653 dictionaryInfo.creationMillis)).append("\n");
654 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
655 builder.append("\n");
656 builder.append(getString(R.string.indexName, indexInfo.shortName))
659 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
662 builder.append("\n");
663 builder.append(getString(R.string.sources)).append("\n");
664 for (final EntrySource source : dictionary.sources) {
666 getString(R.string.sourceInfo, source.getName(),
667 source.getNumEntries())).append("\n");
671 // builder.append(getString(R.string.invalidDictionary));
673 textView.setText(builder.toString());
676 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
677 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
678 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
679 dialog.getWindow().setAttributes(layoutParams);
688 // --------------------------------------------------------------------------
689 // Context Menu + clicks
690 // --------------------------------------------------------------------------
693 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
694 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
695 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
697 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
698 wordList.getName()));
699 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
700 public boolean onMenuItemClick(MenuItem item) {
701 onAppendToWordList(row);
706 final MenuItem copy = menu.add(android.R.string.copy);
707 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
708 public boolean onMenuItemClick(MenuItem item) {
714 if (selectedSpannableText != null) {
715 final String selectedText = selectedSpannableText;
716 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
717 selectedSpannableText));
718 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
719 public boolean onMenuItemClick(MenuItem item) {
721 for (int i = 0; i < dictionary.indices.size(); ++i) {
722 final Index index = dictionary.indices.get(i);
723 if (indexPrepFinished) {
724 System.out.println("Doing index lookup: on " + selectedText);
725 final IndexEntry indexEntry = index.findExact(selectedText);
726 if (indexEntry != null) {
727 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
729 if (tokenRow != null && tokenRow.hasMainEntry) {
735 Log.w(LOG, "Skipping findExact on index " + index.shortName);
738 if (indexToUse == -1) {
739 indexToUse = selectedSpannableIndex;
741 final boolean changeIndex = indexIndex != indexToUse;
742 setSearchText(selectedText, !changeIndex); // If we're not
748 changeIndexGetFocusAndResearch(indexToUse);
750 // Give focus back to list view because typing is done.
751 getListView().requestFocus();
760 protected void onListItemClick(ListView l, View v, int row, long id) {
762 if (clickOpensContextMenu && dictRaf != null) {
767 void onAppendToWordList(final RowBase row) {
770 final StringBuilder rawText = new StringBuilder();
771 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
772 rawText.append(index.longName).append("\t");
773 rawText.append(row.getTokenRow(true).getToken()).append("\t");
774 rawText.append(row.getRawText(saveOnlyFirstSubentry));
775 Log.d(LOG, "Writing : " + rawText);
778 wordList.getParentFile().mkdirs();
779 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
780 out.println(rawText.toString());
782 } catch (IOException e) {
783 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
785 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
786 Toast.LENGTH_LONG).show();
792 * Called when user clicks outside of search text, so that they can start
793 * typing again immediately.
795 void defocusSearchText() {
796 // Log.d(LOG, "defocusSearchText");
797 // Request focus so that if we start typing again, it clears the text
799 getListView().requestFocus();
801 // Visual indication that a new keystroke will clear the search text.
802 searchText.selectAll();
805 @SuppressWarnings("deprecation")
806 void onCopy(final RowBase row) {
809 Log.d(LOG, "Copy, row=" + row);
810 final StringBuilder result = new StringBuilder();
811 result.append(row.getRawText(false));
812 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
813 clipboardManager.setText(result.toString());
814 Log.d(LOG, "Copied: " + result);
818 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
819 if (event.getUnicodeChar() != 0) {
820 if (!searchText.hasFocus()) {
821 setSearchText("" + (char) event.getUnicodeChar(), true);
825 if (keyCode == KeyEvent.KEYCODE_BACK) {
826 // Log.d(LOG, "Clearing dictionary prefs.");
827 // Pretend that we just autolaunched so that we won't do it again.
828 // DictionaryManagerActivity.lastAutoLaunchMillis =
829 // System.currentTimeMillis();
831 if (keyCode == KeyEvent.KEYCODE_ENTER) {
832 Log.d(LOG, "Trying to hide soft keyboard.");
833 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
834 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
835 InputMethodManager.HIDE_NOT_ALWAYS);
838 return super.onKeyDown(keyCode, event);
841 private void setSearchText(final String text, final boolean triggerSearch) {
842 if (!triggerSearch) {
843 getListView().requestFocus();
845 searchText.setText(text);
846 searchText.requestFocus();
849 onSearchTextChange(text);
853 private long cursorDelayMillis = 100;
855 private void moveCursorToRight() {
856 if (searchText.getLayout() != null) {
857 cursorDelayMillis = 100;
858 // Surprising, but this can crash when you rotate...
859 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
861 uiHandler.postDelayed(new Runnable() {
866 }, cursorDelayMillis);
867 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
871 // --------------------------------------------------------------------------
873 // --------------------------------------------------------------------------
875 private void searchFinished(final SearchOperation searchOperation) {
876 if (searchOperation.interrupted.get()) {
877 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
880 if (searchOperation != this.currentSearchOperation) {
881 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
885 final Index.IndexEntry searchResult = searchOperation.searchResult;
886 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
888 currentSearchOperation = null;
889 uiHandler.postDelayed(new Runnable() {
892 if (currentSearchOperation == null) {
893 if (searchResult != null) {
897 jumpToRow(searchResult.startRow);
898 } else if (searchOperation.multiWordSearchResult != null) {
899 // Multi-row search....
900 setFiltered(searchOperation);
902 throw new IllegalStateException("This should never happen.");
905 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
912 private final void jumpToRow(final int row) {
914 getListView().setSelected(true);
917 static final Pattern WHITESPACE = Pattern.compile("\\s+");
919 final class SearchOperation implements Runnable {
921 final AtomicBoolean interrupted = new AtomicBoolean(false);
923 final String searchText;
925 List<String> searchTokens; // filled in for multiWord.
929 long searchStartMillis;
931 Index.IndexEntry searchResult;
933 List<RowBase> multiWordSearchResult;
935 boolean done = false;
937 SearchOperation(final String searchText, final Index index) {
938 this.searchText = searchText.trim();
942 public String toString() {
943 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
949 searchStartMillis = System.currentTimeMillis();
950 final String[] searchTokenArray = WHITESPACE.split(searchText);
951 if (searchTokenArray.length == 1) {
952 searchResult = index.findInsertionPoint(searchText, interrupted);
954 searchTokens = Arrays.asList(searchTokenArray);
955 multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
958 "searchText=" + searchText + ", searchDuration="
959 + (System.currentTimeMillis() - searchStartMillis)
960 + ", interrupted=" + interrupted.get());
961 if (!interrupted.get()) {
962 uiHandler.post(new Runnable() {
965 searchFinished(SearchOperation.this);
969 } catch (Exception e) {
970 Log.e(LOG, "Failure during search (can happen during Activity close.");
972 synchronized (this) {
980 // --------------------------------------------------------------------------
982 // --------------------------------------------------------------------------
984 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
985 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
987 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
988 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
990 final class IndexAdapter extends BaseAdapter {
992 private static final float PADDING_DEFAULT_DP = 8;
994 private static final float PADDING_LARGE_DP = 16;
998 final List<RowBase> rows;
1000 final Set<String> toHighlight;
1002 private int mPaddingDefault;
1004 private int mPaddingLarge;
1006 IndexAdapter(final Index index) {
1009 this.toHighlight = null;
1013 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1016 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1020 private void getMetrics() {
1021 // Get the screen's density scale
1022 final float scale = getResources().getDisplayMetrics().density;
1023 // Convert the dps to pixels, based on density scale
1024 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1025 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1029 public int getCount() {
1034 public RowBase getItem(int position) {
1035 return rows.get(position);
1039 public long getItemId(int position) {
1040 return getItem(position).index();
1044 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1045 final TableLayout result;
1046 if (convertView instanceof TableLayout) {
1047 result = (TableLayout) convertView;
1048 result.removeAllViews();
1050 result = new TableLayout(parent.getContext());
1052 final RowBase row = getItem(position);
1053 if (row instanceof PairEntry.Row) {
1054 return getView(position, (PairEntry.Row) row, parent, result);
1055 } else if (row instanceof TokenRow) {
1056 return getView((TokenRow) row, parent, result);
1057 } else if (row instanceof HtmlEntry.Row) {
1058 return getView((HtmlEntry.Row) row, parent, result);
1060 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1064 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1065 final TableLayout result) {
1066 final PairEntry entry = row.getEntry();
1067 final int rowCount = entry.pairs.size();
1069 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1070 layoutParams.weight = 0.5f;
1071 layoutParams.leftMargin = mPaddingLarge;
1073 for (int r = 0; r < rowCount; ++r) {
1074 final TableRow tableRow = new TableRow(result.getContext());
1076 final TextView col1 = new TextView(tableRow.getContext());
1077 final TextView col2 = new TextView(tableRow.getContext());
1079 // Set the columns in the table.
1081 final TextView bullet = new TextView(tableRow.getContext());
1082 bullet.setText(" • ");
1083 tableRow.addView(bullet);
1085 tableRow.addView(col1, layoutParams);
1086 final TextView margin = new TextView(tableRow.getContext());
1087 margin.setText(" ");
1088 tableRow.addView(margin);
1090 final TextView bullet = new TextView(tableRow.getContext());
1091 bullet.setText(" • ");
1092 tableRow.addView(bullet);
1094 tableRow.addView(col2, layoutParams);
1098 // Set what's in the columns.
1100 final Pair pair = entry.pairs.get(r);
1101 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1102 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1104 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1105 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1107 // Bold the token instances in col1.
1108 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1109 .singleton(row.getTokenRow(true).getToken());
1110 final Spannable col1Spannable = (Spannable) col1.getText();
1111 for (final String token : toBold) {
1113 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1114 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1115 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1116 startPos += token.length();
1120 createTokenLinkSpans(col1, col1Spannable, col1Text);
1121 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1123 col1.setTypeface(typeface);
1124 col2.setTypeface(typeface);
1125 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1126 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1127 // col2.setBackgroundResource(theme.otherLangBg);
1129 if (index.swapPairEntries) {
1130 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1131 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1133 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1134 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1137 result.addView(tableRow);
1140 // Because we have a Button inside a ListView row:
1141 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1142 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1143 result.setClickable(true);
1144 result.setFocusable(true);
1145 result.setLongClickable(true);
1146 result.setBackgroundResource(android.R.drawable.menuitem_background);
1147 result.setOnClickListener(new TextView.OnClickListener() {
1149 public void onClick(View v) {
1150 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1157 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1158 final Context context = parent.getContext();
1160 final HtmlEntry htmlEntry = row.getEntry();
1162 // final TableRow tableRow = new TableRow(context);
1163 final LinearLayout tableRow = new LinearLayout(context);
1164 result.addView(tableRow);
1167 final TextView textView = new TextView(context);
1168 textView.setText(htmlEntry.title);
1169 textView.setLayoutParams(new LinearLayout.LayoutParams(0,
1170 ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
1171 tableRow.addView(textView);
1174 final Button button = new Button(context);
1175 button.setText("open");
1176 button.setLayoutParams(new LinearLayout.LayoutParams(
1177 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.0f));
1178 tableRow.addView(button);
1180 button.setOnClickListener(new OnClickListener() {
1182 public void onClick(View v) {
1183 startActivity(HtmlDisplayActivity.getHtmlIntent(String.format(
1184 "<html><head></head><body>%s</body></html>", htmlEntry.html)));
1191 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1192 final Context context = parent.getContext();
1193 final TextView textView = new TextView(context);
1194 textView.setText(row.getToken());
1196 // textView.setTextColor(android.R.color.secondary_text_light);
1197 textView.setTextAppearance(context, theme.tokenRowFg);
1198 textView.setTypeface(typeface);
1199 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
1201 final TableRow tableRow = new TableRow(result.getContext());
1202 tableRow.addView(textView);
1203 tableRow.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg
1204 : theme.tokenRowOtherBg);
1205 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1206 result.addView(tableRow);
1212 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1214 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1215 final String text) {
1216 // Saw from the source code that LinkMovementMethod sets the selection!
1217 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1218 textView.setMovementMethod(LinkMovementMethod.getInstance());
1219 final Matcher matcher = CHAR_DASH.matcher(text);
1220 while (matcher.find()) {
1221 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(),
1222 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1226 String selectedSpannableText = null;
1228 int selectedSpannableIndex = -1;
1231 public boolean onTouchEvent(MotionEvent event) {
1232 selectedSpannableText = null;
1233 selectedSpannableIndex = -1;
1234 return super.onTouchEvent(event);
1237 private class TextViewLongClickListener implements OnLongClickListener {
1240 private TextViewLongClickListener(final int index) {
1245 public boolean onLongClick(final View v) {
1246 final TextView textView = (TextView) v;
1247 final int start = textView.getSelectionStart();
1248 final int end = textView.getSelectionEnd();
1249 if (start >= 0 && end >= 0) {
1250 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1251 selectedSpannableIndex = index;
1257 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1260 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1263 // --------------------------------------------------------------------------
1265 // --------------------------------------------------------------------------
1267 void onSearchTextChange(final String text) {
1268 if ("thadolina".equals(text)) {
1269 final Dialog dialog = new Dialog(getListView().getContext());
1270 dialog.setContentView(R.layout.thadolina_dialog);
1271 dialog.setTitle("Ti amo, amore mio!");
1272 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1273 imageView.setOnClickListener(new OnClickListener() {
1275 public void onClick(View v) {
1276 final Intent intent = new Intent(Intent.ACTION_VIEW);
1277 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1278 startActivity(intent);
1283 if (dictRaf == null) {
1284 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1287 if (!searchText.isFocused()) {
1288 Log.d(LOG, "searchText changed without focus, doing nothing.");
1291 Log.d(LOG, "onSearchTextChange: " + text);
1292 if (currentSearchOperation != null) {
1293 Log.d(LOG, "Interrupting currentSearchOperation.");
1294 currentSearchOperation.interrupted.set(true);
1296 currentSearchOperation = new SearchOperation(text, index);
1297 searchExecutor.execute(currentSearchOperation);
1300 private class SearchTextWatcher implements TextWatcher {
1301 public void afterTextChanged(final Editable searchTextEditable) {
1302 if (searchText.hasFocus()) {
1303 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
1304 // If they were typing to cause the change, update the UI.
1305 onSearchTextChange(searchText.getText().toString());
1309 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1312 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1316 // --------------------------------------------------------------------------
1317 // Filtered results.
1318 // --------------------------------------------------------------------------
1320 boolean isFiltered() {
1321 return rowsToShow != null;
1324 void setFiltered(final SearchOperation searchOperation) {
1325 ((Button) findViewById(R.id.UpButton)).setEnabled(false);
1326 ((Button) findViewById(R.id.DownButton)).setEnabled(false);
1327 rowsToShow = searchOperation.multiWordSearchResult;
1328 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1331 void clearFiltered() {
1332 ((Button) findViewById(R.id.UpButton)).setEnabled(true);
1333 ((Button) findViewById(R.id.DownButton)).setEnabled(true);
1334 setListAdapter(new IndexAdapter(index));