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.setTypeface(typeface);
297 searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
299 langButton = (Button) findViewById(R.id.LangButton);
301 searchText.requestFocus();
302 searchText.addTextChangedListener(searchTextWatcher);
304 // Set the search text from the intent, then the saved state.
305 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
306 if (savedInstanceState != null) {
307 text = savedInstanceState.getString(C.SEARCH_TOKEN);
312 setSearchText(text, true);
313 Log.d(LOG, "Trying to restore searchText=" + text);
315 final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
316 clearSearchTextButton.setOnClickListener(new OnClickListener() {
317 public void onClick(View v) {
318 onClearSearchTextButton(clearSearchTextButton);
321 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this)
322 .getBoolean(getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
325 final Button langButton = (Button) findViewById(R.id.LangButton);
326 langButton.setOnClickListener(new OnClickListener() {
327 public void onClick(View v) {
331 langButton.setOnLongClickListener(new OnLongClickListener() {
333 public boolean onLongClick(View v) {
334 onLanguageButtonLongClick(v.getContext());
340 final Button upButton = (Button) findViewById(R.id.UpButton);
341 upButton.setOnClickListener(new OnClickListener() {
342 public void onClick(View v) {
343 onUpDownButton(true);
346 final Button downButton = (Button) findViewById(R.id.DownButton);
347 downButton.setOnClickListener(new OnClickListener() {
348 public void onClick(View v) {
349 onUpDownButton(false);
353 getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
355 public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
357 if (!searchText.isFocused()) {
359 final RowBase row = (RowBase) getListAdapter().getItem(position);
360 Log.d(LOG, "onItemSelected: " + row.index());
361 final TokenRow tokenRow = row.getTokenRow(true);
362 searchText.setText(tokenRow.getToken());
368 public void onNothingSelected(AdapterView<?> arg0) {
373 registerForContextMenu(getListView());
376 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
377 getString(R.string.wordListFileDefault)));
378 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
380 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
382 // if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey),
384 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
386 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
388 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
392 protected void onResume() {
394 if (PreferenceActivity.prefsMightHaveChanged) {
395 PreferenceActivity.prefsMightHaveChanged = false;
397 startActivity(getIntent());
399 if (initialSearchText != null) {
400 setSearchText(initialSearchText, true);
405 protected void onPause() {
409 private static void setDictionaryPrefs(final Context context, final File dictFile,
410 final int indexIndex, final String searchToken) {
411 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
413 prefs.putString(C.DICT_FILE, dictFile.getPath());
414 prefs.putInt(C.INDEX_INDEX, indexIndex);
415 prefs.putString(C.SEARCH_TOKEN, ""); // Don't need to save search token.
420 protected void onDestroy() {
422 if (dictRaf == null) {
426 final SearchOperation searchOperation = currentSearchOperation;
427 currentSearchOperation = null;
429 // Before we close the RAF, we have to wind the current search down.
430 if (searchOperation != null) {
431 Log.d(LOG, "Interrupting search to shut down.");
432 currentSearchOperation = null;
433 searchOperation.interrupted.set(true);
437 Log.d(LOG, "Closing RAF.");
439 } catch (IOException e) {
440 Log.e(LOG, "Failed to close dictionary", e);
445 // --------------------------------------------------------------------------
447 // --------------------------------------------------------------------------
449 private void onClearSearchTextButton(final Button clearSearchTextButton) {
450 setSearchText("", true);
451 Log.d(LOG, "Trying to show soft keyboard.");
452 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
453 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
456 void updateLangButton() {
457 // final LanguageResources languageResources =
458 // Language.isoCodeToResources.get(index.shortName);
459 // if (languageResources != null && languageResources.flagId != 0) {
460 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0,
461 // languageResources.flagId, 0);
463 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
464 langButton.setText(index.shortName);
468 void onLanguageButton() {
469 if (currentSearchOperation != null) {
470 currentSearchOperation.interrupted.set(true);
471 currentSearchOperation = null;
473 changeIndexGetFocusAndResearch((indexIndex + 1) % dictionary.indices.size());
476 void onLanguageButtonLongClick(final Context context) {
477 final Dialog dialog = new Dialog(context);
478 dialog.setContentView(R.layout.select_dictionary_dialog);
479 dialog.setTitle(R.string.selectDictionary);
481 final List<DictionaryInfo> installedDicts = ((DictionaryApplication) getApplication())
484 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
486 // final LinearLayout.LayoutParams layoutParams = new
487 // LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
488 // ViewGroup.LayoutParams.WRAP_CONTENT);
489 // layoutParams.width = 0;
490 // layoutParams.weight = 1.0f;
492 final Button button = new Button(listView.getContext());
493 final String name = getString(R.string.dictionaryManager);
494 button.setText(name);
495 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
496 DictionaryManagerActivity.getLaunchIntent()) {
498 protected void onGo() {
500 DictionaryActivity.this.finish();
503 button.setOnClickListener(intentLauncher);
504 // button.setLayoutParams(layoutParams);
505 listView.addHeaderView(button);
506 // listView.setHeaderDividersEnabled(true);
508 listView.setAdapter(new BaseAdapter() {
510 public View getView(int position, View convertView, ViewGroup parent) {
511 final LinearLayout result = new LinearLayout(parent.getContext());
513 final DictionaryInfo dictionaryInfo = getItem(position);
514 final Button button = new Button(parent.getContext());
515 final String name = application
516 .getDictionaryName(dictionaryInfo.uncompressedFilename);
517 button.setText(name);
518 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
519 getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
520 0, searchText.getText().toString())) {
522 protected void onGo() {
524 DictionaryActivity.this.finish();
527 button.setOnClickListener(intentLauncher);
528 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
529 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
530 layoutParams.width = 0;
531 layoutParams.weight = 1.0f;
532 button.setLayoutParams(layoutParams);
533 result.addView(button);
538 public long getItemId(int position) {
543 public DictionaryInfo getItem(int position) {
544 return installedDicts.get(position);
548 public int getCount() {
549 return installedDicts.size();
556 private void changeIndexGetFocusAndResearch(final int newIndex) {
557 indexIndex = newIndex;
558 index = dictionary.indices.get(indexIndex);
559 indexAdapter = new IndexAdapter(index);
560 Log.d(LOG, "changingIndex, newLang=" + index.longName);
561 setListAdapter(indexAdapter);
563 searchText.requestFocus(); // Otherwise, nothing may happen.
564 onSearchTextChange(searchText.getText().toString());
565 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
568 void onUpDownButton(final boolean up) {
572 final int firstVisibleRow = getListView().getFirstVisiblePosition();
573 final RowBase row = index.rows.get(firstVisibleRow);
574 final TokenRow tokenRow = row.getTokenRow(true);
575 final int destIndexEntry;
577 if (row != tokenRow) {
578 destIndexEntry = tokenRow.referenceIndex;
580 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
584 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
586 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
587 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
588 searchText.removeTextChangedListener(searchTextWatcher);
589 searchText.setText(dest.token);
590 if (searchText.getLayout() != null) {
591 // Surprising, but this can otherwise crash sometimes...
592 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
594 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
595 searchText.addTextChangedListener(searchTextWatcher);
598 // --------------------------------------------------------------------------
600 // --------------------------------------------------------------------------
602 final Random random = new Random();
605 public boolean onCreateOptionsMenu(final Menu menu) {
606 application.onCreateGlobalOptionsMenu(this, menu);
609 final MenuItem randomWord = menu.add(getString(R.string.randomWord));
610 randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
611 public boolean onMenuItemClick(final MenuItem menuItem) {
612 final String word = index.sortedIndexEntries.get(random
613 .nextInt(index.sortedIndexEntries.size())).token;
614 setSearchText(word, true);
621 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
622 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
623 public boolean onMenuItemClick(final MenuItem menuItem) {
624 startActivity(DictionaryManagerActivity.getLaunchIntent());
632 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
633 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
634 public boolean onMenuItemClick(final MenuItem menuItem) {
635 final Context context = getListView().getContext();
636 final Dialog dialog = new Dialog(context);
637 dialog.setContentView(R.layout.about_dictionary_dialog);
638 final TextView textView = (TextView) dialog.findViewById(R.id.text);
640 final String name = application.getDictionaryName(dictFile.getName());
641 dialog.setTitle(name);
643 final StringBuilder builder = new StringBuilder();
644 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
645 dictionaryInfo.uncompressedBytes = dictFile.length();
646 if (dictionaryInfo != null) {
647 builder.append(dictionaryInfo.dictInfo).append("\n\n");
648 builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
651 getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
654 getString(R.string.dictionaryCreationTime,
655 dictionaryInfo.creationMillis)).append("\n");
656 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
657 builder.append("\n");
658 builder.append(getString(R.string.indexName, indexInfo.shortName))
661 getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
664 builder.append("\n");
665 builder.append(getString(R.string.sources)).append("\n");
666 for (final EntrySource source : dictionary.sources) {
668 getString(R.string.sourceInfo, source.getName(),
669 source.getNumEntries())).append("\n");
673 // builder.append(getString(R.string.invalidDictionary));
675 textView.setText(builder.toString());
678 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
679 layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
680 layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
681 dialog.getWindow().setAttributes(layoutParams);
690 // --------------------------------------------------------------------------
691 // Context Menu + clicks
692 // --------------------------------------------------------------------------
695 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
696 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
697 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
699 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
700 wordList.getName()));
701 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
702 public boolean onMenuItemClick(MenuItem item) {
703 onAppendToWordList(row);
708 final MenuItem copy = menu.add(android.R.string.copy);
709 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
710 public boolean onMenuItemClick(MenuItem item) {
716 if (selectedSpannableText != null) {
717 final String selectedText = selectedSpannableText;
718 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection,
719 selectedSpannableText));
720 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
721 public boolean onMenuItemClick(MenuItem item) {
723 for (int i = 0; i < dictionary.indices.size(); ++i) {
724 final Index index = dictionary.indices.get(i);
725 if (indexPrepFinished) {
726 System.out.println("Doing index lookup: on " + selectedText);
727 final IndexEntry indexEntry = index.findExact(selectedText);
728 if (indexEntry != null) {
729 final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
731 if (tokenRow != null && tokenRow.hasMainEntry) {
737 Log.w(LOG, "Skipping findExact on index " + index.shortName);
740 if (indexToUse == -1) {
741 indexToUse = selectedSpannableIndex;
743 final boolean changeIndex = indexIndex != indexToUse;
744 setSearchText(selectedText, !changeIndex); // If we're not
750 changeIndexGetFocusAndResearch(indexToUse);
752 // Give focus back to list view because typing is done.
753 getListView().requestFocus();
762 protected void onListItemClick(ListView l, View v, int row, long id) {
764 if (clickOpensContextMenu && dictRaf != null) {
769 void onAppendToWordList(final RowBase row) {
772 final StringBuilder rawText = new StringBuilder();
773 rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
774 rawText.append(index.longName).append("\t");
775 rawText.append(row.getTokenRow(true).getToken()).append("\t");
776 rawText.append(row.getRawText(saveOnlyFirstSubentry));
777 Log.d(LOG, "Writing : " + rawText);
780 wordList.getParentFile().mkdirs();
781 final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
782 out.println(rawText.toString());
784 } catch (IOException e) {
785 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
787 getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
788 Toast.LENGTH_LONG).show();
794 * Called when user clicks outside of search text, so that they can start
795 * typing again immediately.
797 void defocusSearchText() {
798 // Log.d(LOG, "defocusSearchText");
799 // Request focus so that if we start typing again, it clears the text
801 getListView().requestFocus();
803 // Visual indication that a new keystroke will clear the search text.
804 searchText.selectAll();
807 @SuppressWarnings("deprecation")
808 void onCopy(final RowBase row) {
811 Log.d(LOG, "Copy, row=" + row);
812 final StringBuilder result = new StringBuilder();
813 result.append(row.getRawText(false));
814 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
815 clipboardManager.setText(result.toString());
816 Log.d(LOG, "Copied: " + result);
820 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
821 if (event.getUnicodeChar() != 0) {
822 if (!searchText.hasFocus()) {
823 setSearchText("" + (char) event.getUnicodeChar(), true);
827 if (keyCode == KeyEvent.KEYCODE_BACK) {
828 // Log.d(LOG, "Clearing dictionary prefs.");
829 // Pretend that we just autolaunched so that we won't do it again.
830 // DictionaryManagerActivity.lastAutoLaunchMillis =
831 // System.currentTimeMillis();
833 if (keyCode == KeyEvent.KEYCODE_ENTER) {
834 Log.d(LOG, "Trying to hide soft keyboard.");
835 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
836 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
837 InputMethodManager.HIDE_NOT_ALWAYS);
840 return super.onKeyDown(keyCode, event);
843 private void setSearchText(final String text, final boolean triggerSearch) {
844 if (!triggerSearch) {
845 getListView().requestFocus();
847 searchText.setText(text);
848 searchText.requestFocus();
851 onSearchTextChange(text);
855 private long cursorDelayMillis = 100;
857 private void moveCursorToRight() {
858 if (searchText.getLayout() != null) {
859 cursorDelayMillis = 100;
860 // Surprising, but this can crash when you rotate...
861 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
863 uiHandler.postDelayed(new Runnable() {
868 }, cursorDelayMillis);
869 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
873 // --------------------------------------------------------------------------
875 // --------------------------------------------------------------------------
877 private void searchFinished(final SearchOperation searchOperation) {
878 if (searchOperation.interrupted.get()) {
879 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
882 if (searchOperation != this.currentSearchOperation) {
883 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
887 final Index.IndexEntry searchResult = searchOperation.searchResult;
888 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
890 currentSearchOperation = null;
891 uiHandler.postDelayed(new Runnable() {
894 if (currentSearchOperation == null) {
895 if (searchResult != null) {
899 jumpToRow(searchResult.startRow);
900 } else if (searchOperation.multiWordSearchResult != null) {
901 // Multi-row search....
902 setFiltered(searchOperation);
904 throw new IllegalStateException("This should never happen.");
907 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
914 private final void jumpToRow(final int row) {
916 getListView().setSelected(true);
919 static final Pattern WHITESPACE = Pattern.compile("\\s+");
921 final class SearchOperation implements Runnable {
923 final AtomicBoolean interrupted = new AtomicBoolean(false);
925 final String searchText;
927 List<String> searchTokens; // filled in for multiWord.
931 long searchStartMillis;
933 Index.IndexEntry searchResult;
935 List<RowBase> multiWordSearchResult;
937 boolean done = false;
939 SearchOperation(final String searchText, final Index index) {
940 this.searchText = searchText.trim();
944 public String toString() {
945 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
951 searchStartMillis = System.currentTimeMillis();
952 final String[] searchTokenArray = WHITESPACE.split(searchText);
953 if (searchTokenArray.length == 1) {
954 searchResult = index.findInsertionPoint(searchText, interrupted);
956 searchTokens = Arrays.asList(searchTokenArray);
957 multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
960 "searchText=" + searchText + ", searchDuration="
961 + (System.currentTimeMillis() - searchStartMillis)
962 + ", interrupted=" + interrupted.get());
963 if (!interrupted.get()) {
964 uiHandler.post(new Runnable() {
967 searchFinished(SearchOperation.this);
971 } catch (Exception e) {
972 Log.e(LOG, "Failure during search (can happen during Activity close.");
974 synchronized (this) {
982 // --------------------------------------------------------------------------
984 // --------------------------------------------------------------------------
986 static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
987 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
989 static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
990 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
992 final class IndexAdapter extends BaseAdapter {
996 final List<RowBase> rows;
998 final Set<String> toHighlight;
1000 IndexAdapter(final Index index) {
1003 this.toHighlight = null;
1006 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
1009 this.toHighlight = new LinkedHashSet<String>(toHighlight);
1013 public int getCount() {
1018 public RowBase getItem(int position) {
1019 return rows.get(position);
1023 public long getItemId(int position) {
1024 return getItem(position).index();
1028 public TableLayout getView(int position, View convertView, ViewGroup parent) {
1029 final TableLayout result;
1030 if (convertView instanceof TableLayout) {
1031 result = (TableLayout) convertView;
1032 result.removeAllViews();
1034 result = new TableLayout(parent.getContext());
1036 final RowBase row = getItem(position);
1037 if (row instanceof PairEntry.Row) {
1038 return getView(position, (PairEntry.Row) row, parent, result);
1039 } else if (row instanceof TokenRow) {
1040 return getView((TokenRow) row, parent, result);
1041 } else if (row instanceof HtmlEntry.Row) {
1042 return getView((HtmlEntry.Row) row, parent, result);
1044 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
1048 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
1049 final TableLayout result) {
1050 final PairEntry entry = row.getEntry();
1051 final int rowCount = entry.pairs.size();
1053 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
1054 layoutParams.weight = 0.5f;
1056 for (int r = 0; r < rowCount; ++r) {
1057 final TableRow tableRow = new TableRow(result.getContext());
1059 final TextView col1 = new TextView(tableRow.getContext());
1060 final TextView col2 = new TextView(tableRow.getContext());
1062 // Set the columns in the table.
1064 final TextView bullet = new TextView(tableRow.getContext());
1065 bullet.setText(" • ");
1066 tableRow.addView(bullet);
1068 tableRow.addView(col1, layoutParams);
1069 final TextView margin = new TextView(tableRow.getContext());
1070 margin.setText(" ");
1071 tableRow.addView(margin);
1073 final TextView bullet = new TextView(tableRow.getContext());
1074 bullet.setText(" • ");
1075 tableRow.addView(bullet);
1077 tableRow.addView(col2, layoutParams);
1081 // Set what's in the columns.
1083 final Pair pair = entry.pairs.get(r);
1084 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
1085 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
1087 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
1088 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
1090 // Bold the token instances in col1.
1091 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
1092 .singleton(row.getTokenRow(true).getToken());
1093 final Spannable col1Spannable = (Spannable) col1.getText();
1094 for (final String token : toBold) {
1096 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
1097 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
1098 + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1099 startPos += token.length();
1103 createTokenLinkSpans(col1, col1Spannable, col1Text);
1104 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
1106 col1.setTypeface(typeface);
1107 col2.setTypeface(typeface);
1108 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1109 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
1110 // col2.setBackgroundResource(theme.otherLangBg);
1112 if (index.swapPairEntries) {
1113 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
1114 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
1116 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
1117 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
1120 result.addView(tableRow);
1123 // Because we have a Button inside a ListView row:
1124 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
1125 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1126 result.setClickable(true);
1127 result.setFocusable(true);
1128 result.setLongClickable(true);
1129 result.setBackgroundResource(android.R.drawable.menuitem_background);
1130 result.setOnClickListener(new TextView.OnClickListener() {
1132 public void onClick(View v) {
1133 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
1140 private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
1141 final Context context = parent.getContext();
1143 final HtmlEntry htmlEntry = row.getEntry();
1145 // final TableRow tableRow = new TableRow(context);
1146 final LinearLayout tableRow = new LinearLayout(context);
1147 result.addView(tableRow);
1150 final TextView textView = new TextView(context);
1151 textView.setText(htmlEntry.title);
1152 textView.setLayoutParams(new LinearLayout.LayoutParams(0,
1153 ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
1154 tableRow.addView(textView);
1157 final Button button = new Button(context);
1158 button.setText("open");
1159 button.setLayoutParams(new LinearLayout.LayoutParams(
1160 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.0f));
1161 tableRow.addView(button);
1163 button.setOnClickListener(new OnClickListener() {
1165 public void onClick(View v) {
1166 startActivity(HtmlDisplayActivity.getHtmlIntent(String.format(
1167 "<html><head></head><body>%s</body></html>", htmlEntry.html)));
1174 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
1175 final Context context = parent.getContext();
1176 final TextView textView = new TextView(context);
1177 textView.setText(row.getToken());
1179 // textView.setTextColor(android.R.color.secondary_text_light);
1180 textView.setTextAppearance(context, theme.tokenRowFg);
1181 textView.setTypeface(typeface);
1182 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
1184 final TableRow tableRow = new TableRow(result.getContext());
1185 tableRow.addView(textView);
1186 tableRow.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg
1187 : theme.tokenRowOtherBg);
1188 result.addView(tableRow);
1194 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
1196 private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
1197 final String text) {
1198 // Saw from the source code that LinkMovementMethod sets the selection!
1199 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
1200 textView.setMovementMethod(LinkMovementMethod.getInstance());
1201 final Matcher matcher = CHAR_DASH.matcher(text);
1202 while (matcher.find()) {
1203 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(),
1204 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
1208 String selectedSpannableText = null;
1210 int selectedSpannableIndex = -1;
1213 public boolean onTouchEvent(MotionEvent event) {
1214 selectedSpannableText = null;
1215 selectedSpannableIndex = -1;
1216 return super.onTouchEvent(event);
1219 private class TextViewLongClickListener implements OnLongClickListener {
1222 private TextViewLongClickListener(final int index) {
1227 public boolean onLongClick(final View v) {
1228 final TextView textView = (TextView) v;
1229 final int start = textView.getSelectionStart();
1230 final int end = textView.getSelectionEnd();
1231 if (start >= 0 && end >= 0) {
1232 selectedSpannableText = textView.getText().subSequence(start, end).toString();
1233 selectedSpannableIndex = index;
1239 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
1242 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1245 // --------------------------------------------------------------------------
1247 // --------------------------------------------------------------------------
1249 void onSearchTextChange(final String text) {
1250 if ("thadolina".equals(text)) {
1251 final Dialog dialog = new Dialog(getListView().getContext());
1252 dialog.setContentView(R.layout.thadolina_dialog);
1253 dialog.setTitle("Ti amo, amore mio!");
1254 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
1255 imageView.setOnClickListener(new OnClickListener() {
1257 public void onClick(View v) {
1258 final Intent intent = new Intent(Intent.ACTION_VIEW);
1259 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
1260 startActivity(intent);
1265 if (dictRaf == null) {
1266 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
1269 if (!searchText.isFocused()) {
1270 Log.d(LOG, "searchText changed without focus, doing nothing.");
1273 Log.d(LOG, "onSearchTextChange: " + text);
1274 if (currentSearchOperation != null) {
1275 Log.d(LOG, "Interrupting currentSearchOperation.");
1276 currentSearchOperation.interrupted.set(true);
1278 currentSearchOperation = new SearchOperation(text, index);
1279 searchExecutor.execute(currentSearchOperation);
1282 private class SearchTextWatcher implements TextWatcher {
1283 public void afterTextChanged(final Editable searchTextEditable) {
1284 if (searchText.hasFocus()) {
1285 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
1286 // If they were typing to cause the change, update the UI.
1287 onSearchTextChange(searchText.getText().toString());
1291 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1294 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
1298 // --------------------------------------------------------------------------
1299 // Filtered results.
1300 // --------------------------------------------------------------------------
1302 boolean isFiltered() {
1303 return rowsToShow != null;
1306 void setFiltered(final SearchOperation searchOperation) {
1307 ((Button) findViewById(R.id.UpButton)).setEnabled(false);
1308 ((Button) findViewById(R.id.DownButton)).setEnabled(false);
1309 rowsToShow = searchOperation.multiWordSearchResult;
1310 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
1313 void clearFiltered() {
1314 ((Button) findViewById(R.id.UpButton)).setEnabled(true);
1315 ((Button) findViewById(R.id.DownButton)).setEnabled(true);
1316 setListAdapter(new IndexAdapter(index));