1 // Copyright 2011 Google Inc. All Rights Reserved.
\r
3 // Licensed under the Apache License, Version 2.0 (the "License");
\r
4 // you may not use this file except in compliance with the License.
\r
5 // You may obtain a copy of the License at
\r
7 // http://www.apache.org/licenses/LICENSE-2.0
\r
9 // Unless required by applicable law or agreed to in writing, software
\r
10 // distributed under the License is distributed on an "AS IS" BASIS,
\r
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
12 // See the License for the specific language governing permissions and
\r
13 // limitations under the License.
\r
15 package com.hughes.android.dictionary;
\r
17 import java.io.File;
\r
18 import java.io.FileWriter;
\r
19 import java.io.IOException;
\r
20 import java.io.PrintWriter;
\r
21 import java.io.RandomAccessFile;
\r
22 import java.text.SimpleDateFormat;
\r
23 import java.util.ArrayList;
\r
24 import java.util.Date;
\r
25 import java.util.List;
\r
26 import java.util.concurrent.Executor;
\r
27 import java.util.concurrent.Executors;
\r
28 import java.util.concurrent.ThreadFactory;
\r
29 import java.util.concurrent.atomic.AtomicBoolean;
\r
30 import java.util.regex.Matcher;
\r
31 import java.util.regex.Pattern;
\r
33 import android.app.Activity;
\r
34 import android.app.Dialog;
\r
35 import android.app.ListActivity;
\r
36 import android.content.Context;
\r
37 import android.content.Intent;
\r
38 import android.content.SharedPreferences;
\r
39 import android.graphics.Typeface;
\r
40 import android.os.Bundle;
\r
41 import android.os.Handler;
\r
42 import android.preference.PreferenceManager;
\r
43 import android.text.ClipboardManager;
\r
44 import android.text.Editable;
\r
45 import android.text.Selection;
\r
46 import android.text.Spannable;
\r
47 import android.text.TextWatcher;
\r
48 import android.text.method.LinkMovementMethod;
\r
49 import android.text.style.StyleSpan;
\r
50 import android.util.Log;
\r
51 import android.util.TypedValue;
\r
52 import android.view.ContextMenu;
\r
53 import android.view.ContextMenu.ContextMenuInfo;
\r
54 import android.view.KeyEvent;
\r
55 import android.view.Menu;
\r
56 import android.view.MenuItem;
\r
57 import android.view.MenuItem.OnMenuItemClickListener;
\r
58 import android.view.MotionEvent;
\r
59 import android.view.View;
\r
60 import android.view.View.OnClickListener;
\r
61 import android.view.View.OnLongClickListener;
\r
62 import android.view.ViewGroup;
\r
63 import android.view.inputmethod.InputMethodManager;
\r
64 import android.widget.AdapterView;
\r
65 import android.widget.AdapterView.AdapterContextMenuInfo;
\r
66 import android.widget.BaseAdapter;
\r
67 import android.widget.Button;
\r
68 import android.widget.EditText;
\r
69 import android.widget.LinearLayout;
\r
70 import android.widget.ListAdapter;
\r
71 import android.widget.ListView;
\r
72 import android.widget.TableLayout;
\r
73 import android.widget.TableRow;
\r
74 import android.widget.TextView;
\r
75 import android.widget.Toast;
\r
77 import com.hughes.android.dictionary.engine.Dictionary;
\r
78 import com.hughes.android.dictionary.engine.Index;
\r
79 import com.hughes.android.dictionary.engine.PairEntry;
\r
80 import com.hughes.android.dictionary.engine.PairEntry.Pair;
\r
81 import com.hughes.android.dictionary.engine.RowBase;
\r
82 import com.hughes.android.dictionary.engine.TokenRow;
\r
83 import com.hughes.android.dictionary.engine.TransliteratorManager;
\r
84 import com.hughes.android.util.PersistentObjectCache;
\r
86 public class DictionaryActivity extends ListActivity {
\r
88 static final String LOG = "QuickDic";
\r
90 String dictFile = null;
\r
91 RandomAccessFile dictRaf = null;
\r
92 Dictionary dictionary = null;
\r
96 // package for test.
\r
97 final Handler uiHandler = new Handler();
\r
98 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
\r
100 public Thread newThread(Runnable r) {
\r
101 return new Thread(r, "searchExecutor");
\r
104 private SearchOperation currentSearchOperation = null;
\r
106 C.Theme theme = C.Theme.LIGHT;
\r
108 EditText searchText;
\r
112 private File wordList = null;
\r
113 private boolean saveOnlyFirstSubentry = false;
\r
114 private boolean clickOpensContextMenu = false;
\r
116 // Visible for testing.
\r
117 ListAdapter indexAdapter = null;
\r
119 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
\r
121 //private Vibrator vibrator = null;
\r
123 public DictionaryActivity() {
\r
126 public static Intent getIntent(final Context context, final int dictIndex, final int indexIndex, final String searchToken) {
\r
127 setDictionaryPrefs(context, dictIndex, indexIndex, searchToken);
\r
128 final Intent intent = new Intent();
\r
129 intent.setClassName(DictionaryActivity.class.getPackage().getName(), DictionaryActivity.class.getName());
\r
133 // TODO: Can we trigger an App restart when the preferences activity gets opened?
\r
134 // TODO: fix these...
\r
137 protected void onSaveInstanceState(final Bundle outState) {
\r
138 super.onSaveInstanceState(outState);
\r
139 setDictionaryPrefs(this, dictIndex, indexIndex, searchText.getText().toString());
\r
142 public static void setDictionaryPrefs(final Context context,
\r
143 final int dictIndex, final int indexIndex, final String searchToken) {
\r
144 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
\r
145 prefs.putInt(C.DICT_INDEX, dictIndex);
\r
146 prefs.putInt(C.INDEX_INDEX, indexIndex);
\r
147 prefs.putString(C.SEARCH_TOKEN, searchToken);
\r
151 public static void clearDictionaryPrefs(final Context context) {
\r
152 final SharedPreferences.Editor prefs = PreferenceManager
\r
153 .getDefaultSharedPreferences(context).edit();
\r
154 prefs.remove(C.DICT_INDEX);
\r
155 prefs.remove(C.INDEX_INDEX);
\r
156 prefs.remove(C.SEARCH_TOKEN);
\r
158 Log.d(LOG, "Removed default dictionary prefs.");
\r
162 public void onCreate(Bundle savedInstanceState) {
\r
163 Log.d(LOG, "onCreate:" + this);
\r
164 theme = ((DictionaryApplication)getApplication()).getSelectedTheme();
\r
165 super.onCreate(savedInstanceState);
\r
167 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
\r
170 PersistentObjectCache.init(this);
\r
171 QuickDicConfig quickDicConfig = PersistentObjectCache.init(
\r
172 this).read(C.DICTIONARY_CONFIGS, QuickDicConfig.class);
\r
173 dictIndex = prefs.getInt(C.DICT_INDEX, 0) ;
\r
174 final DictionaryInfo dictionaryConfig = quickDicConfig.dictionaryInfos.get(dictIndex);
\r
175 this.setTitle("QuickDic: " + dictionaryConfig.name);
\r
176 dictRaf = new RandomAccessFile(dictionaryConfig.localFile, "r");
\r
177 dictionary = new Dictionary(dictRaf);
\r
178 } catch (Exception e) {
\r
179 Log.e(LOG, "Unable to load dictionary.", e);
\r
180 if (dictRaf != null) {
\r
183 } catch (IOException e1) {
\r
184 Log.e(LOG, "Unable to close dictRaf.", e1);
\r
188 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()), Toast.LENGTH_LONG);
\r
189 startActivity(DictionaryManagerActivity.getIntent(this));
\r
194 indexIndex = prefs.getInt(C.INDEX_INDEX, 0) % dictionary.indices.size();
\r
195 Log.d(LOG, "Loading index.");
\r
196 index = dictionary.indices.get(indexIndex);
\r
197 setListAdapter(new IndexAdapter(index));
\r
199 // Pre-load the collators.
\r
200 searchExecutor.execute(new Runnable() {
\r
201 public void run() {
\r
202 final long startMillis = System.currentTimeMillis();
\r
204 TransliteratorManager.init(new TransliteratorManager.Callback() {
\r
206 public void onTransliteratorReady() {
\r
207 uiHandler.post(new Runnable() {
\r
209 public void run() {
\r
210 onSearchTextChange(searchText.getText().toString());
\r
216 for (final Index index : dictionary.indices) {
\r
217 Log.d(LOG, "Starting collator load for lang=" + index.sortLanguage.getIsoCode());
\r
219 final com.ibm.icu.text.Collator c = index.sortLanguage.getCollator();
\r
220 if (c.compare("pre-print", "preppy") >= 0) {
\r
221 Log.e(LOG, c.getClass()
\r
222 + " is buggy, lookups may not work properly.");
\r
225 Log.d(LOG, "Loading collators took:"
\r
226 + (System.currentTimeMillis() - startMillis));
\r
230 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "12");
\r
232 fontSizeSp = Integer.parseInt(fontSize);
\r
233 } catch (NumberFormatException e) {
\r
237 setContentView(R.layout.dictionary_activity);
\r
238 searchText = (EditText) findViewById(R.id.SearchText);
\r
239 searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
241 langButton = (Button) findViewById(R.id.LangButton);
\r
243 searchText.requestFocus();
\r
244 searchText.addTextChangedListener(searchTextWatcher);
\r
245 final String search = prefs.getString(C.SEARCH_TOKEN, "");
\r
246 searchText.setText(search);
\r
247 searchText.setSelection(0, search.length());
\r
248 Log.d(LOG, "Trying to restore searchText=" + search);
\r
250 final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
\r
251 clearSearchTextButton.setOnClickListener(new OnClickListener() {
\r
252 public void onClick(View v) {
\r
253 onClearSearchTextButton(clearSearchTextButton);
\r
256 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
\r
257 getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
\r
260 final Button langButton = (Button) findViewById(R.id.LangButton);
\r
261 langButton.setOnClickListener(new OnClickListener() {
\r
262 public void onClick(View v) {
\r
263 onLanguageButton();
\r
266 langButton.setOnLongClickListener(new OnLongClickListener() {
\r
268 public boolean onLongClick(View v) {
\r
269 onLanguageButtonLongClick();
\r
273 updateLangButton();
\r
275 final Button upButton = (Button) findViewById(R.id.UpButton);
\r
276 upButton.setOnClickListener(new OnClickListener() {
\r
277 public void onClick(View v) {
\r
278 onUpDownButton(true);
\r
281 final Button downButton = (Button) findViewById(R.id.DownButton);
\r
282 downButton.setOnClickListener(new OnClickListener() {
\r
283 public void onClick(View v) {
\r
284 onUpDownButton(false);
\r
288 getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
\r
290 public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
\r
292 if (!searchText.isFocused()) {
\r
293 // TODO: don't do this if multi words are entered.
\r
294 final RowBase row = (RowBase) getListAdapter().getItem(position);
\r
295 Log.d(LOG, "onItemSelected: " + row.index());
\r
296 final TokenRow tokenRow = row.getTokenRow(true);
\r
297 searchText.setText(tokenRow.getToken());
\r
302 public void onNothingSelected(AdapterView<?> arg0) {
\r
307 registerForContextMenu(getListView());
\r
310 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
\r
311 getString(R.string.wordListFileDefault)));
\r
312 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey), false);
\r
313 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey), false);
\r
314 //if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey), true)) {
\r
315 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
\r
317 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
\r
321 protected void onResume() {
\r
323 if (PreferenceActivity.prefsMightHaveChanged) {
\r
324 PreferenceActivity.prefsMightHaveChanged = false;
\r
326 startActivity(getIntent());
\r
331 protected void onPause() {
\r
336 protected void onDestroy() {
\r
338 if (dictRaf == null) {
\r
341 setDictionaryPrefs(this, dictIndex, indexIndex, searchText.getText().toString());
\r
343 // Before we close the RAF, we have to wind the current search down.
\r
344 if (currentSearchOperation != null) {
\r
345 Log.d(LOG, "Interrupting search to shut down.");
\r
346 final SearchOperation searchOperation = currentSearchOperation;
\r
347 currentSearchOperation = null;
\r
348 searchOperation.interrupted.set(true);
\r
349 synchronized (searchOperation) {
\r
350 while (!searchOperation.done) {
\r
352 searchOperation.wait();
\r
353 } catch (InterruptedException e) {
\r
354 Log.d(LOG, "Interrupted.", e);
\r
361 Log.d(LOG, "Closing RAF.");
\r
363 } catch (IOException e) {
\r
364 Log.e(LOG, "Failed to close dictionary", e);
\r
369 // --------------------------------------------------------------------------
\r
371 // --------------------------------------------------------------------------
\r
373 private void onClearSearchTextButton(final Button clearSearchTextButton) {
\r
374 clearSearchTextButton.requestFocus();
\r
375 searchText.setText("");
\r
376 searchText.requestFocus();
\r
377 Log.d(LOG, "Trying to show soft keyboard.");
\r
378 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
379 manager.showSoftInput(searchText, InputMethodManager.SHOW_FORCED);
\r
382 void updateLangButton() {
\r
383 langButton.setText(index.shortName);
\r
386 void onLanguageButton() {
\r
387 if (currentSearchOperation != null) {
\r
388 currentSearchOperation.interrupted.set(true);
\r
389 currentSearchOperation = null;
\r
392 changeIndex((indexIndex + 1)% dictionary.indices.size());
\r
393 onSearchTextChange(searchText.getText().toString());
\r
396 static class OpenIndexButton extends Button implements OnClickListener {
\r
398 final Activity activity;
\r
399 final int dictionaryIndex;
\r
400 final int indexIndex;
\r
402 public OpenIndexButton(final Context context, final Activity activity, final String text, final int dictionaryIndex, final int indexIndex) {
\r
404 this.activity = activity;
\r
405 this.dictionaryIndex = dictionaryIndex;
\r
406 this.indexIndex = indexIndex;
\r
407 setOnClickListener(this);
\r
408 setText(text, BufferType.NORMAL);
\r
412 public void onClick(View v) {
\r
414 getContext().startActivity(DictionaryActivity.getIntent(getContext(), dictionaryIndex, indexIndex, ""));
\r
419 void onLanguageButtonLongClick() {
\r
420 Context mContext = getApplicationContext();
\r
421 Dialog dialog = new Dialog(mContext);
\r
423 dialog.setContentView(R.layout.select_dictionary_dialog);
\r
424 dialog.setTitle(R.string.selectADictionary);
\r
426 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
\r
428 QuickDicConfig quickDicConfig = PersistentObjectCache.init(
\r
429 this).read(C.DICTIONARY_CONFIGS, QuickDicConfig.class);
\r
430 final List<DictionaryInfo> dictionaryInfos = new ArrayList<DictionaryInfo>();
\r
431 for (final DictionaryInfo dictionaryInfo : quickDicConfig.dictionaryInfos) {
\r
432 if (new File(dictionaryInfo.localFile).canRead()) {
\r
433 dictionaryInfos.add(dictionaryInfo);
\r
436 listView.setAdapter(new BaseAdapter() {
\r
439 public View getView(int position, View convertView, ViewGroup parent) {
\r
440 final LinearLayout result = new LinearLayout(parent.getContext());
\r
441 result.addView(new Butt)
\r
445 public long getItemId(int position) {
\r
450 public Object getItem(int position) {
\r
451 return dictionaryInfos.get(position);
\r
455 public int getCount() {
\r
456 return dictionaryInfos.size();
\r
462 private void changeIndex(final int newIndex) {
\r
463 indexIndex = newIndex;
\r
464 index = dictionary.indices.get(indexIndex);
\r
465 indexAdapter = new IndexAdapter(index);
\r
466 Log.d(LOG, "changingIndex, newLang=" + index.longName);
\r
467 setListAdapter(indexAdapter);
\r
468 updateLangButton();
\r
471 void onUpDownButton(final boolean up) {
\r
472 final int firstVisibleRow = getListView().getFirstVisiblePosition();
\r
473 final RowBase row = index.rows.get(firstVisibleRow);
\r
474 final TokenRow tokenRow = row.getTokenRow(true);
\r
475 final int destIndexEntry;
\r
477 if (row != tokenRow) {
\r
478 destIndexEntry = tokenRow.referenceIndex;
\r
480 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
\r
484 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
\r
486 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
\r
487 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
\r
488 searchText.removeTextChangedListener(searchTextWatcher);
\r
489 searchText.setText(dest.token);
\r
490 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
\r
491 searchText.addTextChangedListener(searchTextWatcher);
\r
494 // --------------------------------------------------------------------------
\r
496 // --------------------------------------------------------------------------
\r
499 public boolean onCreateOptionsMenu(final Menu menu) {
\r
502 final MenuItem preferences = menu.add(getString(R.string.preferences));
\r
503 preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
504 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
505 PreferenceActivity.prefsMightHaveChanged = true;
\r
506 startActivity(new Intent(DictionaryActivity.this,
\r
507 PreferenceActivity.class));
\r
514 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
\r
515 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
516 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
517 startActivity(DictionaryManagerActivity.getIntent(DictionaryActivity.this));
\r
525 final MenuItem about = menu.add(getString(R.string.about));
\r
526 about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
527 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
528 final Intent intent = new Intent().setClassName(AboutActivity.class
\r
529 .getPackage().getName(), AboutActivity.class.getCanonicalName());
\r
530 startActivity(intent);
\r
540 // --------------------------------------------------------------------------
\r
541 // Context Menu + clicks
\r
542 // --------------------------------------------------------------------------
\r
545 public void onCreateContextMenu(ContextMenu menu, View v,
\r
546 ContextMenuInfo menuInfo) {
\r
547 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
\r
548 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
\r
550 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList, wordList.getName()));
\r
551 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
552 public boolean onMenuItemClick(MenuItem item) {
\r
553 onAppendToWordList(row);
\r
558 final MenuItem copy = menu.add(android.R.string.copy);
\r
559 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
560 public boolean onMenuItemClick(MenuItem item) {
\r
566 if (selectedSpannableText != null) {
\r
567 final String selectedText = selectedSpannableText;
\r
568 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection, selectedSpannableText));
\r
569 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
570 public boolean onMenuItemClick(MenuItem item) {
\r
571 if (indexIndex != selectedSpannableIndex) {
\r
572 changeIndex(selectedSpannableIndex);
\r
574 searchText.setText(selectedText);
\r
584 protected void onListItemClick(ListView l, View v, int row, long id) {
\r
585 defocusSearchText();
\r
587 if (clickOpensContextMenu && dictRaf != null) {
\r
588 openContextMenu(v);
\r
592 void onAppendToWordList(final RowBase row) {
\r
593 defocusSearchText();
\r
595 final StringBuilder rawText = new StringBuilder();
\r
597 new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date()))
\r
599 rawText.append(index.longName).append("\t");
\r
600 rawText.append(row.getTokenRow(true).getToken()).append("\t");
\r
601 rawText.append(row.getRawText(saveOnlyFirstSubentry));
\r
602 Log.d(LOG, "Writing : " + rawText);
\r
605 wordList.getParentFile().mkdirs();
\r
606 final PrintWriter out = new PrintWriter(
\r
607 new FileWriter(wordList, true));
\r
608 out.println(rawText.toString());
\r
610 } catch (IOException e) {
\r
611 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
\r
612 Toast.makeText(this, getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()), Toast.LENGTH_LONG);
\r
618 * Called when user clicks outside of search text, so that they can start
\r
619 * typing again immediately.
\r
621 void defocusSearchText() {
\r
622 //Log.d(LOG, "defocusSearchText");
\r
623 // Request focus so that if we start typing again, it clears the text input.
\r
624 getListView().requestFocus();
\r
626 // Visual indication that a new keystroke will clear the search text.
\r
627 searchText.selectAll();
\r
630 void onCopy(final RowBase row) {
\r
631 defocusSearchText();
\r
633 Log.d(LOG, "Copy, row=" + row);
\r
634 final StringBuilder result = new StringBuilder();
\r
635 result.append(row.getRawText(false));
\r
636 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
\r
637 clipboardManager.setText(result.toString());
\r
638 Log.d(LOG, "Copied: " + result);
\r
642 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
\r
643 if (event.getUnicodeChar() != 0) {
\r
644 if (!searchText.hasFocus()) {
\r
645 searchText.setText("" + (char) event.getUnicodeChar());
\r
646 onSearchTextChange(searchText.getText().toString());
\r
647 searchText.requestFocus();
\r
648 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
\r
652 if (keyCode == KeyEvent.KEYCODE_BACK) {
\r
653 Log.d(LOG, "Clearing dictionary prefs.");
\r
654 DictionaryActivity.clearDictionaryPrefs(this);
\r
656 if (keyCode == KeyEvent.KEYCODE_ENTER) {
\r
657 Log.d(LOG, "Trying to hide soft keyboard.");
\r
658 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
659 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
\r
662 return super.onKeyDown(keyCode, event);
\r
666 // --------------------------------------------------------------------------
\r
668 // --------------------------------------------------------------------------
\r
670 private void searchFinished(final SearchOperation searchOperation) {
\r
671 if (searchOperation.interrupted.get()) {
\r
672 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
\r
675 if (searchOperation != this.currentSearchOperation) {
\r
676 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
\r
680 final Index.IndexEntry searchResult = searchOperation.searchResult;
\r
681 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
\r
683 currentSearchOperation = null;
\r
685 uiHandler.postDelayed(new Runnable() {
\r
687 public void run() {
\r
688 if (currentSearchOperation == null) {
\r
689 jumpToRow(searchResult.startRow);
\r
691 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
\r
696 // if (!searchResult.success) {
\r
697 // if (vibrator != null) {
\r
698 // vibrator.vibrate(VIBRATE_MILLIS);
\r
700 // searchText.setText(searchResult.longestPrefixString);
\r
701 // searchText.setSelection(searchResult.longestPrefixString.length());
\r
707 private final void jumpToRow(final int row) {
\r
709 getListView().setSelected(true);
\r
712 final class SearchOperation implements Runnable {
\r
714 final AtomicBoolean interrupted = new AtomicBoolean(false);
\r
715 final String searchText;
\r
718 long searchStartMillis;
\r
720 Index.IndexEntry searchResult;
\r
722 boolean done = false;
\r
724 SearchOperation(final String searchText, final Index index) {
\r
725 this.searchText = searchText.trim();
\r
726 this.index = index;
\r
729 public String toString() {
\r
730 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
\r
734 public void run() {
\r
736 searchStartMillis = System.currentTimeMillis();
\r
737 searchResult = index.findInsertionPoint(searchText, interrupted);
\r
738 Log.d(LOG, "searchText=" + searchText + ", searchDuration="
\r
739 + (System.currentTimeMillis() - searchStartMillis) + ", interrupted="
\r
740 + interrupted.get());
\r
741 if (!interrupted.get()) {
\r
742 uiHandler.post(new Runnable() {
\r
744 public void run() {
\r
745 searchFinished(SearchOperation.this);
\r
750 synchronized (this) {
\r
759 // --------------------------------------------------------------------------
\r
761 // --------------------------------------------------------------------------
\r
763 final class IndexAdapter extends BaseAdapter {
\r
767 IndexAdapter(final Index index) {
\r
768 this.index = index;
\r
772 public int getCount() {
\r
773 return index.rows.size();
\r
777 public RowBase getItem(int position) {
\r
778 return index.rows.get(position);
\r
782 public long getItemId(int position) {
\r
783 return getItem(position).index();
\r
787 public View getView(int position, final View convertView, ViewGroup parent) {
\r
788 final RowBase row = index.rows.get(position);
\r
789 if (row instanceof PairEntry.Row) {
\r
790 return getView((PairEntry.Row) row, parent, convertView);
\r
791 } else if (row instanceof TokenRow) {
\r
792 return getView((TokenRow) row, parent, convertView);
\r
794 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
\r
798 private View getView(PairEntry.Row row, ViewGroup parent, final View convertView) {
\r
799 final TableLayout result = new TableLayout(parent.getContext());
\r
800 final PairEntry entry = row.getEntry();
\r
801 final int rowCount = entry.pairs.size();
\r
802 for (int r = 0; r < rowCount; ++r) {
\r
803 final TableRow tableRow = new TableRow(result.getContext());
\r
805 final TextView col1 = new TextView(tableRow.getContext());
\r
806 final TextView col2 = new TextView(tableRow.getContext());
\r
807 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
\r
808 layoutParams.weight = 0.5f;
\r
810 // Set the columns in the table.
\r
812 final TextView bullet = new TextView(tableRow.getContext());
\r
813 bullet.setText(" • ");
\r
814 tableRow.addView(bullet);
\r
816 tableRow.addView(col1, layoutParams);
\r
817 final TextView margin = new TextView(tableRow.getContext());
\r
818 margin.setText(" ");
\r
819 tableRow.addView(margin);
\r
821 final TextView bullet = new TextView(tableRow.getContext());
\r
822 bullet.setText(" • ");
\r
823 tableRow.addView(bullet);
\r
825 tableRow.addView(col2, layoutParams);
\r
829 // Set what's in the columns.
\r
831 // TODO: color words by gender
\r
832 final Pair pair = entry.pairs.get(r);
\r
833 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
\r
834 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
\r
836 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
\r
837 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
\r
839 // Bold the token instances in col1.
\r
840 final Spannable col1Spannable = (Spannable) col1.getText();
\r
842 final String token = row.getTokenRow(true).getToken();
\r
843 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
\r
844 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos,
\r
845 startPos + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
846 startPos += token.length();
\r
849 createTokenLinkSpans(col1, col1Spannable, col1Text);
\r
850 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
\r
852 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
853 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
854 // col2.setBackgroundResource(theme.otherLangBg);
\r
856 if (index.swapPairEntries) {
\r
857 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
858 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
860 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
861 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
864 result.addView(tableRow);
\r
870 // final WebView result = (WebView) (convertView instanceof WebView ? convertView : new WebView(parent.getContext()));
\r
872 // final PairEntry entry = row.getEntry();
\r
873 // final int rowCount = entry.pairs.size();
\r
874 // final StringBuilder html = new StringBuilder();
\r
875 // html.append("<html><body><table width=\"100%\">");
\r
876 // for (int r = 0; r < rowCount; ++r) {
\r
877 // html.append("<tr>");
\r
879 // final Pair pair = entry.pairs.get(r);
\r
880 // // TODO: escape both the token and the text.
\r
881 // final String token = row.getTokenRow(true).getToken();
\r
882 // final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
\r
883 // final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
\r
885 // col1Text.replaceAll(token, String.format("<b>%s</b>", token));
\r
888 // html.append("<td width=\"50%\">");
\r
890 // html.append("<li>");
\r
892 // html.append(col1Text);
\r
893 // html.append("</td>");
\r
896 // html.append("<td width=\"50%\">");
\r
898 // html.append("<li>");
\r
900 // html.append(col2Text);
\r
901 // html.append("</td>");
\r
903 //// column1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
904 //// column2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
906 // html.append("</tr>");
\r
908 // html.append("</table></body></html>");
\r
910 // Log.i(LOG, html.toString());
\r
912 // result.getSettings().setRenderPriority(RenderPriority.HIGH);
\r
913 // result.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
\r
915 // result.loadData("<html><body><table><tr><td>line (connected series of public conveyances, and hence, an established arrangement for forwarding merchandise, etc.) (noun)</td><td>verbinding</td></tr></table></body></html>", "text/html", "utf-8");
\r
920 private View getView(TokenRow row, ViewGroup parent, final View convertView) {
\r
921 final Context context = parent.getContext();
\r
922 final TextView textView = new TextView(context);
\r
923 textView.setText(row.getToken());
\r
924 textView.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg : theme.tokenRowOtherBg);
\r
926 //textView.setTextColor(android.R.color.secondary_text_light);
\r
927 textView.setTextAppearance(context, theme.tokenRowFg);
\r
928 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
\r
934 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}0-9]+");
\r
936 private void createTokenLinkSpans(final TextView textView, final Spannable spannable, final String text) {
\r
937 // Saw from the source code that LinkMovementMethod sets the selection!
\r
938 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
\r
939 textView.setMovementMethod(LinkMovementMethod.getInstance());
\r
940 final Matcher matcher = CHAR_DASH.matcher(text);
\r
941 while (matcher.find()) {
\r
942 spannable.setSpan(new MyClickableSpan(), matcher.start(), matcher.end(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
947 String selectedSpannableText = null;
\r
948 int selectedSpannableIndex = -1;
\r
951 public boolean onTouchEvent(MotionEvent event) {
\r
952 selectedSpannableText = null;
\r
953 selectedSpannableIndex = -1;
\r
954 return super.onTouchEvent(event);
\r
957 private class TextViewLongClickListener implements OnLongClickListener {
\r
960 private TextViewLongClickListener(final int index) {
\r
961 this.index = index;
\r
965 public boolean onLongClick(final View v) {
\r
966 final TextView textView = (TextView) v;
\r
967 final int start = textView.getSelectionStart();
\r
968 final int end = textView.getSelectionEnd();
\r
969 if (start >= 0 && end >= 0) {
\r
970 selectedSpannableText = textView.getText().subSequence(start, end).toString();
\r
971 selectedSpannableIndex = index;
\r
976 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(0);
\r
977 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(1);
\r
980 // --------------------------------------------------------------------------
\r
982 // --------------------------------------------------------------------------
\r
984 void onSearchTextChange(final String text) {
\r
985 if (dictRaf == null) {
\r
986 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
\r
989 if (!searchText.isFocused()) {
\r
990 Log.d(LOG, "searchText changed without focus, doing nothing.");
\r
993 Log.d(LOG, "onSearchTextChange: " + text);
\r
994 if (currentSearchOperation != null) {
\r
995 Log.d(LOG, "Interrupting currentSearchOperation.");
\r
996 currentSearchOperation.interrupted.set(true);
\r
998 currentSearchOperation = new SearchOperation(text, index);
\r
999 searchExecutor.execute(currentSearchOperation);
\r
1002 private class SearchTextWatcher implements TextWatcher {
\r
1003 public void afterTextChanged(final Editable searchTextEditable) {
\r
1004 if (searchText.hasFocus()) {
\r
1005 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
\r
1006 // If they were typing to cause the change, update the UI.
\r
1007 onSearchTextChange(searchText.getText().toString());
\r
1011 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
\r
1015 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
\r