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.LayoutParams;
\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.DictionaryInfo.IndexInfo;
\r
78 import com.hughes.android.dictionary.engine.Dictionary;
\r
79 import com.hughes.android.dictionary.engine.Index;
\r
80 import com.hughes.android.dictionary.engine.PairEntry;
\r
81 import com.hughes.android.dictionary.engine.PairEntry.Pair;
\r
82 import com.hughes.android.dictionary.engine.RowBase;
\r
83 import com.hughes.android.dictionary.engine.TokenRow;
\r
84 import com.hughes.android.dictionary.engine.TransliteratorManager;
\r
85 import com.hughes.android.util.IntentLauncher;
\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
159 final Intent intent = getIntent();
\r
160 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
\r
163 final String name = application.getDictionaryName(dictFile.getName());
\r
164 this.setTitle("QuickDic: " + name);
\r
165 dictRaf = new RandomAccessFile(dictFile, "r");
\r
166 dictionary = new Dictionary(dictRaf);
\r
167 } catch (Exception e) {
\r
168 Log.e(LOG, "Unable to load dictionary.", e);
\r
169 if (dictRaf != null) {
\r
172 } catch (IOException e1) {
\r
173 Log.e(LOG, "Unable to close dictRaf.", e1);
\r
177 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()), Toast.LENGTH_LONG);
\r
178 startActivity(DictionaryManagerActivity.getLaunchIntent());
\r
183 Log.d(LOG, "Loading index.");
\r
184 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0) % dictionary.indices.size();
\r
185 index = dictionary.indices.get(indexIndex);
\r
186 setListAdapter(new IndexAdapter(index));
\r
188 // Pre-load the collators.
\r
189 searchExecutor.execute(new Runnable() {
\r
190 public void run() {
\r
191 final long startMillis = System.currentTimeMillis();
\r
193 TransliteratorManager.init(new TransliteratorManager.Callback() {
\r
195 public void onTransliteratorReady() {
\r
196 uiHandler.post(new Runnable() {
\r
198 public void run() {
\r
199 onSearchTextChange(searchText.getText().toString());
\r
205 for (final Index index : dictionary.indices) {
\r
206 Log.d(LOG, "Starting collator load for lang=" + index.sortLanguage.getIsoCode());
\r
208 final com.ibm.icu.text.Collator c = index.sortLanguage.getCollator();
\r
209 if (c.compare("pre-print", "preppy") >= 0) {
\r
210 Log.e(LOG, c.getClass()
\r
211 + " is buggy, lookups may not work properly.");
\r
214 Log.d(LOG, "Loading collators took:"
\r
215 + (System.currentTimeMillis() - startMillis));
\r
219 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
\r
221 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
\r
223 fontSizeSp = Integer.parseInt(fontSize.trim());
\r
224 } catch (NumberFormatException e) {
\r
228 setContentView(R.layout.dictionary_activity);
\r
229 searchText = (EditText) findViewById(R.id.SearchText);
\r
230 searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
232 langButton = (Button) findViewById(R.id.LangButton);
\r
234 searchText.requestFocus();
\r
235 searchText.addTextChangedListener(searchTextWatcher);
\r
236 final String search = prefs.getString(C.SEARCH_TOKEN, "");
\r
237 searchText.setText(search);
\r
238 searchText.setSelection(0, search.length());
\r
239 Log.d(LOG, "Trying to restore searchText=" + search);
\r
241 final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
\r
242 clearSearchTextButton.setOnClickListener(new OnClickListener() {
\r
243 public void onClick(View v) {
\r
244 onClearSearchTextButton(clearSearchTextButton);
\r
247 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
\r
248 getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
\r
251 final Button langButton = (Button) findViewById(R.id.LangButton);
\r
252 langButton.setOnClickListener(new OnClickListener() {
\r
253 public void onClick(View v) {
\r
254 onLanguageButton();
\r
257 langButton.setOnLongClickListener(new OnLongClickListener() {
\r
259 public boolean onLongClick(View v) {
\r
260 onLanguageButtonLongClick(v.getContext());
\r
264 updateLangButton();
\r
266 final Button upButton = (Button) findViewById(R.id.UpButton);
\r
267 upButton.setOnClickListener(new OnClickListener() {
\r
268 public void onClick(View v) {
\r
269 onUpDownButton(true);
\r
272 final Button downButton = (Button) findViewById(R.id.DownButton);
\r
273 downButton.setOnClickListener(new OnClickListener() {
\r
274 public void onClick(View v) {
\r
275 onUpDownButton(false);
\r
279 getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
\r
281 public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
\r
283 if (!searchText.isFocused()) {
\r
284 // TODO: don't do this if multi words are entered.
\r
285 final RowBase row = (RowBase) getListAdapter().getItem(position);
\r
286 Log.d(LOG, "onItemSelected: " + row.index());
\r
287 final TokenRow tokenRow = row.getTokenRow(true);
\r
288 searchText.setText(tokenRow.getToken());
\r
293 public void onNothingSelected(AdapterView<?> arg0) {
\r
298 registerForContextMenu(getListView());
\r
301 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
\r
302 getString(R.string.wordListFileDefault)));
\r
303 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey), false);
\r
304 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey), false);
\r
305 //if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey), true)) {
\r
306 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
\r
308 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
\r
310 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
\r
314 protected void onResume() {
\r
316 if (PreferenceActivity.prefsMightHaveChanged) {
\r
317 PreferenceActivity.prefsMightHaveChanged = false;
\r
319 startActivity(getIntent());
\r
324 protected void onPause() {
\r
328 private static void setDictionaryPrefs(final Context context,
\r
329 final File dictFile, final int indexIndex, final String searchToken) {
\r
330 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
\r
331 prefs.putString(C.DICT_FILE, dictFile.getPath());
\r
332 prefs.putInt(C.INDEX_INDEX, indexIndex);
\r
333 prefs.putString(C.SEARCH_TOKEN, searchToken);
\r
337 private static void clearDictionaryPrefs(final Context context) {
\r
338 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
\r
339 prefs.remove(C.DICT_FILE);
\r
340 prefs.remove(C.INDEX_INDEX);
\r
341 prefs.remove(C.SEARCH_TOKEN);
\r
347 protected void onDestroy() {
\r
349 if (dictRaf == null) {
\r
353 // Before we close the RAF, we have to wind the current search down.
\r
354 if (currentSearchOperation != null) {
\r
355 Log.d(LOG, "Interrupting search to shut down.");
\r
356 final SearchOperation searchOperation = currentSearchOperation;
\r
357 currentSearchOperation = null;
\r
358 searchOperation.interrupted.set(true);
\r
359 synchronized (searchOperation) {
\r
360 while (!searchOperation.done) {
\r
362 searchOperation.wait();
\r
363 } catch (InterruptedException e) {
\r
364 Log.d(LOG, "Interrupted.", e);
\r
371 Log.d(LOG, "Closing RAF.");
\r
373 } catch (IOException e) {
\r
374 Log.e(LOG, "Failed to close dictionary", e);
\r
379 // --------------------------------------------------------------------------
\r
381 // --------------------------------------------------------------------------
\r
383 private void onClearSearchTextButton(final Button clearSearchTextButton) {
\r
384 clearSearchTextButton.requestFocus();
\r
385 searchText.setText("");
\r
386 searchText.requestFocus();
\r
387 Log.d(LOG, "Trying to show soft keyboard.");
\r
388 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
389 manager.showSoftInput(searchText, InputMethodManager.SHOW_FORCED);
\r
392 void updateLangButton() {
\r
393 langButton.setText(index.shortName);
\r
396 void onLanguageButton() {
\r
397 if (currentSearchOperation != null) {
\r
398 currentSearchOperation.interrupted.set(true);
\r
399 currentSearchOperation = null;
\r
401 changeIndex((indexIndex + 1)% dictionary.indices.size());
\r
404 static class OpenIndexButton extends Button implements OnClickListener {
\r
406 final Activity activity;
\r
407 final Intent intent;
\r
409 public OpenIndexButton(final Context context, final Activity activity, final String text, final Intent intent) {
\r
411 this.activity = activity;
\r
412 this.intent = intent;
\r
413 setOnClickListener(this);
\r
414 setText(text, BufferType.NORMAL);
\r
418 public void onClick(View v) {
\r
420 getContext().startActivity(intent);
\r
425 void onLanguageButtonLongClick(final Context context) {
\r
426 final Dialog dialog = new Dialog(context);
\r
427 dialog.setContentView(R.layout.select_dictionary_dialog);
\r
428 dialog.setTitle(R.string.selectDictionary);
\r
430 final List<DictionaryInfo> installedDicts = ((DictionaryApplication)getApplication()).getUsableDicts();
\r
431 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
\r
432 listView.setAdapter(new BaseAdapter() {
\r
434 public View getView(int position, View convertView, ViewGroup parent) {
\r
435 final LinearLayout result = new LinearLayout(parent.getContext());
\r
436 final DictionaryInfo dictionaryInfo = getItem(position);
\r
437 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
\r
438 final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
\r
439 final Button button = new Button(parent.getContext());
\r
440 String name = application.getLanguageName(indexInfo.shortName);
\r
441 if (name == null) {
\r
442 name = indexInfo.shortName;
\r
444 button.setText(name);
\r
445 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(), getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename), i, "")) {
\r
447 protected void onGo() {
\r
449 DictionaryActivity.this.finish();
\r
452 button.setOnClickListener(intentLauncher);
\r
454 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
\r
455 layoutParams.width = 0;
\r
456 layoutParams.weight = 1.0f;
\r
457 button.setLayoutParams(layoutParams);
\r
459 result.addView(button);
\r
465 public long getItemId(int position) {
\r
470 public DictionaryInfo getItem(int position) {
\r
471 return installedDicts.get(position);
\r
475 public int getCount() {
\r
476 return installedDicts.size();
\r
484 private void changeIndex(final int newIndex) {
\r
485 indexIndex = newIndex;
\r
486 index = dictionary.indices.get(indexIndex);
\r
487 indexAdapter = new IndexAdapter(index);
\r
488 Log.d(LOG, "changingIndex, newLang=" + index.longName);
\r
489 setListAdapter(indexAdapter);
\r
490 updateLangButton();
\r
491 searchText.requestFocus(); // Otherwise, nothing may happen.
\r
492 onSearchTextChange(searchText.getText().toString());
\r
495 void onUpDownButton(final boolean up) {
\r
496 final int firstVisibleRow = getListView().getFirstVisiblePosition();
\r
497 final RowBase row = index.rows.get(firstVisibleRow);
\r
498 final TokenRow tokenRow = row.getTokenRow(true);
\r
499 final int destIndexEntry;
\r
501 if (row != tokenRow) {
\r
502 destIndexEntry = tokenRow.referenceIndex;
\r
504 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
\r
508 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
\r
510 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
\r
511 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
\r
512 searchText.removeTextChangedListener(searchTextWatcher);
\r
513 searchText.setText(dest.token);
\r
514 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
\r
515 searchText.addTextChangedListener(searchTextWatcher);
\r
518 // --------------------------------------------------------------------------
\r
520 // --------------------------------------------------------------------------
\r
523 public boolean onCreateOptionsMenu(final Menu menu) {
\r
526 final MenuItem preferences = menu.add(getString(R.string.preferences));
\r
527 preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
528 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
529 PreferenceActivity.prefsMightHaveChanged = true;
\r
530 startActivity(new Intent(DictionaryActivity.this,
\r
531 PreferenceActivity.class));
\r
538 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
\r
539 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
540 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
541 startActivity(DictionaryManagerActivity.getLaunchIntent());
\r
549 final MenuItem about = menu.add(getString(R.string.about));
\r
550 about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
551 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
552 final Intent intent = new Intent().setClassName(AboutActivity.class
\r
553 .getPackage().getName(), AboutActivity.class.getCanonicalName());
\r
554 startActivity(intent);
\r
564 // --------------------------------------------------------------------------
\r
565 // Context Menu + clicks
\r
566 // --------------------------------------------------------------------------
\r
569 public void onCreateContextMenu(ContextMenu menu, View v,
\r
570 ContextMenuInfo menuInfo) {
\r
571 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
\r
572 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
\r
574 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList, wordList.getName()));
\r
575 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
576 public boolean onMenuItemClick(MenuItem item) {
\r
577 onAppendToWordList(row);
\r
582 final MenuItem copy = menu.add(android.R.string.copy);
\r
583 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
584 public boolean onMenuItemClick(MenuItem item) {
\r
590 if (selectedSpannableText != null) {
\r
591 final String selectedText = selectedSpannableText;
\r
592 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection, selectedSpannableText));
\r
593 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
594 public boolean onMenuItemClick(MenuItem item) {
\r
595 if (indexIndex != selectedSpannableIndex) {
\r
596 changeIndex(selectedSpannableIndex);
\r
598 setSearchText(selectedText);
\r
608 protected void onListItemClick(ListView l, View v, int row, long id) {
\r
609 defocusSearchText();
\r
611 if (clickOpensContextMenu && dictRaf != null) {
\r
612 openContextMenu(v);
\r
616 void onAppendToWordList(final RowBase row) {
\r
617 defocusSearchText();
\r
619 final StringBuilder rawText = new StringBuilder();
\r
621 new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date()))
\r
623 rawText.append(index.longName).append("\t");
\r
624 rawText.append(row.getTokenRow(true).getToken()).append("\t");
\r
625 rawText.append(row.getRawText(saveOnlyFirstSubentry));
\r
626 Log.d(LOG, "Writing : " + rawText);
\r
629 wordList.getParentFile().mkdirs();
\r
630 final PrintWriter out = new PrintWriter(
\r
631 new FileWriter(wordList, true));
\r
632 out.println(rawText.toString());
\r
634 } catch (IOException e) {
\r
635 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
\r
636 Toast.makeText(this, getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()), Toast.LENGTH_LONG);
\r
642 * Called when user clicks outside of search text, so that they can start
\r
643 * typing again immediately.
\r
645 void defocusSearchText() {
\r
646 //Log.d(LOG, "defocusSearchText");
\r
647 // Request focus so that if we start typing again, it clears the text input.
\r
648 getListView().requestFocus();
\r
650 // Visual indication that a new keystroke will clear the search text.
\r
651 searchText.selectAll();
\r
654 void onCopy(final RowBase row) {
\r
655 defocusSearchText();
\r
657 Log.d(LOG, "Copy, row=" + row);
\r
658 final StringBuilder result = new StringBuilder();
\r
659 result.append(row.getRawText(false));
\r
660 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
\r
661 clipboardManager.setText(result.toString());
\r
662 Log.d(LOG, "Copied: " + result);
\r
666 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
\r
667 if (event.getUnicodeChar() != 0) {
\r
668 if (!searchText.hasFocus()) {
\r
669 setSearchText("" + (char) event.getUnicodeChar());
\r
673 if (keyCode == KeyEvent.KEYCODE_BACK) {
\r
674 Log.d(LOG, "Clearing dictionary prefs.");
\r
675 DictionaryActivity.clearDictionaryPrefs(this);
\r
677 if (keyCode == KeyEvent.KEYCODE_ENTER) {
\r
678 Log.d(LOG, "Trying to hide soft keyboard.");
\r
679 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
680 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
\r
683 return super.onKeyDown(keyCode, event);
\r
686 private void setSearchText(final String text) {
\r
687 searchText.setText(text);
\r
688 searchText.requestFocus();
\r
689 onSearchTextChange(searchText.getText().toString());
\r
690 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
\r
694 // --------------------------------------------------------------------------
\r
696 // --------------------------------------------------------------------------
\r
698 private void searchFinished(final SearchOperation searchOperation) {
\r
699 if (searchOperation.interrupted.get()) {
\r
700 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
\r
703 if (searchOperation != this.currentSearchOperation) {
\r
704 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
\r
708 final Index.IndexEntry searchResult = searchOperation.searchResult;
\r
709 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
\r
711 currentSearchOperation = null;
\r
713 uiHandler.postDelayed(new Runnable() {
\r
715 public void run() {
\r
716 if (currentSearchOperation == null) {
\r
717 jumpToRow(searchResult.startRow);
\r
719 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
\r
724 // if (!searchResult.success) {
\r
725 // if (vibrator != null) {
\r
726 // vibrator.vibrate(VIBRATE_MILLIS);
\r
728 // searchText.setText(searchResult.longestPrefixString);
\r
729 // searchText.setSelection(searchResult.longestPrefixString.length());
\r
735 private final void jumpToRow(final int row) {
\r
737 getListView().setSelected(true);
\r
740 final class SearchOperation implements Runnable {
\r
742 final AtomicBoolean interrupted = new AtomicBoolean(false);
\r
743 final String searchText;
\r
746 long searchStartMillis;
\r
748 Index.IndexEntry searchResult;
\r
750 boolean done = false;
\r
752 SearchOperation(final String searchText, final Index index) {
\r
753 this.searchText = searchText.trim();
\r
754 this.index = index;
\r
757 public String toString() {
\r
758 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
\r
762 public void run() {
\r
764 searchStartMillis = System.currentTimeMillis();
\r
765 searchResult = index.findInsertionPoint(searchText, interrupted);
\r
766 Log.d(LOG, "searchText=" + searchText + ", searchDuration="
\r
767 + (System.currentTimeMillis() - searchStartMillis) + ", interrupted="
\r
768 + interrupted.get());
\r
769 if (!interrupted.get()) {
\r
770 uiHandler.post(new Runnable() {
\r
772 public void run() {
\r
773 searchFinished(SearchOperation.this);
\r
778 synchronized (this) {
\r
787 // --------------------------------------------------------------------------
\r
789 // --------------------------------------------------------------------------
\r
791 final class IndexAdapter extends BaseAdapter {
\r
795 IndexAdapter(final Index index) {
\r
796 this.index = index;
\r
800 public int getCount() {
\r
801 return index.rows.size();
\r
805 public RowBase getItem(int position) {
\r
806 return index.rows.get(position);
\r
810 public long getItemId(int position) {
\r
811 return getItem(position).index();
\r
815 public View getView(int position, final View convertView, ViewGroup parent) {
\r
816 final RowBase row = index.rows.get(position);
\r
817 if (row instanceof PairEntry.Row) {
\r
818 return getView((PairEntry.Row) row, parent, convertView);
\r
819 } else if (row instanceof TokenRow) {
\r
820 return getView((TokenRow) row, parent, convertView);
\r
822 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
\r
826 private View getView(PairEntry.Row row, ViewGroup parent, final View convertView) {
\r
827 final LinearLayout result = new LinearLayout(parent.getContext());
\r
828 final PairEntry entry = row.getEntry();
\r
829 final int rowCount = entry.pairs.size();
\r
830 for (int r = 0; r < rowCount; ++r) {
\r
831 final LinearLayout tableRow = new LinearLayout(result.getContext());
\r
832 final LinearLayout.LayoutParams rowLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
\r
833 tableRow.setLayoutParams(rowLayoutParams);
\r
835 final TextView col1 = new TextView(tableRow.getContext());
\r
836 final TextView col2 = new TextView(tableRow.getContext());
\r
837 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
\r
838 layoutParams.weight = 1.0f;
\r
840 // Set the columns in the table.
\r
842 final TextView bullet = new TextView(tableRow.getContext());
\r
843 bullet.setText(" • ");
\r
844 tableRow.addView(bullet);
\r
846 tableRow.addView(col1, layoutParams);
\r
847 final TextView margin = new TextView(tableRow.getContext());
\r
848 margin.setText(" ");
\r
849 tableRow.addView(margin);
\r
851 final TextView bullet = new TextView(tableRow.getContext());
\r
852 bullet.setText(" • ");
\r
853 tableRow.addView(bullet);
\r
855 tableRow.addView(col2, layoutParams);
\r
859 // Set what's in the columns.
\r
861 // TODO: color words by gender
\r
862 final Pair pair = entry.pairs.get(r);
\r
863 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
\r
864 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
\r
866 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
\r
867 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
\r
869 // Bold the token instances in col1.
\r
870 final Spannable col1Spannable = (Spannable) col1.getText();
\r
872 final String token = row.getTokenRow(true).getToken();
\r
873 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
\r
874 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos,
\r
875 startPos + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
876 startPos += token.length();
\r
879 createTokenLinkSpans(col1, col1Spannable, col1Text);
\r
880 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
\r
882 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
883 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
884 // col2.setBackgroundResource(theme.otherLangBg);
\r
886 if (index.swapPairEntries) {
\r
887 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
888 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
890 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
891 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
894 result.addView(tableRow);
\r
900 // final WebView result = (WebView) (convertView instanceof WebView ? convertView : new WebView(parent.getContext()));
\r
902 // final PairEntry entry = row.getEntry();
\r
903 // final int rowCount = entry.pairs.size();
\r
904 // final StringBuilder html = new StringBuilder();
\r
905 // html.append("<html><body><table width=\"100%\">");
\r
906 // for (int r = 0; r < rowCount; ++r) {
\r
907 // html.append("<tr>");
\r
909 // final Pair pair = entry.pairs.get(r);
\r
910 // // TODO: escape both the token and the text.
\r
911 // final String token = row.getTokenRow(true).getToken();
\r
912 // final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
\r
913 // final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
\r
915 // col1Text.replaceAll(token, String.format("<b>%s</b>", token));
\r
918 // html.append("<td width=\"50%\">");
\r
920 // html.append("<li>");
\r
922 // html.append(col1Text);
\r
923 // html.append("</td>");
\r
926 // html.append("<td width=\"50%\">");
\r
928 // html.append("<li>");
\r
930 // html.append(col2Text);
\r
931 // html.append("</td>");
\r
933 //// column1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
934 //// column2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
936 // html.append("</tr>");
\r
938 // html.append("</table></body></html>");
\r
940 // Log.i(LOG, html.toString());
\r
942 // result.getSettings().setRenderPriority(RenderPriority.HIGH);
\r
943 // result.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
\r
945 // 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
950 private View getView(TokenRow row, ViewGroup parent, final View convertView) {
\r
951 final Context context = parent.getContext();
\r
952 final TextView textView = new TextView(context);
\r
953 textView.setText(row.getToken());
\r
954 textView.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg : theme.tokenRowOtherBg);
\r
956 //textView.setTextColor(android.R.color.secondary_text_light);
\r
957 textView.setTextAppearance(context, theme.tokenRowFg);
\r
958 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
\r
964 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}0-9]+");
\r
966 private void createTokenLinkSpans(final TextView textView, final Spannable spannable, final String text) {
\r
967 // Saw from the source code that LinkMovementMethod sets the selection!
\r
968 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
\r
969 textView.setMovementMethod(LinkMovementMethod.getInstance());
\r
970 final Matcher matcher = CHAR_DASH.matcher(text);
\r
971 while (matcher.find()) {
\r
972 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
977 String selectedSpannableText = null;
\r
978 int selectedSpannableIndex = -1;
\r
981 public boolean onTouchEvent(MotionEvent event) {
\r
982 selectedSpannableText = null;
\r
983 selectedSpannableIndex = -1;
\r
984 return super.onTouchEvent(event);
\r
987 private class TextViewLongClickListener implements OnLongClickListener {
\r
990 private TextViewLongClickListener(final int index) {
\r
991 this.index = index;
\r
995 public boolean onLongClick(final View v) {
\r
996 final TextView textView = (TextView) v;
\r
997 final int start = textView.getSelectionStart();
\r
998 final int end = textView.getSelectionEnd();
\r
999 if (start >= 0 && end >= 0) {
\r
1000 selectedSpannableText = textView.getText().subSequence(start, end).toString();
\r
1001 selectedSpannableIndex = index;
\r
1006 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(0);
\r
1007 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(1);
\r
1010 // --------------------------------------------------------------------------
\r
1012 // --------------------------------------------------------------------------
\r
1014 void onSearchTextChange(final String text) {
\r
1015 if (dictRaf == null) {
\r
1016 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
\r
1019 if (!searchText.isFocused()) {
\r
1020 Log.d(LOG, "searchText changed without focus, doing nothing.");
\r
1023 Log.d(LOG, "onSearchTextChange: " + text);
\r
1024 if (currentSearchOperation != null) {
\r
1025 Log.d(LOG, "Interrupting currentSearchOperation.");
\r
1026 currentSearchOperation.interrupted.set(true);
\r
1028 currentSearchOperation = new SearchOperation(text, index);
\r
1029 searchExecutor.execute(currentSearchOperation);
\r
1032 private class SearchTextWatcher implements TextWatcher {
\r
1033 public void afterTextChanged(final Editable searchTextEditable) {
\r
1034 if (searchText.hasFocus()) {
\r
1035 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
\r
1036 // If they were typing to cause the change, update the UI.
\r
1037 onSearchTextChange(searchText.getText().toString());
\r
1041 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
\r
1045 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
\r