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 android.app.Dialog;
18 import android.app.ListActivity;
19 import android.content.Context;
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.graphics.Typeface;
23 import android.net.Uri;
24 import android.os.Bundle;
25 import android.os.Handler;
26 import android.preference.PreferenceManager;
27 import android.text.ClipboardManager;
28 import android.text.Editable;
29 import android.text.Selection;
30 import android.text.Spannable;
31 import android.text.TextWatcher;
32 import android.text.method.LinkMovementMethod;
33 import android.text.style.StyleSpan;
34 import android.util.Log;
35 import android.util.TypedValue;
36 import android.view.ContextMenu;
37 import android.view.ContextMenu.ContextMenuInfo;
38 import android.view.KeyEvent;
39 import android.view.Menu;
40 import android.view.MenuItem;
41 import android.view.MenuItem.OnMenuItemClickListener;
42 import android.view.MotionEvent;
43 import android.view.View;
44 import android.view.View.OnClickListener;
45 import android.view.View.OnLongClickListener;
46 import android.view.ViewGroup;
47 import android.view.WindowManager;
48 import android.view.inputmethod.InputMethodManager;
49 import android.widget.AdapterView;
50 import android.widget.AdapterView.AdapterContextMenuInfo;
51 import android.widget.LinearLayout.LayoutParams;
52 import android.widget.BaseAdapter;
53 import android.widget.Button;
54 import android.widget.EditText;
55 import android.widget.ImageButton;
56 import android.widget.ImageView;
57 import android.widget.LinearLayout;
58 import android.widget.ListAdapter;
59 import android.widget.ListView;
60 import android.widget.TableLayout;
61 import android.widget.TableRow;
62 import android.widget.TextView;
63 import android.widget.Toast;
65 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
66 import com.hughes.android.dictionary.engine.Dictionary;
67 import com.hughes.android.dictionary.engine.EntrySource;
68 import com.hughes.android.dictionary.engine.HtmlEntry;
69 import com.hughes.android.dictionary.engine.Index;
70 import com.hughes.android.dictionary.engine.Index.IndexEntry;
71 import com.hughes.android.dictionary.engine.PairEntry;
72 import com.hughes.android.dictionary.engine.PairEntry.Pair;
73 import com.hughes.android.dictionary.engine.RowBase;
74 import com.hughes.android.dictionary.engine.TokenRow;
75 import com.hughes.android.dictionary.engine.TransliteratorManager;
76 import com.hughes.android.util.IntentLauncher;
77 import com.hughes.android.util.NonLinkClickableSpan;
80 import java.io.FileWriter;
81 import java.io.IOException;
82 import java.io.PrintWriter;
83 import java.io.RandomAccessFile;
84 import java.text.SimpleDateFormat;
85 import java.util.Arrays;
86 import java.util.Collections;
87 import java.util.Date;
88 import java.util.LinkedHashSet;
89 import java.util.List;
90 import java.util.Random;
92 import java.util.concurrent.Executor;
93 import java.util.concurrent.Executors;
94 import java.util.concurrent.ThreadFactory;
95 import java.util.concurrent.atomic.AtomicBoolean;
96 import java.util.regex.Matcher;
97 import java.util.regex.Pattern;
99 public class DictionaryActivity extends ListActivity {
101 static final String LOG = "QuickDic";
103 private String initialSearchText;
105 DictionaryApplication application;
107 File dictFile = null;
109 RandomAccessFile dictRaf = null;
111 Dictionary dictionary = null;
117 List<RowBase> rowsToShow = null; // if not null, just show these rows.
120 final Handler uiHandler = new Handler();
122 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
124 public Thread newThread(Runnable r) {
125 return new Thread(r, "searchExecutor");
129 private SearchOperation currentSearchOperation = null;
131 C.Theme theme = C.Theme.LIGHT;
142 private File wordList = null;
144 private boolean saveOnlyFirstSubentry = false;
146 private boolean clickOpensContextMenu = false;
148 // Visible for testing.
149 ListAdapter indexAdapter = null;
151 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
154 * For some languages, loading the transliterators used in this search takes
155 * a long time, so we fire it up on a different thread, and don't invoke it
156 * from the main thread until it's already finished once.
158 private volatile boolean indexPrepFinished = false;
160 public DictionaryActivity() {
163 public static Intent getLaunchIntent(final File dictFile, final int indexIndex,
164 final String searchToken) {
165 final Intent intent = new Intent();
166 intent.setClassName(DictionaryActivity.class.getPackage().getName(),
167 DictionaryActivity.class.getName());
168 intent.putExtra(C.DICT_FILE, dictFile.getPath());
169 intent.putExtra(C.INDEX_INDEX, indexIndex);
170 intent.putExtra(C.SEARCH_TOKEN, searchToken);
175 protected void onSaveInstanceState(final Bundle outState) {
176 super.onSaveInstanceState(outState);
177 Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
178 outState.putInt(C.INDEX_INDEX, indexIndex);
179 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
183 protected void onRestoreInstanceState(final Bundle outState) {
184 super.onRestoreInstanceState(outState);
185 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
190 public void onCreate(Bundle savedInstanceState) {
191 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
192 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if
195 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
197 Log.d(LOG, "onCreate:" + this);
198 super.onCreate(savedInstanceState);
200 application = (DictionaryApplication) getApplication();
201 theme = application.getSelectedTheme();
203 final Intent intent = getIntent();
204 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
207 final String name = application.getDictionaryName(dictFile.getName());
208 this.setTitle("QuickDic: " + name);
209 dictRaf = new RandomAccessFile(dictFile, "r");
210 dictionary = new Dictionary(dictRaf);
211 } catch (Exception e) {
212 Log.e(LOG, "Unable to load dictionary.", e);
213 if (dictRaf != null) {
216 } catch (IOException e1) {
217 Log.e(LOG, "Unable to close dictRaf.", e1);
221 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
222 Toast.LENGTH_LONG).show();
223 startActivity(DictionaryManagerActivity.getLaunchIntent());
227 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
228 if (savedInstanceState != null) {
229 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
231 indexIndex %= dictionary.indices.size();
232 Log.d(LOG, "Loading index " + indexIndex);
233 index = dictionary.indices.get(indexIndex);
234 setListAdapter(new IndexAdapter(index));
236 // Pre-load the collators.
237 new Thread(new Runnable() {
239 final long startMillis = System.currentTimeMillis();
241 TransliteratorManager.init(new TransliteratorManager.Callback() {
243 public void onTransliteratorReady() {
244 uiHandler.post(new Runnable() {
247 onSearchTextChange(searchText.getText().toString());
253 for (final Index index : dictionary.indices) {
254 final String searchToken = index.sortedIndexEntries.get(0).token;
255 final IndexEntry entry = index.findExact(searchToken);
256 if (!searchToken.equals(entry.token)) {
257 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
260 indexPrepFinished = true;
261 } catch (Exception e) {
263 "Exception while prepping. This can happen if dictionary is closed while search is happening.");
265 Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
269 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
270 if ("SYSTEM".equals(fontName)) {
271 typeface = Typeface.DEFAULT;
274 typeface = Typeface.createFromAsset(getAssets(), fontName);
275 } catch (Exception e) {
276 Log.w(LOG, "Exception trying to use typeface, using default.", e);
277 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
278 Toast.LENGTH_LONG).show();
281 // if (!"SYSTEM".equals(fontName)) {
282 // throw new RuntimeException("Test force using system font: " +
285 if (typeface == null) {
286 Log.w(LOG, "Unable to create typeface, using default.");
287 typeface = Typeface.DEFAULT;
289 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
291 fontSizeSp = Integer.parseInt(fontSize.trim());
292 } catch (NumberFormatException e) {
296 setContentView(R.layout.dictionary_activity);
297 searchText = (EditText) findViewById(R.id.SearchText);
298 searchText.requestFocus();
299 searchText.addTextChangedListener(searchTextWatcher);
301 // Set the search text from the intent, then the saved state.
302 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
303 if (savedInstanceState != null) {
304 text = savedInstanceState.getString(C.SEARCH_TOKEN);
309 setSearchText(text, true);
310 Log.d(LOG, "Trying to restore searchText=" + text);
312 final View clearSearchTextButton = findViewById(R.id.ClearSearchTextButton);
313 clearSearchTextButton.setOnClickListener(new OnClickListener() {
314 public void onClick(View v) {
315 onClearSearchTextButton();
318 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
319 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
322 langButton = (Button) findViewById(R.id.LangButton);
323 langButton.setOnClickListener(new OnClickListener() {
324 public void onClick(View v) {
328 langButton.setOnLongClickListener(new OnLongClickListener() {
330 public boolean onLongClick(View v) {
331 onLanguageButtonLongClick(v.getContext());
337 final View upButton = findViewById(R.id.UpButton);
338 upButton.setOnClickListener(new OnClickListener() {
339 public void onClick(View v) {
340 onUpDownButton(true);
343 final View downButton = findViewById(R.id.DownButton);
344 downButton.setOnClickListener(new OnClickListener() {
345 public void onClick(View v) {
346 onUpDownButton(false);
350 getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
352 public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
354 if (!searchText.isFocused()) {
356 final RowBase row = (RowBase) getListAdapter().getItem(position);
357 Log.d(LOG, "onItemSelected: " + row.index());
358 final TokenRow tokenRow = row.getTokenRow(true);
359 searchText.setText(tokenRow.getToken());
365 public void onNothingSelected(AdapterView<?> arg0) {
370 registerForContextMenu(getListView());
373 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
374 getString(R.string.wordListFileDefault)));
375 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
377 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
379 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
381 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
383 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
385 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
389 protected void onResume() {
391 if (PreferenceActivity.prefsMightHaveChanged) {
392 PreferenceActivity.prefsMightHaveChanged = false;
394 startActivity(getIntent());
396 if (initialSearchText != null) {
397 setSearchText(initialSearchText, true);
402 protected void onPause() {
406 private static void setDictionaryPrefs(final Context context, final File dictFile,
407 final int indexIndex, final String searchToken) {
408 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
410 prefs.putString(C.DICT_FILE, dictFile.getPath());
411 prefs.putInt(C.INDEX_INDEX, indexIndex);
412 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
417 protected void onDestroy() {
419 if (dictRaf == null) {
423 final SearchOperation searchOperation = currentSearchOperation;
424 currentSearchOperation = null;
426 // Before we close the RAF, we have to wind the current search down.
427 if (searchOperation != null) {
428 Log.d(LOG, "Interrupting search to shut down.");
429 currentSearchOperation = null;
430 searchOperation.interrupted.set(true);
434 Log.d(LOG, "Closing RAF.");
436 } catch (IOException e) {
437 Log.e(LOG, "Failed to close dictionary", e);
442 // --------------------------------------------------------------------------
444 // --------------------------------------------------------------------------
446 private void onClearSearchTextButton() {
447 setSearchText("", true);
448 Log.d(LOG, "Trying to show soft keyboard.");
449 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
450 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
453 void updateLangButton() {
454 // final LanguageResources languageResources =
455 // Language.isoCodeToResources.get(index.shortName);
456 // if (languageResources != null && languageResources.flagId != 0) {
457 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
458 // languageResources.flagId, 0);
460 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
461 langButton.setText(index.shortName);
465 void onLanguageButton() {
466 if (currentSearchOperation != null) {
467 currentSearchOperation.interrupted.set(true);
468 currentSearchOperation = null;
470 changeIndexGetFocusAndResearch((indexIndex + 1) % dictionary.indices.size());
473 void onLanguageButtonLongClick(final Context context) {
474 final Dialog dialog = new Dialog(context);
475 dialog.setContentView(R.layout.select_dictionary_dialog);
476 dialog.setTitle(R.string.selectDictionary);
478 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
481 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
483 // final LinearLayout.LayoutParams layoutParams = new
484 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
485 // ViewGroup.LayoutParams.WRAP_CONTENT);
486 // layoutParams.width = 0;
487 // layoutParams.weight = 1.0f;
489 final Button button = new Button(listView.getContext());
490 final String name = getString(R.string.dictionaryManager);
491 button.setText(name);
492 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
493 DictionaryManagerActivity.getLaunchIntent()) {
495 protected void onGo() {
497 DictionaryActivity.this.finish();
500 button.setOnClickListener(intentLauncher);
501 // button.setLayoutParams(layoutParams);
502 listView.addHeaderView(button);
503 // listView.setHeaderDividersEnabled(true);
505 listView.setAdapter(new BaseAdapter() {
507 public View getView(int position, View convertView, ViewGroup parent) {
508 final LinearLayout result = new LinearLayout(parent.getContext());
510 final DictionaryInfo dictionaryInfo = getItem(position);
511 final Button button = new Button(parent.getContext());
512 final String name = application
513 .getDictionaryName(dictionaryInfo.uncompressedFilename);
514 button.setText(name);
515 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
516 getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
517 0, searchText.getText().toString())) {
519 protected void onGo() {
521 DictionaryActivity.this.finish();
524 button.setOnClickListener(intentLauncher);
525 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
526 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
527 layoutParams.width = 0;
528 layoutParams.weight = 1.0f;
529 button.setLayoutParams(layoutParams);
530 result.addView(button);
535 public long getItemId(int position) {
540 public DictionaryInfo getItem(int position) {
541 return installedDicts.get(position);
545 public int getCount() {
546 return installedDicts.size();
553 private void changeIndexGetFocusAndResearch(final int newIndex) {
554 indexIndex = newIndex;
555 index = dictionary.indices.get(indexIndex);
556 indexAdapter = new IndexAdapter(index);
557 Log.d(LOG, "changingIndex, newLang=" + index.longName);
558 setListAdapter(indexAdapter);
560 searchText.requestFocus(); // Otherwise, nothing may happen.
561 onSearchTextChange(searchText.getText().toString());
562 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
565 void onUpDownButton(final boolean up) {
569 final int firstVisibleRow = getListView().getFirstVisiblePosition();
570 final RowBase row = index.rows.get(firstVisibleRow);
571 final TokenRow tokenRow = row.getTokenRow(true);
572 final int destIndexEntry;
574 if (row != tokenRow) {
575 destIndexEntry = tokenRow.referenceIndex;
577 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
581 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
583 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
584 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
585 searchText.removeTextChangedListener(searchTextWatcher);
586 searchText.setText(dest.token);
587 if (searchText.getLayout() != null) {
588 // Surprising, but this can otherwise crash sometimes...
589 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
591 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
592 searchText.addTextChangedListener(searchTextWatcher);
595 // --------------------------------------------------------------------------
597 // --------------------------------------------------------------------------
599 final Random random = new Random();
602 public boolean onCreateOptionsMenu(final Menu menu) {
603 application.onCreateGlobalOptionsMenu(this, menu);
606 final MenuItem randomWord = menu.add(getString(R.string.randomWord));
607 randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
608 public boolean onMenuItemClick(final MenuItem menuItem) {
609 final String word = index.sortedIndexEntries.get(random
610 .nextInt(index.sortedIndexEntries.size())).token;
611 setSearchText(word, true);
618 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
619 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
620 public boolean onMenuItemClick(final MenuItem menuItem) {
621 startActivity(DictionaryManagerActivity.getLaunchIntent());
629 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
630 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
631 public boolean onMenuItemClick(final MenuItem menuItem) {
632 final Context context = getListView().getContext();
633 final Dialog dialog = new Dialog(context);
634 dialog.setContentView(R.layout.about_dictionary_dialog);
635 final TextView textView = (TextView) dialog.findViewById(R.id.text);
637 final String name = application.getDictionaryName(dictFile.getName());
638 dialog.setTitle(name);
640 final StringBuilder builder = new StringBuilder();
641 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
642 dictionaryInfo.uncompressedBytes = dictFile.length();
643 if (dictionaryInfo != null) {
644 builder.append(dictionaryInfo.dictInfo).append("\n\n");
645 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
648 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
651 getString(R.string.dictionaryCreationTime,
652 dictionaryInfo.creationMillis)).append("\n");
653 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
654 builder.append("\n");
655 builder.append(getString(R.string.indexName, indexInfo.shortName))
658 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
661 builder.append("\n");
662 builder.append(getString(R.string.sources)).append("\n");
663 for (final EntrySource source : dictionary.sources) {
665 getString(R.string.sourceInfo, source.getName(),
666 source.getNumEntries())).append("\n");
670 // builder.append(getString(R.string.invalidDictionary));
672 textView.setText(builder.toString());
675 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
676 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
677 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
678 dialog.getWindow().setAttributes(layoutParams);
687 // --------------------------------------------------------------------------
688 // Context Menu + clicks
689 // --------------------------------------------------------------------------
692 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
693 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
694 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
696 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
697 wordList.getName()));
698 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
699 public boolean onMenuItemClick(MenuItem item) {
700 onAppendToWordList(row);
705 final MenuItem copy = menu.add(android.R.string.copy);
706 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
707 public boolean onMenuItemClick(MenuItem item) {
713 if (selectedSpannableText != null) {
714 final String selectedText = selectedSpannableText;
715 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
716 selectedSpannableText));
717 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
718 public boolean onMenuItemClick(MenuItem item) {
720 for (int i = 0; i < dictionary.indices.size(); ++i) {
721 final Index index = dictionary.indices.get(i);
722 if (indexPrepFinished) {
723 System.out.println("Doing index lookup: on " + selectedText);
724 final IndexEntry indexEntry = index.findExact(selectedText);
725 if (indexEntry != null) {
726 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
728 if (tokenRow != null && tokenRow.hasMainEntry) {
734 Log.w(LOG, "Skipping findExact on index " + index.shortName);
737 if (indexToUse == -1) {
738 indexToUse = selectedSpannableIndex;
740 final boolean changeIndex = indexIndex != indexToUse;
741 setSearchText(selectedText, !changeIndex); // If we're not
747 changeIndexGetFocusAndResearch(indexToUse);
749 // Give focus back to list view because typing is done.
750 getListView().requestFocus();
759 protected void onListItemClick(ListView l, View v, int row, long id) {
761 if (clickOpensContextMenu && dictRaf != null) {
766 void onAppendToWordList(final RowBase row) {
769 final StringBuilder rawText = new StringBuilder();
770 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
771 rawText.append(index.longName).append("\t");
772 rawText.append(row.getTokenRow(true).getToken()).append("\t");
773 rawText.append(row.getRawText(saveOnlyFirstSubentry));
774 Log.d(LOG, "Writing : " + rawText);
777 wordList.getParentFile().mkdirs();
778 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
779 out.println(rawText.toString());
781 } catch (IOException e) {
782 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
784 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
785 Toast.LENGTH_LONG).show();
791 * Called when user clicks outside of search text, so that they can start
792 * typing again immediately.
794 void defocusSearchText() {
795 // Log.d(LOG, "defocusSearchText");
796 // Request focus so that if we start typing again, it clears the text
798 getListView().requestFocus();
800 // Visual indication that a new keystroke will clear the search text.
801 searchText.selectAll();
804 @SuppressWarnings("deprecation")
805 void onCopy(final RowBase row) {
808 Log.d(LOG, "Copy, row=" + row);
809 final StringBuilder result = new StringBuilder();
810 result.append(row.getRawText(false));
811 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
812 clipboardManager.setText(result.toString());
813 Log.d(LOG, "Copied: " + result);
817 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
818 if (event.getUnicodeChar() != 0) {
819 if (!searchText.hasFocus()) {
820 setSearchText("" + (char) event.getUnicodeChar(), true);
824 if (keyCode == KeyEvent.KEYCODE_BACK) {
825 // Log.d(LOG, "Clearing dictionary prefs.");
826 // Pretend that we just autolaunched so that we won't do it again.
827 // DictionaryManagerActivity.lastAutoLaunchMillis =
828 // System.currentTimeMillis();
830 if (keyCode == KeyEvent.KEYCODE_ENTER) {
831 Log.d(LOG, "Trying to hide soft keyboard.");
832 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
833 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
834 InputMethodManager.HIDE_NOT_ALWAYS);
837 return super.onKeyDown(keyCode, event);
840 private void setSearchText(final String text, final boolean triggerSearch) {
841 if (!triggerSearch) {
842 getListView().requestFocus();
844 searchText.setText(text);
845 searchText.requestFocus();
848 onSearchTextChange(text);
852 private long cursorDelayMillis = 100;
854 private void moveCursorToRight() {
855 if (searchText.getLayout() != null) {
856 cursorDelayMillis = 100;
857 // Surprising, but this can crash when you rotate...
858 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
860 uiHandler.postDelayed(new Runnable() {
865 }, cursorDelayMillis);
866 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
870 // --------------------------------------------------------------------------
872 // --------------------------------------------------------------------------
874 private void searchFinished(final SearchOperation searchOperation) {
875 if (searchOperation.interrupted.get()) {
876 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
879 if (searchOperation != this.currentSearchOperation) {
880 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
884 final Index.IndexEntry searchResult = searchOperation.searchResult;
885 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
887 currentSearchOperation = null;
888 uiHandler.postDelayed(new Runnable() {
891 if (currentSearchOperation == null) {
892 if (searchResult != null) {
896 jumpToRow(searchResult.startRow);
897 } else if (searchOperation.multiWordSearchResult != null) {
898 // Multi-row search....
899 setFiltered(searchOperation);
901 throw new IllegalStateException("This should never happen.");
904 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
911 private final void jumpToRow(final int row) {
913 getListView().setSelected(true);
916 static final Pattern WHITESPACE = Pattern.compile("\\s+");
918 final class SearchOperation implements Runnable {
920 final AtomicBoolean interrupted = new AtomicBoolean(false);
922 final String searchText;
924 List<String> searchTokens; // filled in for multiWord.
928 long searchStartMillis;
930 Index.IndexEntry searchResult;
932 List<RowBase> multiWordSearchResult;
934 boolean done = false;
936 SearchOperation(final String searchText, final Index index) {
937 this.searchText = searchText.trim();
941 public String toString() {
942 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
948 searchStartMillis = System.currentTimeMillis();
949 final String[] searchTokenArray = WHITESPACE.split(searchText);
950 if (searchTokenArray.length == 1) {
951 searchResult = index.findInsertionPoint(searchText, interrupted);
953 searchTokens = Arrays.asList(searchTokenArray);
954 multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
957 "searchText=" + searchText + ", searchDuration="
958 + (System.currentTimeMillis() - searchStartMillis)
959 + ", interrupted=" + interrupted.get());
960 if (!interrupted.get()) {
961 uiHandler.post(new Runnable() {
964 searchFinished(SearchOperation.this);
968 } catch (Exception e) {
969 Log.e(LOG, "Failure during search (can happen during Activity close.");
971 synchronized (this) {
979 // --------------------------------------------------------------------------
981 // --------------------------------------------------------------------------
983 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
984 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
986 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
987 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
989 final class IndexAdapter extends BaseAdapter {
991 private static final float PADDING_DEFAULT_DP = 8;
993 private static final float PADDING_LARGE_DP = 16;
997 final List<RowBase> rows;
999 final Set<String> toHighlight;
1001 private int mPaddingDefault;
1003 private int mPaddingLarge;
1005 IndexAdapter(final Index index) {
1008 this.toHighlight = null;
1012 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1015 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1019 private void getMetrics() {
1020 // Get the screen's density scale
1021 final float scale = getResources().getDisplayMetrics().density;
1022 // Convert the dps to pixels, based on density scale
1023 mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
1024 mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
1028 public int getCount() {
1033 public RowBase getItem(int position) {
1034 return rows.get(position);
1038 public long getItemId(int position) {
1039 return getItem(position).index();
1043 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1044 final TableLayout result;
1045 if (convertView instanceof TableLayout) {
1046 result = (TableLayout) convertView;
1047 result.removeAllViews();
1049 result = new TableLayout(parent.getContext());
1051 final RowBase row = getItem(position);
1052 if (row instanceof PairEntry.Row) {
1053 return getView(position, (PairEntry.Row) row, parent, result);
1054 } else if (row instanceof TokenRow) {
1055 return getView((TokenRow) row, parent, result);
1056 } else if (row instanceof HtmlEntry.Row) {
1057 return getView((HtmlEntry.Row) row, parent, result);
1059 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1063 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1064 final TableLayout result) {
1065 final PairEntry entry = row.getEntry();
1066 final int rowCount = entry.pairs.size();
1068 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1069 layoutParams.weight = 0.5f;
1070 layoutParams.leftMargin = mPaddingLarge;
1072 for (int r = 0; r < rowCount; ++r) {
1073 final TableRow tableRow = new TableRow(result.getContext());
1075 final TextView col1 = new TextView(tableRow.getContext());
1076 final TextView col2 = new TextView(tableRow.getContext());
1078 // Set the columns in the table.
1080 final TextView bullet = new TextView(tableRow.getContext());
1081 bullet.setText(" • ");
1082 tableRow.addView(bullet);
1084 tableRow.addView(col1, layoutParams);
1085 final TextView margin = new TextView(tableRow.getContext());
1086 margin.setText(" ");
1087 tableRow.addView(margin);
1089 final TextView bullet = new TextView(tableRow.getContext());
1090 bullet.setText(" • ");
1091 tableRow.addView(bullet);
1093 tableRow.addView(col2, layoutParams);
1097 // Set what's in the columns.
1099 final Pair pair = entry.pairs.get(r);
1100 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1101 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1103 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1104 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1106 // Bold the token instances in col1.
1107 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1108 .singleton(row.getTokenRow(true).getToken());
1109 final Spannable col1Spannable = (Spannable) col1.getText();
1110 for (final String token : toBold) {
1112 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1113 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1114 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1115 startPos += token.length();
1119 createTokenLinkSpans(col1, col1Spannable, col1Text);
1120 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1122 col1.setTypeface(typeface);
1123 col2.setTypeface(typeface);
1124 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1125 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1126 // col2.setBackgroundResource(theme.otherLangBg);
1128 if (index.swapPairEntries) {
1129 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1130 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1132 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1133 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1136 result.addView(tableRow);
1139 // Because we have a Button inside a ListView row:
1140 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1141 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1142 result.setClickable(true);
1143 result.setFocusable(true);
1144 result.setLongClickable(true);
1145 result.setBackgroundResource(android.R.drawable.menuitem_background);
1146 result.setOnClickListener(new TextView.OnClickListener() {
1148 public void onClick(View v) {
1149 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1156 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1157 final Context context = parent.getContext();
1159 final HtmlEntry htmlEntry = row.getEntry();
1161 // final TableRow tableRow = new TableRow(context);
1162 final LinearLayout tableRow = new LinearLayout(context);
1163 result.addView(tableRow);
1166 final TextView textView = new TextView(context);
1167 textView.setText(htmlEntry.title);
1168 textView.setLayoutParams(new LinearLayout.LayoutParams(0,
1169 ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
1170 tableRow.addView(textView);
1173 final Button button = new Button(context);
1174 button.setText("open");
1175 button.setLayoutParams(new LinearLayout.LayoutParams(
1176 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.0f));
1177 tableRow.addView(button);
1179 button.setOnClickListener(new OnClickListener() {
1181 public void onClick(View v) {
1182 startActivity(HtmlDisplayActivity.getHtmlIntent(String.format(
1183 "<html><head></head><body>%s</body></html>", htmlEntry.html)));
1190 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1191 final Context context = parent.getContext();
1193 final TableRow tableRow = new TableRow(result.getContext());
1194 tableRow.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg
1195 : theme.tokenRowOtherBg);
1196 tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
1197 result.addView(tableRow);
1199 final IndexEntry indexEntry = row.getIndexEntry();
1201 final TextView textView = new TextView(context);
1202 textView.setText(indexEntry.token);
1204 // textView.setTextColor(android.R.color.secondary_text_light);
1205 textView.setTextAppearance(context, theme.tokenRowFg);
1206 textView.setTypeface(typeface);
1207 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
1208 TableRow.LayoutParams lp = new TableRow.LayoutParams(0);
1210 textView.setLayoutParams(lp);
1211 tableRow.addView(textView);
1214 if (!indexEntry.htmlEntries.isEmpty()) {
1215 final ImageButton button = new ImageButton(context);
1216 button.setImageResource(R.drawable.ic_menu_forward);
1217 button.setOnClickListener(new OnClickListener() {
1219 public void onClick(View v) {
1220 final String html = HtmlEntry.htmlBody(indexEntry.htmlEntries);
1221 startActivity(HtmlDisplayActivity.getHtmlIntent(String.format(
1222 "<html><head></head><body>%s</body></html>", html)));
1225 tableRow.addView(button);
1226 lp = new TableRow.LayoutParams(1);
1228 button.setLayoutParams(lp);
1229 //result.setColumnStretchable(0, true);
1230 //result.setColumnStretchable(1, false);
1239 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1241 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1242 final String text) {
1243 // Saw from the source code that LinkMovementMethod sets the selection!
1244 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1245 textView.setMovementMethod(LinkMovementMethod.getInstance());
1246 final Matcher matcher = CHAR_DASH.matcher(text);
1247 while (matcher.find()) {
1248 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(),
1249 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1253 String selectedSpannableText = null;
1255 int selectedSpannableIndex = -1;
1258 public boolean onTouchEvent(MotionEvent event) {
1259 selectedSpannableText = null;
1260 selectedSpannableIndex = -1;
1261 return super.onTouchEvent(event);
1264 private class TextViewLongClickListener implements OnLongClickListener {
1267 private TextViewLongClickListener(final int index) {
1272 public boolean onLongClick(final View v) {
1273 final TextView textView = (TextView) v;
1274 final int start = textView.getSelectionStart();
1275 final int end = textView.getSelectionEnd();
1276 if (start >= 0 && end >= 0) {
1277 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1278 selectedSpannableIndex = index;
1284 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1287 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1290 // --------------------------------------------------------------------------
1292 // --------------------------------------------------------------------------
1294 void onSearchTextChange(final String text) {
1295 if ("thadolina".equals(text)) {
1296 final Dialog dialog = new Dialog(getListView().getContext());
1297 dialog.setContentView(R.layout.thadolina_dialog);
1298 dialog.setTitle("Ti amo, amore mio!");
1299 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1300 imageView.setOnClickListener(new OnClickListener() {
1302 public void onClick(View v) {
1303 final Intent intent = new Intent(Intent.ACTION_VIEW);
1304 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1305 startActivity(intent);
1310 if (dictRaf == null) {
1311 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1314 if (!searchText.isFocused()) {
1315 Log.d(LOG, "searchText changed without focus, doing nothing.");
1318 Log.d(LOG, "onSearchTextChange: " + text);
1319 if (currentSearchOperation != null) {
1320 Log.d(LOG, "Interrupting currentSearchOperation.");
1321 currentSearchOperation.interrupted.set(true);
1323 currentSearchOperation = new SearchOperation(text, index);
1324 searchExecutor.execute(currentSearchOperation);
1327 private class SearchTextWatcher implements TextWatcher {
1328 public void afterTextChanged(final Editable searchTextEditable) {
1329 if (searchText.hasFocus()) {
1330 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
1331 // If they were typing to cause the change, update the UI.
1332 onSearchTextChange(searchText.getText().toString());
1336 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1339 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1343 // --------------------------------------------------------------------------
1344 // Filtered results.
1345 // --------------------------------------------------------------------------
1347 boolean isFiltered() {
1348 return rowsToShow != null;
1351 void setFiltered(final SearchOperation searchOperation) {
1352 ((Button) findViewById(R.id.UpButton)).setEnabled(false);
1353 ((Button) findViewById(R.id.DownButton)).setEnabled(false);
1354 rowsToShow = searchOperation.multiWordSearchResult;
1355 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1358 void clearFiltered() {
1359 ((Button) findViewById(R.id.UpButton)).setEnabled(true);
1360 ((Button) findViewById(R.id.DownButton)).setEnabled(true);
1361 setListAdapter(new IndexAdapter(index));