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);
296 searchText.requestFocus();
297 searchText.addTextChangedListener(searchTextWatcher);
299 // Set the search text from the intent, then the saved state.
300 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
301 if (savedInstanceState != null) {
302 text = savedInstanceState.getString(C.SEARCH_TOKEN);
307 setSearchText(text, true);
308 Log.d(LOG, "Trying to restore searchText=" + text);
310 final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
311 clearSearchTextButton.setOnClickListener(new OnClickListener() {
312 public void onClick(View v) {
313 onClearSearchTextButton();
316 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
317 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
320 langButton = (Button) findViewById(R.id.LangButton);
321 langButton.setOnClickListener(new OnClickListener() {
322 public void onClick(View v) {
326 langButton.setOnLongClickListener(new OnLongClickListener() {
328 public boolean onLongClick(View v) {
329 onLanguageButtonLongClick(v.getContext());
335 final View upButton = findViewById(R.id.UpButton);
336 upButton.setOnClickListener(new OnClickListener() {
337 public void onClick(View v) {
338 onUpDownButton(true);
341 final View downButton = findViewById(R.id.DownButton);
342 downButton.setOnClickListener(new OnClickListener() {
343 public void onClick(View v) {
344 onUpDownButton(false);
348 getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
350 public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
352 if (!searchText.isFocused()) {
354 final RowBase row = (RowBase) getListAdapter().getItem(position);
355 Log.d(LOG, "onItemSelected: " + row.index());
356 final TokenRow tokenRow = row.getTokenRow(true);
357 searchText.setText(tokenRow.getToken());
363 public void onNothingSelected(AdapterView<?> arg0) {
368 registerForContextMenu(getListView());
371 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
372 getString(R.string.wordListFileDefault)));
373 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
375 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
377 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
379 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
381 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
383 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
387 protected void onResume() {
389 if (PreferenceActivity.prefsMightHaveChanged) {
390 PreferenceActivity.prefsMightHaveChanged = false;
392 startActivity(getIntent());
394 if (initialSearchText != null) {
395 setSearchText(initialSearchText, true);
400 protected void onPause() {
404 private static void setDictionaryPrefs(final Context context, final File dictFile,
405 final int indexIndex, final String searchToken) {
406 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
408 prefs.putString(C.DICT_FILE, dictFile.getPath());
409 prefs.putInt(C.INDEX_INDEX, indexIndex);
410 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
415 protected void onDestroy() {
417 if (dictRaf == null) {
421 final SearchOperation searchOperation = currentSearchOperation;
422 currentSearchOperation = null;
424 // Before we close the RAF, we have to wind the current search down.
425 if (searchOperation != null) {
426 Log.d(LOG, "Interrupting search to shut down.");
427 currentSearchOperation = null;
428 searchOperation.interrupted.set(true);
432 Log.d(LOG, "Closing RAF.");
434 } catch (IOException e) {
435 Log.e(LOG, "Failed to close dictionary", e);
440 // --------------------------------------------------------------------------
442 // --------------------------------------------------------------------------
444 private void onClearSearchTextButton() {
445 setSearchText("", true);
446 Log.d(LOG, "Trying to show soft keyboard.");
447 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
448 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
451 void updateLangButton() {
452 // final LanguageResources languageResources =
453 // Language.isoCodeToResources.get(index.shortName);
454 // if (languageResources != null && languageResources.flagId != 0) {
455 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
456 // languageResources.flagId, 0);
458 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
459 langButton.setText(index.shortName);
463 void onLanguageButton() {
464 if (currentSearchOperation != null) {
465 currentSearchOperation.interrupted.set(true);
466 currentSearchOperation = null;
468 changeIndexGetFocusAndResearch((indexIndex + 1) % dictionary.indices.size());
471 void onLanguageButtonLongClick(final Context context) {
472 final Dialog dialog = new Dialog(context);
473 dialog.setContentView(R.layout.select_dictionary_dialog);
474 dialog.setTitle(R.string.selectDictionary);
476 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
479 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
481 // final LinearLayout.LayoutParams layoutParams = new
482 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
483 // ViewGroup.LayoutParams.WRAP_CONTENT);
484 // layoutParams.width = 0;
485 // layoutParams.weight = 1.0f;
487 final Button button = new Button(listView.getContext());
488 final String name = getString(R.string.dictionaryManager);
489 button.setText(name);
490 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
491 DictionaryManagerActivity.getLaunchIntent()) {
493 protected void onGo() {
495 DictionaryActivity.this.finish();
498 button.setOnClickListener(intentLauncher);
499 // button.setLayoutParams(layoutParams);
500 listView.addHeaderView(button);
501 // listView.setHeaderDividersEnabled(true);
503 listView.setAdapter(new BaseAdapter() {
505 public View getView(int position, View convertView, ViewGroup parent) {
506 final LinearLayout result = new LinearLayout(parent.getContext());
508 final DictionaryInfo dictionaryInfo = getItem(position);
509 final Button button = new Button(parent.getContext());
510 final String name = application
511 .getDictionaryName(dictionaryInfo.uncompressedFilename);
512 button.setText(name);
513 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
514 getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
515 0, searchText.getText().toString())) {
517 protected void onGo() {
519 DictionaryActivity.this.finish();
522 button.setOnClickListener(intentLauncher);
523 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
524 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
525 layoutParams.width = 0;
526 layoutParams.weight = 1.0f;
527 button.setLayoutParams(layoutParams);
528 result.addView(button);
533 public long getItemId(int position) {
538 public DictionaryInfo getItem(int position) {
539 return installedDicts.get(position);
543 public int getCount() {
544 return installedDicts.size();
551 private void changeIndexGetFocusAndResearch(final int newIndex) {
552 indexIndex = newIndex;
553 index = dictionary.indices.get(indexIndex);
554 indexAdapter = new IndexAdapter(index);
555 Log.d(LOG, "changingIndex, newLang=" + index.longName);
556 setListAdapter(indexAdapter);
558 searchText.requestFocus(); // Otherwise, nothing may happen.
559 onSearchTextChange(searchText.getText().toString());
560 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
563 void onUpDownButton(final boolean up) {
567 final int firstVisibleRow = getListView().getFirstVisiblePosition();
568 final RowBase row = index.rows.get(firstVisibleRow);
569 final TokenRow tokenRow = row.getTokenRow(true);
570 final int destIndexEntry;
572 if (row != tokenRow) {
573 destIndexEntry = tokenRow.referenceIndex;
575 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
579 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
581 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
582 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
583 searchText.removeTextChangedListener(searchTextWatcher);
584 searchText.setText(dest.token);
585 if (searchText.getLayout() != null) {
586 // Surprising, but this can otherwise crash sometimes...
587 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
589 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
590 searchText.addTextChangedListener(searchTextWatcher);
593 // --------------------------------------------------------------------------
595 // --------------------------------------------------------------------------
597 final Random random = new Random();
600 public boolean onCreateOptionsMenu(final Menu menu) {
601 application.onCreateGlobalOptionsMenu(this, menu);
604 final MenuItem randomWord = menu.add(getString(R.string.randomWord));
605 randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
606 public boolean onMenuItemClick(final MenuItem menuItem) {
607 final String word = index.sortedIndexEntries.get(random
608 .nextInt(index.sortedIndexEntries.size())).token;
609 setSearchText(word, true);
616 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
617 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
618 public boolean onMenuItemClick(final MenuItem menuItem) {
619 startActivity(DictionaryManagerActivity.getLaunchIntent());
627 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
628 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
629 public boolean onMenuItemClick(final MenuItem menuItem) {
630 final Context context = getListView().getContext();
631 final Dialog dialog = new Dialog(context);
632 dialog.setContentView(R.layout.about_dictionary_dialog);
633 final TextView textView = (TextView) dialog.findViewById(R.id.text);
635 final String name = application.getDictionaryName(dictFile.getName());
636 dialog.setTitle(name);
638 final StringBuilder builder = new StringBuilder();
639 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
640 dictionaryInfo.uncompressedBytes = dictFile.length();
641 if (dictionaryInfo != null) {
642 builder.append(dictionaryInfo.dictInfo).append("\n\n");
643 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
646 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
649 getString(R.string.dictionaryCreationTime,
650 dictionaryInfo.creationMillis)).append("\n");
651 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
652 builder.append("\n");
653 builder.append(getString(R.string.indexName, indexInfo.shortName))
656 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
659 builder.append("\n");
660 builder.append(getString(R.string.sources)).append("\n");
661 for (final EntrySource source : dictionary.sources) {
663 getString(R.string.sourceInfo, source.getName(),
664 source.getNumEntries())).append("\n");
668 // builder.append(getString(R.string.invalidDictionary));
670 textView.setText(builder.toString());
673 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
674 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
675 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
676 dialog.getWindow().setAttributes(layoutParams);
685 // --------------------------------------------------------------------------
686 // Context Menu + clicks
687 // --------------------------------------------------------------------------
690 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
691 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
692 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
694 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
695 wordList.getName()));
696 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
697 public boolean onMenuItemClick(MenuItem item) {
698 onAppendToWordList(row);
703 final MenuItem copy = menu.add(android.R.string.copy);
704 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
705 public boolean onMenuItemClick(MenuItem item) {
711 if (selectedSpannableText != null) {
712 final String selectedText = selectedSpannableText;
713 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
714 selectedSpannableText));
715 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
716 public boolean onMenuItemClick(MenuItem item) {
718 for (int i = 0; i < dictionary.indices.size(); ++i) {
719 final Index index = dictionary.indices.get(i);
720 if (indexPrepFinished) {
721 System.out.println("Doing index lookup: on " + selectedText);
722 final IndexEntry indexEntry = index.findExact(selectedText);
723 if (indexEntry != null) {
724 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
726 if (tokenRow != null && tokenRow.hasMainEntry) {
732 Log.w(LOG, "Skipping findExact on index " + index.shortName);
735 if (indexToUse == -1) {
736 indexToUse = selectedSpannableIndex;
738 final boolean changeIndex = indexIndex != indexToUse;
739 setSearchText(selectedText, !changeIndex); // If we're not
745 changeIndexGetFocusAndResearch(indexToUse);
747 // Give focus back to list view because typing is done.
748 getListView().requestFocus();
757 protected void onListItemClick(ListView l, View v, int row, long id) {
759 if (clickOpensContextMenu && dictRaf != null) {
764 void onAppendToWordList(final RowBase row) {
767 final StringBuilder rawText = new StringBuilder();
768 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
769 rawText.append(index.longName).append("\t");
770 rawText.append(row.getTokenRow(true).getToken()).append("\t");
771 rawText.append(row.getRawText(saveOnlyFirstSubentry));
772 Log.d(LOG, "Writing : " + rawText);
775 wordList.getParentFile().mkdirs();
776 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
777 out.println(rawText.toString());
779 } catch (IOException e) {
780 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
782 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
783 Toast.LENGTH_LONG).show();
789 * Called when user clicks outside of search text, so that they can start
790 * typing again immediately.
792 void defocusSearchText() {
793 // Log.d(LOG, "defocusSearchText");
794 // Request focus so that if we start typing again, it clears the text
796 getListView().requestFocus();
798 // Visual indication that a new keystroke will clear the search text.
799 searchText.selectAll();
802 @SuppressWarnings("deprecation")
803 void onCopy(final RowBase row) {
806 Log.d(LOG, "Copy, row=" + row);
807 final StringBuilder result = new StringBuilder();
808 result.append(row.getRawText(false));
809 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
810 clipboardManager.setText(result.toString());
811 Log.d(LOG, "Copied: " + result);
815 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
816 if (event.getUnicodeChar() != 0) {
817 if (!searchText.hasFocus()) {
818 setSearchText("" + (char) event.getUnicodeChar(), true);
822 if (keyCode == KeyEvent.KEYCODE_BACK) {
823 // Log.d(LOG, "Clearing dictionary prefs.");
824 // Pretend that we just autolaunched so that we won't do it again.
825 // DictionaryManagerActivity.lastAutoLaunchMillis =
826 // System.currentTimeMillis();
828 if (keyCode == KeyEvent.KEYCODE_ENTER) {
829 Log.d(LOG, "Trying to hide soft keyboard.");
830 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
831 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
832 InputMethodManager.HIDE_NOT_ALWAYS);
835 return super.onKeyDown(keyCode, event);
838 private void setSearchText(final String text, final boolean triggerSearch) {
839 if (!triggerSearch) {
840 getListView().requestFocus();
842 searchText.setText(text);
843 searchText.requestFocus();
846 onSearchTextChange(text);
850 private long cursorDelayMillis = 100;
852 private void moveCursorToRight() {
853 if (searchText.getLayout() != null) {
854 cursorDelayMillis = 100;
855 // Surprising, but this can crash when you rotate...
856 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
858 uiHandler.postDelayed(new Runnable() {
863 }, cursorDelayMillis);
864 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
868 // --------------------------------------------------------------------------
870 // --------------------------------------------------------------------------
872 private void searchFinished(final SearchOperation searchOperation) {
873 if (searchOperation.interrupted.get()) {
874 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
877 if (searchOperation != this.currentSearchOperation) {
878 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
882 final Index.IndexEntry searchResult = searchOperation.searchResult;
883 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
885 currentSearchOperation = null;
886 uiHandler.postDelayed(new Runnable() {
889 if (currentSearchOperation == null) {
890 if (searchResult != null) {
894 jumpToRow(searchResult.startRow);
895 } else if (searchOperation.multiWordSearchResult != null) {
896 // Multi-row search....
897 setFiltered(searchOperation);
899 throw new IllegalStateException("This should never happen.");
902 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
909 private final void jumpToRow(final int row) {
911 getListView().setSelected(true);
914 static final Pattern WHITESPACE = Pattern.compile("\\s+");
916 final class SearchOperation implements Runnable {
918 final AtomicBoolean interrupted = new AtomicBoolean(false);
920 final String searchText;
922 List<String> searchTokens; // filled in for multiWord.
926 long searchStartMillis;
928 Index.IndexEntry searchResult;
930 List<RowBase> multiWordSearchResult;
932 boolean done = false;
934 SearchOperation(final String searchText, final Index index) {
935 this.searchText = searchText.trim();
939 public String toString() {
940 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
946 searchStartMillis = System.currentTimeMillis();
947 final String[] searchTokenArray = WHITESPACE.split(searchText);
948 if (searchTokenArray.length == 1) {
949 searchResult = index.findInsertionPoint(searchText, interrupted);
951 searchTokens = Arrays.asList(searchTokenArray);
952 multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
955 "searchText=" + searchText + ", searchDuration="
956 + (System.currentTimeMillis() - searchStartMillis)
957 + ", interrupted=" + interrupted.get());
958 if (!interrupted.get()) {
959 uiHandler.post(new Runnable() {
962 searchFinished(SearchOperation.this);
966 } catch (Exception e) {
967 Log.e(LOG, "Failure during search (can happen during Activity close.");
969 synchronized (this) {
977 // --------------------------------------------------------------------------
979 // --------------------------------------------------------------------------
981 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
982 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
984 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
985 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
987 final class IndexAdapter extends BaseAdapter {
989 private static final float PADDING_DEFAULT_DP = 8;
991 private static final float PADDING_LARGE_DP = 16;
995 final List<RowBase> rows;
997 final Set<String> toHighlight;
999 private int mPaddingDefault;
1001 private int mPaddingLarge;
1003 IndexAdapter(final Index index) {
1006 this.toHighlight = null;
1010 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1013 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1017 private void getMetrics() {
1018 // Get the screen's density scale
1019 final float scale = getResources().getDisplayMetrics().density;
1020 // Convert the dps to pixels, based on density scale
1021 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1022 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1026 public int getCount() {
1031 public RowBase getItem(int position) {
1032 return rows.get(position);
1036 public long getItemId(int position) {
1037 return getItem(position).index();
1041 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1042 final TableLayout result;
1043 if (convertView instanceof TableLayout) {
1044 result = (TableLayout) convertView;
1045 result.removeAllViews();
1047 result = new TableLayout(parent.getContext());
1049 final RowBase row = getItem(position);
1050 if (row instanceof PairEntry.Row) {
1051 return getView(position, (PairEntry.Row) row, parent, result);
1052 } else if (row instanceof TokenRow) {
1053 return getView((TokenRow) row, parent, result);
1054 } else if (row instanceof HtmlEntry.Row) {
1055 return getView((HtmlEntry.Row) row, parent, result);
1057 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1061 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1062 final TableLayout result) {
1063 final PairEntry entry = row.getEntry();
1064 final int rowCount = entry.pairs.size();
1066 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1067 layoutParams.weight = 0.5f;
1068 layoutParams.leftMargin = mPaddingLarge;
1070 for (int r = 0; r < rowCount; ++r) {
1071 final TableRow tableRow = new TableRow(result.getContext());
1073 final TextView col1 = new TextView(tableRow.getContext());
1074 final TextView col2 = new TextView(tableRow.getContext());
1076 // Set the columns in the table.
1078 final TextView bullet = new TextView(tableRow.getContext());
1079 bullet.setText(" • ");
1080 tableRow.addView(bullet);
1082 tableRow.addView(col1, layoutParams);
1083 final TextView margin = new TextView(tableRow.getContext());
1084 margin.setText(" ");
1085 tableRow.addView(margin);
1087 final TextView bullet = new TextView(tableRow.getContext());
1088 bullet.setText(" • ");
1089 tableRow.addView(bullet);
1091 tableRow.addView(col2, layoutParams);
1095 // Set what's in the columns.
1097 final Pair pair = entry.pairs.get(r);
1098 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1099 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1101 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1102 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1104 // Bold the token instances in col1.
1105 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1106 .singleton(row.getTokenRow(true).getToken());
1107 final Spannable col1Spannable = (Spannable) col1.getText();
1108 for (final String token : toBold) {
1110 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1111 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1112 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1113 startPos += token.length();
1117 createTokenLinkSpans(col1, col1Spannable, col1Text);
1118 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1120 col1.setTypeface(typeface);
1121 col2.setTypeface(typeface);
1122 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1123 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1124 // col2.setBackgroundResource(theme.otherLangBg);
1126 if (index.swapPairEntries) {
1127 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1128 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1130 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1131 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1134 result.addView(tableRow);
1137 // Because we have a Button inside a ListView row:
1138 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1139 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1140 result.setClickable(true);
1141 result.setFocusable(true);
1142 result.setLongClickable(true);
1143 result.setBackgroundResource(android.R.drawable.menuitem_background);
1144 result.setOnClickListener(new TextView.OnClickListener() {
1146 public void onClick(View v) {
1147 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1154 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1155 final Context context = parent.getContext();
1157 final HtmlEntry htmlEntry = row.getEntry();
1159 // final TableRow tableRow = new TableRow(context);
1160 final LinearLayout tableRow = new LinearLayout(context);
1161 result.addView(tableRow);
1164 final TextView textView = new TextView(context);
1165 textView.setText(htmlEntry.title);
1166 textView.setLayoutParams(new LinearLayout.LayoutParams(0,
1167 ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
1168 tableRow.addView(textView);
1171 final Button button = new Button(context);
1172 button.setText("open");
1173 button.setLayoutParams(new LinearLayout.LayoutParams(
1174 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.0f));
1175 tableRow.addView(button);
1177 button.setOnClickListener(new OnClickListener() {
1179 public void onClick(View v) {
1180 startActivity(HtmlDisplayActivity.getHtmlIntent(String.format(
1181 "<html><head></head><body>%s</body></html>", htmlEntry.html)));
1188 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1189 final Context context = parent.getContext();
1190 final TextView textView = new TextView(context);
1191 textView.setText(row.getToken());
1193 // textView.setTextColor(android.R.color.secondary_text_light);
1194 textView.setTextAppearance(context, theme.tokenRowFg);
1195 textView.setTypeface(typeface);
1196 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
1198 final TableRow tableRow = new TableRow(result.getContext());
1199 tableRow.addView(textView);
1200 tableRow.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg
1201 : theme.tokenRowOtherBg);
1202 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1203 result.addView(tableRow);
1209 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1211 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1212 final String text) {
1213 // Saw from the source code that LinkMovementMethod sets the selection!
1214 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1215 textView.setMovementMethod(LinkMovementMethod.getInstance());
1216 final Matcher matcher = CHAR_DASH.matcher(text);
1217 while (matcher.find()) {
1218 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(),
1219 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1223 String selectedSpannableText = null;
1225 int selectedSpannableIndex = -1;
1228 public boolean onTouchEvent(MotionEvent event) {
1229 selectedSpannableText = null;
1230 selectedSpannableIndex = -1;
1231 return super.onTouchEvent(event);
1234 private class TextViewLongClickListener implements OnLongClickListener {
1237 private TextViewLongClickListener(final int index) {
1242 public boolean onLongClick(final View v) {
1243 final TextView textView = (TextView) v;
1244 final int start = textView.getSelectionStart();
1245 final int end = textView.getSelectionEnd();
1246 if (start >= 0 && end >= 0) {
1247 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1248 selectedSpannableIndex = index;
1254 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1257 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1260 // --------------------------------------------------------------------------
1262 // --------------------------------------------------------------------------
1264 void onSearchTextChange(final String text) {
1265 if ("thadolina".equals(text)) {
1266 final Dialog dialog = new Dialog(getListView().getContext());
1267 dialog.setContentView(R.layout.thadolina_dialog);
1268 dialog.setTitle("Ti amo, amore mio!");
1269 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1270 imageView.setOnClickListener(new OnClickListener() {
1272 public void onClick(View v) {
1273 final Intent intent = new Intent(Intent.ACTION_VIEW);
1274 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1275 startActivity(intent);
1280 if (dictRaf == null) {
1281 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1284 if (!searchText.isFocused()) {
1285 Log.d(LOG, "searchText changed without focus, doing nothing.");
1288 Log.d(LOG, "onSearchTextChange: " + text);
1289 if (currentSearchOperation != null) {
1290 Log.d(LOG, "Interrupting currentSearchOperation.");
1291 currentSearchOperation.interrupted.set(true);
1293 currentSearchOperation = new SearchOperation(text, index);
1294 searchExecutor.execute(currentSearchOperation);
1297 private class SearchTextWatcher implements TextWatcher {
1298 public void afterTextChanged(final Editable searchTextEditable) {
1299 if (searchText.hasFocus()) {
1300 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
1301 // If they were typing to cause the change, update the UI.
1302 onSearchTextChange(searchText.getText().toString());
1306 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1309 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1313 // --------------------------------------------------------------------------
1314 // Filtered results.
1315 // --------------------------------------------------------------------------
1317 boolean isFiltered() {
1318 return rowsToShow != null;
1321 void setFiltered(final SearchOperation searchOperation) {
1322 ((Button) findViewById(R.id.UpButton)).setEnabled(false);
1323 ((Button) findViewById(R.id.DownButton)).setEnabled(false);
1324 rowsToShow = searchOperation.multiWordSearchResult;
1325 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1328 void clearFiltered() {
1329 ((Button) findViewById(R.id.UpButton)).setEnabled(true);
1330 ((Button) findViewById(R.id.DownButton)).setEnabled(true);
1331 setListAdapter(new IndexAdapter(index));