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.Date;
\r
24 import java.util.List;
\r
25 import java.util.concurrent.Executor;
\r
26 import java.util.concurrent.Executors;
\r
27 import java.util.concurrent.ThreadFactory;
\r
28 import java.util.concurrent.atomic.AtomicBoolean;
\r
29 import java.util.regex.Matcher;
\r
30 import java.util.regex.Pattern;
\r
32 import android.app.Activity;
\r
33 import android.app.Dialog;
\r
34 import android.app.ListActivity;
\r
35 import android.content.Context;
\r
36 import android.content.Intent;
\r
37 import android.content.SharedPreferences;
\r
38 import android.graphics.Typeface;
\r
39 import android.os.Bundle;
\r
40 import android.os.Handler;
\r
41 import android.preference.PreferenceManager;
\r
42 import android.text.ClipboardManager;
\r
43 import android.text.Editable;
\r
44 import android.text.Selection;
\r
45 import android.text.Spannable;
\r
46 import android.text.TextWatcher;
\r
47 import android.text.method.LinkMovementMethod;
\r
48 import android.text.style.StyleSpan;
\r
49 import android.util.Log;
\r
50 import android.util.TypedValue;
\r
51 import android.view.ContextMenu;
\r
52 import android.view.ContextMenu.ContextMenuInfo;
\r
53 import android.view.KeyEvent;
\r
54 import android.view.Menu;
\r
55 import android.view.MenuItem;
\r
56 import android.view.MenuItem.OnMenuItemClickListener;
\r
57 import android.view.MotionEvent;
\r
58 import android.view.View;
\r
59 import android.view.View.OnClickListener;
\r
60 import android.view.View.OnLongClickListener;
\r
61 import android.view.ViewGroup;
\r
62 import android.view.inputmethod.InputMethodManager;
\r
63 import android.widget.AdapterView;
\r
64 import android.widget.AdapterView.AdapterContextMenuInfo;
\r
65 import android.widget.BaseAdapter;
\r
66 import android.widget.Button;
\r
67 import android.widget.EditText;
\r
68 import android.widget.LinearLayout;
\r
69 import android.widget.ListAdapter;
\r
70 import android.widget.ListView;
\r
71 import android.widget.TableLayout;
\r
72 import android.widget.TableRow;
\r
73 import android.widget.TextView;
\r
74 import android.widget.Toast;
\r
76 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
\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.IntentLauncher;
\r
85 import com.hughes.android.util.NonLinkClickableSpan;
\r
87 public class DictionaryActivity extends ListActivity {
\r
89 static final String LOG = "QuickDic";
\r
91 DictionaryApplication application;
\r
92 File dictFile = null;
\r
93 RandomAccessFile dictRaf = null;
\r
94 Dictionary dictionary = null;
\r
98 // package for test.
\r
99 final Handler uiHandler = new Handler();
\r
100 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
\r
102 public Thread newThread(Runnable r) {
\r
103 return new Thread(r, "searchExecutor");
\r
106 private SearchOperation currentSearchOperation = null;
\r
108 C.Theme theme = C.Theme.LIGHT;
\r
110 EditText searchText;
\r
114 private File wordList = null;
\r
115 private boolean saveOnlyFirstSubentry = false;
\r
116 private boolean clickOpensContextMenu = false;
\r
118 // Visible for testing.
\r
119 ListAdapter indexAdapter = null;
\r
121 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
\r
123 public DictionaryActivity() {
\r
126 public static Intent getLaunchIntent(final File dictFile, final int indexIndex, final String searchToken) {
\r
127 final Intent intent = new Intent();
\r
128 intent.setClassName(DictionaryActivity.class.getPackage().getName(), DictionaryActivity.class.getName());
\r
129 intent.putExtra(C.DICT_FILE, dictFile.getPath());
\r
130 intent.putExtra(C.INDEX_INDEX, indexIndex);
\r
131 intent.putExtra(C.SEARCH_TOKEN, searchToken);
\r
136 protected void onSaveInstanceState(final Bundle outState) {
\r
137 super.onSaveInstanceState(outState);
\r
138 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
\r
142 protected void onRestoreInstanceState(final Bundle outState) {
\r
143 super.onRestoreInstanceState(outState);
\r
144 setSearchText(outState.getString(C.SEARCH_TOKEN));
\r
148 public void onCreate(Bundle savedInstanceState) {
\r
149 Log.d(LOG, "onCreate:" + this);
\r
150 super.onCreate(savedInstanceState);
\r
152 application = (DictionaryApplication) getApplication();
\r
153 theme = application.getSelectedTheme();
\r
155 // Clear them so that if something goes wrong, we won't relaunch.
\r
156 clearDictionaryPrefs(this);
\r
158 final Intent intent = getIntent();
\r
159 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
\r
162 final String name = application.getDictionaryName(dictFile.getName());
\r
163 this.setTitle("QuickDic: " + name);
\r
164 dictRaf = new RandomAccessFile(dictFile, "r");
\r
165 dictionary = new Dictionary(dictRaf);
\r
166 } catch (Exception e) {
\r
167 Log.e(LOG, "Unable to load dictionary.", e);
\r
168 if (dictRaf != null) {
\r
171 } catch (IOException e1) {
\r
172 Log.e(LOG, "Unable to close dictRaf.", e1);
\r
176 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()), Toast.LENGTH_LONG);
\r
177 startActivity(DictionaryManagerActivity.getLaunchIntent());
\r
182 Log.d(LOG, "Loading index.");
\r
183 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0) % dictionary.indices.size();
\r
184 index = dictionary.indices.get(indexIndex);
\r
185 setListAdapter(new IndexAdapter(index));
\r
187 // Pre-load the collators.
\r
188 searchExecutor.execute(new Runnable() {
\r
189 public void run() {
\r
190 final long startMillis = System.currentTimeMillis();
\r
192 TransliteratorManager.init(new TransliteratorManager.Callback() {
\r
194 public void onTransliteratorReady() {
\r
195 uiHandler.post(new Runnable() {
\r
197 public void run() {
\r
198 onSearchTextChange(searchText.getText().toString());
\r
204 for (final Index index : dictionary.indices) {
\r
205 Log.d(LOG, "Starting collator load for lang=" + index.sortLanguage.getIsoCode());
\r
207 final com.ibm.icu.text.Collator c = index.sortLanguage.getCollator();
\r
208 if (c.compare("pre-print", "preppy") >= 0) {
\r
209 Log.e(LOG, c.getClass()
\r
210 + " is buggy, lookups may not work properly.");
\r
213 Log.d(LOG, "Loading collators took:"
\r
214 + (System.currentTimeMillis() - startMillis));
\r
218 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
\r
220 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
\r
222 fontSizeSp = Integer.parseInt(fontSize.trim());
\r
223 } catch (NumberFormatException e) {
\r
227 setContentView(R.layout.dictionary_activity);
\r
228 searchText = (EditText) findViewById(R.id.SearchText);
\r
229 searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
231 langButton = (Button) findViewById(R.id.LangButton);
\r
233 searchText.requestFocus();
\r
234 searchText.addTextChangedListener(searchTextWatcher);
\r
235 final String search = prefs.getString(C.SEARCH_TOKEN, "");
\r
236 searchText.setText(search);
\r
237 searchText.setSelection(0, search.length());
\r
238 Log.d(LOG, "Trying to restore searchText=" + search);
\r
240 final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
\r
241 clearSearchTextButton.setOnClickListener(new OnClickListener() {
\r
242 public void onClick(View v) {
\r
243 onClearSearchTextButton(clearSearchTextButton);
\r
246 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
\r
247 getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
\r
250 final Button langButton = (Button) findViewById(R.id.LangButton);
\r
251 langButton.setOnClickListener(new OnClickListener() {
\r
252 public void onClick(View v) {
\r
253 onLanguageButton();
\r
256 langButton.setOnLongClickListener(new OnLongClickListener() {
\r
258 public boolean onLongClick(View v) {
\r
259 onLanguageButtonLongClick(v.getContext());
\r
263 updateLangButton();
\r
265 final Button upButton = (Button) findViewById(R.id.UpButton);
\r
266 upButton.setOnClickListener(new OnClickListener() {
\r
267 public void onClick(View v) {
\r
268 onUpDownButton(true);
\r
271 final Button downButton = (Button) findViewById(R.id.DownButton);
\r
272 downButton.setOnClickListener(new OnClickListener() {
\r
273 public void onClick(View v) {
\r
274 onUpDownButton(false);
\r
278 getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
\r
280 public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
\r
282 if (!searchText.isFocused()) {
\r
283 // TODO: don't do this if multi words are entered.
\r
284 final RowBase row = (RowBase) getListAdapter().getItem(position);
\r
285 Log.d(LOG, "onItemSelected: " + row.index());
\r
286 final TokenRow tokenRow = row.getTokenRow(true);
\r
287 searchText.setText(tokenRow.getToken());
\r
292 public void onNothingSelected(AdapterView<?> arg0) {
\r
297 registerForContextMenu(getListView());
\r
300 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
\r
301 getString(R.string.wordListFileDefault)));
\r
302 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey), false);
\r
303 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey), false);
\r
304 //if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey), true)) {
\r
305 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
\r
307 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
\r
309 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
\r
313 protected void onResume() {
\r
315 if (PreferenceActivity.prefsMightHaveChanged) {
\r
316 PreferenceActivity.prefsMightHaveChanged = false;
\r
318 startActivity(getIntent());
\r
323 protected void onPause() {
\r
327 private static void setDictionaryPrefs(final Context context,
\r
328 final File dictFile, final int indexIndex, final String searchToken) {
\r
329 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
\r
330 prefs.putString(C.DICT_FILE, dictFile.getPath());
\r
331 prefs.putInt(C.INDEX_INDEX, indexIndex);
\r
332 prefs.putString(C.SEARCH_TOKEN, searchToken);
\r
336 private static void clearDictionaryPrefs(final Context context) {
\r
337 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
\r
338 prefs.remove(C.DICT_FILE);
\r
339 prefs.remove(C.INDEX_INDEX);
\r
340 prefs.remove(C.SEARCH_TOKEN);
\r
346 protected void onDestroy() {
\r
348 if (dictRaf == null) {
\r
352 // Before we close the RAF, we have to wind the current search down.
\r
353 if (currentSearchOperation != null) {
\r
354 Log.d(LOG, "Interrupting search to shut down.");
\r
355 final SearchOperation searchOperation = currentSearchOperation;
\r
356 currentSearchOperation = null;
\r
357 searchOperation.interrupted.set(true);
\r
358 synchronized (searchOperation) {
\r
359 while (!searchOperation.done) {
\r
361 searchOperation.wait();
\r
362 } catch (InterruptedException e) {
\r
363 Log.d(LOG, "Interrupted.", e);
\r
370 Log.d(LOG, "Closing RAF.");
\r
372 } catch (IOException e) {
\r
373 Log.e(LOG, "Failed to close dictionary", e);
\r
378 // --------------------------------------------------------------------------
\r
380 // --------------------------------------------------------------------------
\r
382 private void onClearSearchTextButton(final Button clearSearchTextButton) {
\r
383 clearSearchTextButton.requestFocus();
\r
384 searchText.setText("");
\r
385 searchText.requestFocus();
\r
386 Log.d(LOG, "Trying to show soft keyboard.");
\r
387 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
388 manager.showSoftInput(searchText, InputMethodManager.SHOW_FORCED);
\r
391 void updateLangButton() {
\r
392 langButton.setText(index.shortName);
\r
395 void onLanguageButton() {
\r
396 if (currentSearchOperation != null) {
\r
397 currentSearchOperation.interrupted.set(true);
\r
398 currentSearchOperation = null;
\r
400 changeIndex((indexIndex + 1)% dictionary.indices.size());
\r
403 static class OpenIndexButton extends Button implements OnClickListener {
\r
405 final Activity activity;
\r
406 final Intent intent;
\r
408 public OpenIndexButton(final Context context, final Activity activity, final String text, final Intent intent) {
\r
410 this.activity = activity;
\r
411 this.intent = intent;
\r
412 setOnClickListener(this);
\r
413 setText(text, BufferType.NORMAL);
\r
417 public void onClick(View v) {
\r
419 getContext().startActivity(intent);
\r
424 void onLanguageButtonLongClick(final Context context) {
\r
425 final Dialog dialog = new Dialog(context);
\r
426 dialog.setContentView(R.layout.select_dictionary_dialog);
\r
427 dialog.setTitle(R.string.selectDictionary);
\r
429 final List<DictionaryInfo> installedDicts = ((DictionaryApplication)getApplication()).getUsableDicts();
\r
430 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
\r
431 listView.setAdapter(new BaseAdapter() {
\r
433 public View getView(int position, View convertView, ViewGroup parent) {
\r
434 final LinearLayout result = new LinearLayout(parent.getContext());
\r
435 final DictionaryInfo dictionaryInfo = getItem(position);
\r
436 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
\r
437 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
\r
438 final Button button = new Button(parent.getContext());
\r
439 String name = application.getLanguageName(indexInfo.shortName);
\r
440 if (name == null) {
\r
441 name = indexInfo.shortName;
\r
443 button.setText(name);
\r
444 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(), getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename), i, "")) {
\r
446 protected void onGo() {
\r
448 DictionaryActivity.this.finish();
\r
451 button.setOnClickListener(intentLauncher);
\r
453 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
\r
454 layoutParams.width = 0;
\r
455 layoutParams.weight = 1.0f;
\r
456 button.setLayoutParams(layoutParams);
\r
458 result.addView(button);
\r
464 public long getItemId(int position) {
\r
469 public DictionaryInfo getItem(int position) {
\r
470 return installedDicts.get(position);
\r
474 public int getCount() {
\r
475 return installedDicts.size();
\r
483 private void changeIndex(final int newIndex) {
\r
484 indexIndex = newIndex;
\r
485 index = dictionary.indices.get(indexIndex);
\r
486 indexAdapter = new IndexAdapter(index);
\r
487 Log.d(LOG, "changingIndex, newLang=" + index.longName);
\r
488 setListAdapter(indexAdapter);
\r
489 updateLangButton();
\r
490 searchText.requestFocus(); // Otherwise, nothing may happen.
\r
491 onSearchTextChange(searchText.getText().toString());
\r
494 void onUpDownButton(final boolean up) {
\r
495 final int firstVisibleRow = getListView().getFirstVisiblePosition();
\r
496 final RowBase row = index.rows.get(firstVisibleRow);
\r
497 final TokenRow tokenRow = row.getTokenRow(true);
\r
498 final int destIndexEntry;
\r
500 if (row != tokenRow) {
\r
501 destIndexEntry = tokenRow.referenceIndex;
\r
503 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
\r
507 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
\r
509 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
\r
510 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
\r
511 searchText.removeTextChangedListener(searchTextWatcher);
\r
512 searchText.setText(dest.token);
\r
513 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
\r
514 searchText.addTextChangedListener(searchTextWatcher);
\r
517 // --------------------------------------------------------------------------
\r
519 // --------------------------------------------------------------------------
\r
522 public boolean onCreateOptionsMenu(final Menu menu) {
\r
523 application.onCreateGlobalOptionsMenu(this, menu);
\r
526 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
\r
527 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
528 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
529 startActivity(DictionaryManagerActivity.getLaunchIntent());
\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 setSearchText(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 setSearchText("" + (char) event.getUnicodeChar());
\r
649 if (keyCode == KeyEvent.KEYCODE_BACK) {
\r
650 Log.d(LOG, "Clearing dictionary prefs.");
\r
651 DictionaryActivity.clearDictionaryPrefs(this);
\r
653 if (keyCode == KeyEvent.KEYCODE_ENTER) {
\r
654 Log.d(LOG, "Trying to hide soft keyboard.");
\r
655 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
656 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
\r
659 return super.onKeyDown(keyCode, event);
\r
662 private void setSearchText(final String text) {
\r
663 searchText.setText(text);
\r
664 searchText.requestFocus();
\r
665 onSearchTextChange(searchText.getText().toString());
\r
666 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
\r
670 // --------------------------------------------------------------------------
\r
672 // --------------------------------------------------------------------------
\r
674 private void searchFinished(final SearchOperation searchOperation) {
\r
675 if (searchOperation.interrupted.get()) {
\r
676 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
\r
679 if (searchOperation != this.currentSearchOperation) {
\r
680 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
\r
684 final Index.IndexEntry searchResult = searchOperation.searchResult;
\r
685 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
\r
687 currentSearchOperation = null;
\r
689 uiHandler.postDelayed(new Runnable() {
\r
691 public void run() {
\r
692 if (currentSearchOperation == null) {
\r
693 jumpToRow(searchResult.startRow);
\r
695 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
\r
700 // if (!searchResult.success) {
\r
701 // if (vibrator != null) {
\r
702 // vibrator.vibrate(VIBRATE_MILLIS);
\r
704 // searchText.setText(searchResult.longestPrefixString);
\r
705 // searchText.setSelection(searchResult.longestPrefixString.length());
\r
711 private final void jumpToRow(final int row) {
\r
713 getListView().setSelected(true);
\r
716 final class SearchOperation implements Runnable {
\r
718 final AtomicBoolean interrupted = new AtomicBoolean(false);
\r
719 final String searchText;
\r
722 long searchStartMillis;
\r
724 Index.IndexEntry searchResult;
\r
726 boolean done = false;
\r
728 SearchOperation(final String searchText, final Index index) {
\r
729 this.searchText = searchText.trim();
\r
730 this.index = index;
\r
733 public String toString() {
\r
734 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
\r
738 public void run() {
\r
740 searchStartMillis = System.currentTimeMillis();
\r
741 searchResult = index.findInsertionPoint(searchText, interrupted);
\r
742 Log.d(LOG, "searchText=" + searchText + ", searchDuration="
\r
743 + (System.currentTimeMillis() - searchStartMillis) + ", interrupted="
\r
744 + interrupted.get());
\r
745 if (!interrupted.get()) {
\r
746 uiHandler.post(new Runnable() {
\r
748 public void run() {
\r
749 searchFinished(SearchOperation.this);
\r
754 synchronized (this) {
\r
763 // --------------------------------------------------------------------------
\r
765 // --------------------------------------------------------------------------
\r
767 final class IndexAdapter extends BaseAdapter {
\r
771 IndexAdapter(final Index index) {
\r
772 this.index = index;
\r
776 public int getCount() {
\r
777 return index.rows.size();
\r
781 public RowBase getItem(int position) {
\r
782 return index.rows.get(position);
\r
786 public long getItemId(int position) {
\r
787 return getItem(position).index();
\r
791 public View getView(int position, final View convertView, ViewGroup parent) {
\r
792 final RowBase row = index.rows.get(position);
\r
793 if (row instanceof PairEntry.Row) {
\r
794 return getView((PairEntry.Row) row, parent, convertView);
\r
795 } else if (row instanceof TokenRow) {
\r
796 return getView((TokenRow) row, parent, convertView);
\r
798 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
\r
802 private View getView(PairEntry.Row row, ViewGroup parent, final View convertView) {
\r
803 final TableLayout result = new TableLayout(parent.getContext());
\r
804 final PairEntry entry = row.getEntry();
\r
805 final int rowCount = entry.pairs.size();
\r
806 for (int r = 0; r < rowCount; ++r) {
\r
807 final TableRow tableRow = new TableRow(result.getContext());
\r
809 final TextView col1 = new TextView(tableRow.getContext());
\r
810 final TextView col2 = new TextView(tableRow.getContext());
\r
811 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
\r
812 layoutParams.weight = 0.5f;
\r
814 // Set the columns in the table.
\r
816 final TextView bullet = new TextView(tableRow.getContext());
\r
817 bullet.setText(" • ");
\r
818 tableRow.addView(bullet);
\r
820 tableRow.addView(col1, layoutParams);
\r
821 final TextView margin = new TextView(tableRow.getContext());
\r
822 margin.setText(" ");
\r
823 tableRow.addView(margin);
\r
825 final TextView bullet = new TextView(tableRow.getContext());
\r
826 bullet.setText(" • ");
\r
827 tableRow.addView(bullet);
\r
829 tableRow.addView(col2, layoutParams);
\r
833 // Set what's in the columns.
\r
835 // TODO: color words by gender
\r
836 final Pair pair = entry.pairs.get(r);
\r
837 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
\r
838 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
\r
840 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
\r
841 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
\r
843 // Bold the token instances in col1.
\r
844 final Spannable col1Spannable = (Spannable) col1.getText();
\r
846 final String token = row.getTokenRow(true).getToken();
\r
847 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
\r
848 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos,
\r
849 startPos + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
850 startPos += token.length();
\r
853 createTokenLinkSpans(col1, col1Spannable, col1Text);
\r
854 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
\r
856 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
857 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
858 // col2.setBackgroundResource(theme.otherLangBg);
\r
860 if (index.swapPairEntries) {
\r
861 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
862 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
864 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
865 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
868 result.addView(tableRow);
\r
874 // final WebView result = (WebView) (convertView instanceof WebView ? convertView : new WebView(parent.getContext()));
\r
876 // final PairEntry entry = row.getEntry();
\r
877 // final int rowCount = entry.pairs.size();
\r
878 // final StringBuilder html = new StringBuilder();
\r
879 // html.append("<html><body><table width=\"100%\">");
\r
880 // for (int r = 0; r < rowCount; ++r) {
\r
881 // html.append("<tr>");
\r
883 // final Pair pair = entry.pairs.get(r);
\r
884 // // TODO: escape both the token and the text.
\r
885 // final String token = row.getTokenRow(true).getToken();
\r
886 // final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
\r
887 // final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
\r
889 // col1Text.replaceAll(token, String.format("<b>%s</b>", token));
\r
892 // html.append("<td width=\"50%\">");
\r
894 // html.append("<li>");
\r
896 // html.append(col1Text);
\r
897 // html.append("</td>");
\r
900 // html.append("<td width=\"50%\">");
\r
902 // html.append("<li>");
\r
904 // html.append(col2Text);
\r
905 // html.append("</td>");
\r
907 //// column1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
908 //// column2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
910 // html.append("</tr>");
\r
912 // html.append("</table></body></html>");
\r
914 // Log.i(LOG, html.toString());
\r
916 // result.getSettings().setRenderPriority(RenderPriority.HIGH);
\r
917 // result.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
\r
919 // 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
924 private View getView(TokenRow row, ViewGroup parent, final View convertView) {
\r
925 final Context context = parent.getContext();
\r
926 final TextView textView = new TextView(context);
\r
927 textView.setText(row.getToken());
\r
928 textView.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg : theme.tokenRowOtherBg);
\r
930 //textView.setTextColor(android.R.color.secondary_text_light);
\r
931 textView.setTextAppearance(context, theme.tokenRowFg);
\r
932 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
\r
938 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}0-9]+");
\r
940 private void createTokenLinkSpans(final TextView textView, final Spannable spannable, final String text) {
\r
941 // Saw from the source code that LinkMovementMethod sets the selection!
\r
942 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
\r
943 textView.setMovementMethod(LinkMovementMethod.getInstance());
\r
944 final Matcher matcher = CHAR_DASH.matcher(text);
\r
945 while (matcher.find()) {
\r
946 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
951 String selectedSpannableText = null;
\r
952 int selectedSpannableIndex = -1;
\r
955 public boolean onTouchEvent(MotionEvent event) {
\r
956 selectedSpannableText = null;
\r
957 selectedSpannableIndex = -1;
\r
958 return super.onTouchEvent(event);
\r
961 private class TextViewLongClickListener implements OnLongClickListener {
\r
964 private TextViewLongClickListener(final int index) {
\r
965 this.index = index;
\r
969 public boolean onLongClick(final View v) {
\r
970 final TextView textView = (TextView) v;
\r
971 final int start = textView.getSelectionStart();
\r
972 final int end = textView.getSelectionEnd();
\r
973 if (start >= 0 && end >= 0) {
\r
974 selectedSpannableText = textView.getText().subSequence(start, end).toString();
\r
975 selectedSpannableIndex = index;
\r
980 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(0);
\r
981 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(1);
\r
984 // --------------------------------------------------------------------------
\r
986 // --------------------------------------------------------------------------
\r
988 void onSearchTextChange(final String text) {
\r
989 if (dictRaf == null) {
\r
990 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
\r
993 if (!searchText.isFocused()) {
\r
994 Log.d(LOG, "searchText changed without focus, doing nothing.");
\r
997 Log.d(LOG, "onSearchTextChange: " + text);
\r
998 if (currentSearchOperation != null) {
\r
999 Log.d(LOG, "Interrupting currentSearchOperation.");
\r
1000 currentSearchOperation.interrupted.set(true);
\r
1002 currentSearchOperation = new SearchOperation(text, index);
\r
1003 searchExecutor.execute(currentSearchOperation);
\r
1006 private class SearchTextWatcher implements TextWatcher {
\r
1007 public void afterTextChanged(final Editable searchTextEditable) {
\r
1008 if (searchText.hasFocus()) {
\r
1009 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
\r
1010 // If they were typing to cause the change, update the UI.
\r
1011 onSearchTextChange(searchText.getText().toString());
\r
1015 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
\r
1019 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
\r