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
86 public class DictionaryActivity extends ListActivity {
\r
88 static final String LOG = "QuickDic";
\r
90 DictionaryApplication application;
\r
91 File dictFile = null;
\r
92 RandomAccessFile dictRaf = null;
\r
93 Dictionary dictionary = null;
\r
97 // package for test.
\r
98 final Handler uiHandler = new Handler();
\r
99 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
\r
101 public Thread newThread(Runnable r) {
\r
102 return new Thread(r, "searchExecutor");
\r
105 private SearchOperation currentSearchOperation = null;
\r
107 C.Theme theme = C.Theme.LIGHT;
\r
109 EditText searchText;
\r
113 private File wordList = null;
\r
114 private boolean saveOnlyFirstSubentry = false;
\r
115 private boolean clickOpensContextMenu = false;
\r
117 // Visible for testing.
\r
118 ListAdapter indexAdapter = null;
\r
120 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
\r
122 public DictionaryActivity() {
\r
125 public static Intent getLaunchIntent(final File dictFile, final int indexIndex, final String searchToken) {
\r
126 final Intent intent = new Intent();
\r
127 intent.setClassName(DictionaryActivity.class.getPackage().getName(), DictionaryActivity.class.getName());
\r
128 intent.putExtra(C.DICT_FILE, dictFile.getPath());
\r
129 intent.putExtra(C.INDEX_INDEX, indexIndex);
\r
130 intent.putExtra(C.SEARCH_TOKEN, searchToken);
\r
135 protected void onSaveInstanceState(final Bundle outState) {
\r
136 super.onSaveInstanceState(outState);
\r
137 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
\r
141 protected void onRestoreInstanceState(final Bundle outState) {
\r
142 super.onRestoreInstanceState(outState);
\r
143 setSearchText(outState.getString(C.SEARCH_TOKEN));
\r
147 public void onCreate(Bundle savedInstanceState) {
\r
148 Log.d(LOG, "onCreate:" + this);
\r
149 super.onCreate(savedInstanceState);
\r
151 application = (DictionaryApplication) getApplication();
\r
152 theme = application.getSelectedTheme();
\r
154 // Clear them so that if something goes wrong, we won't relaunch.
\r
155 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
525 final MenuItem preferences = menu.add(getString(R.string.preferences));
\r
526 preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
527 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
528 PreferenceActivity.prefsMightHaveChanged = true;
\r
529 startActivity(new Intent(DictionaryActivity.this,
\r
530 PreferenceActivity.class));
\r
537 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
\r
538 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
539 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
540 startActivity(DictionaryManagerActivity.getLaunchIntent());
\r
548 final MenuItem about = menu.add(getString(R.string.about));
\r
549 about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
550 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
551 final Intent intent = new Intent().setClassName(AboutActivity.class
\r
552 .getPackage().getName(), AboutActivity.class.getCanonicalName());
\r
553 startActivity(intent);
\r
563 // --------------------------------------------------------------------------
\r
564 // Context Menu + clicks
\r
565 // --------------------------------------------------------------------------
\r
568 public void onCreateContextMenu(ContextMenu menu, View v,
\r
569 ContextMenuInfo menuInfo) {
\r
570 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
\r
571 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
\r
573 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList, wordList.getName()));
\r
574 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
575 public boolean onMenuItemClick(MenuItem item) {
\r
576 onAppendToWordList(row);
\r
581 final MenuItem copy = menu.add(android.R.string.copy);
\r
582 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
583 public boolean onMenuItemClick(MenuItem item) {
\r
589 if (selectedSpannableText != null) {
\r
590 final String selectedText = selectedSpannableText;
\r
591 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection, selectedSpannableText));
\r
592 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
593 public boolean onMenuItemClick(MenuItem item) {
\r
594 if (indexIndex != selectedSpannableIndex) {
\r
595 changeIndex(selectedSpannableIndex);
\r
597 setSearchText(selectedText);
\r
607 protected void onListItemClick(ListView l, View v, int row, long id) {
\r
608 defocusSearchText();
\r
610 if (clickOpensContextMenu && dictRaf != null) {
\r
611 openContextMenu(v);
\r
615 void onAppendToWordList(final RowBase row) {
\r
616 defocusSearchText();
\r
618 final StringBuilder rawText = new StringBuilder();
\r
620 new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date()))
\r
622 rawText.append(index.longName).append("\t");
\r
623 rawText.append(row.getTokenRow(true).getToken()).append("\t");
\r
624 rawText.append(row.getRawText(saveOnlyFirstSubentry));
\r
625 Log.d(LOG, "Writing : " + rawText);
\r
628 wordList.getParentFile().mkdirs();
\r
629 final PrintWriter out = new PrintWriter(
\r
630 new FileWriter(wordList, true));
\r
631 out.println(rawText.toString());
\r
633 } catch (IOException e) {
\r
634 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
\r
635 Toast.makeText(this, getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()), Toast.LENGTH_LONG);
\r
641 * Called when user clicks outside of search text, so that they can start
\r
642 * typing again immediately.
\r
644 void defocusSearchText() {
\r
645 //Log.d(LOG, "defocusSearchText");
\r
646 // Request focus so that if we start typing again, it clears the text input.
\r
647 getListView().requestFocus();
\r
649 // Visual indication that a new keystroke will clear the search text.
\r
650 searchText.selectAll();
\r
653 void onCopy(final RowBase row) {
\r
654 defocusSearchText();
\r
656 Log.d(LOG, "Copy, row=" + row);
\r
657 final StringBuilder result = new StringBuilder();
\r
658 result.append(row.getRawText(false));
\r
659 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
\r
660 clipboardManager.setText(result.toString());
\r
661 Log.d(LOG, "Copied: " + result);
\r
665 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
\r
666 if (event.getUnicodeChar() != 0) {
\r
667 if (!searchText.hasFocus()) {
\r
668 setSearchText("" + (char) event.getUnicodeChar());
\r
672 if (keyCode == KeyEvent.KEYCODE_BACK) {
\r
673 Log.d(LOG, "Clearing dictionary prefs.");
\r
674 DictionaryActivity.clearDictionaryPrefs(this);
\r
676 if (keyCode == KeyEvent.KEYCODE_ENTER) {
\r
677 Log.d(LOG, "Trying to hide soft keyboard.");
\r
678 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
679 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
\r
682 return super.onKeyDown(keyCode, event);
\r
685 private void setSearchText(final String text) {
\r
686 searchText.setText(text);
\r
687 searchText.requestFocus();
\r
688 onSearchTextChange(searchText.getText().toString());
\r
689 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
\r
693 // --------------------------------------------------------------------------
\r
695 // --------------------------------------------------------------------------
\r
697 private void searchFinished(final SearchOperation searchOperation) {
\r
698 if (searchOperation.interrupted.get()) {
\r
699 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
\r
702 if (searchOperation != this.currentSearchOperation) {
\r
703 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
\r
707 final Index.IndexEntry searchResult = searchOperation.searchResult;
\r
708 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
\r
710 currentSearchOperation = null;
\r
712 uiHandler.postDelayed(new Runnable() {
\r
714 public void run() {
\r
715 if (currentSearchOperation == null) {
\r
716 jumpToRow(searchResult.startRow);
\r
718 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
\r
723 // if (!searchResult.success) {
\r
724 // if (vibrator != null) {
\r
725 // vibrator.vibrate(VIBRATE_MILLIS);
\r
727 // searchText.setText(searchResult.longestPrefixString);
\r
728 // searchText.setSelection(searchResult.longestPrefixString.length());
\r
734 private final void jumpToRow(final int row) {
\r
736 getListView().setSelected(true);
\r
739 final class SearchOperation implements Runnable {
\r
741 final AtomicBoolean interrupted = new AtomicBoolean(false);
\r
742 final String searchText;
\r
745 long searchStartMillis;
\r
747 Index.IndexEntry searchResult;
\r
749 boolean done = false;
\r
751 SearchOperation(final String searchText, final Index index) {
\r
752 this.searchText = searchText.trim();
\r
753 this.index = index;
\r
756 public String toString() {
\r
757 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
\r
761 public void run() {
\r
763 searchStartMillis = System.currentTimeMillis();
\r
764 searchResult = index.findInsertionPoint(searchText, interrupted);
\r
765 Log.d(LOG, "searchText=" + searchText + ", searchDuration="
\r
766 + (System.currentTimeMillis() - searchStartMillis) + ", interrupted="
\r
767 + interrupted.get());
\r
768 if (!interrupted.get()) {
\r
769 uiHandler.post(new Runnable() {
\r
771 public void run() {
\r
772 searchFinished(SearchOperation.this);
\r
777 synchronized (this) {
\r
786 // --------------------------------------------------------------------------
\r
788 // --------------------------------------------------------------------------
\r
790 final class IndexAdapter extends BaseAdapter {
\r
794 IndexAdapter(final Index index) {
\r
795 this.index = index;
\r
799 public int getCount() {
\r
800 return index.rows.size();
\r
804 public RowBase getItem(int position) {
\r
805 return index.rows.get(position);
\r
809 public long getItemId(int position) {
\r
810 return getItem(position).index();
\r
814 public View getView(int position, final View convertView, ViewGroup parent) {
\r
815 final RowBase row = index.rows.get(position);
\r
816 if (row instanceof PairEntry.Row) {
\r
817 return getView((PairEntry.Row) row, parent, convertView);
\r
818 } else if (row instanceof TokenRow) {
\r
819 return getView((TokenRow) row, parent, convertView);
\r
821 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
\r
825 private View getView(PairEntry.Row row, ViewGroup parent, final View convertView) {
\r
826 final TableLayout result = new TableLayout(parent.getContext());
\r
827 final PairEntry entry = row.getEntry();
\r
828 final int rowCount = entry.pairs.size();
\r
829 for (int r = 0; r < rowCount; ++r) {
\r
830 final TableRow tableRow = new TableRow(result.getContext());
\r
832 final TextView col1 = new TextView(tableRow.getContext());
\r
833 final TextView col2 = new TextView(tableRow.getContext());
\r
834 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
\r
835 layoutParams.weight = 0.5f;
\r
837 // Set the columns in the table.
\r
839 final TextView bullet = new TextView(tableRow.getContext());
\r
840 bullet.setText(" • ");
\r
841 tableRow.addView(bullet);
\r
843 tableRow.addView(col1, layoutParams);
\r
844 final TextView margin = new TextView(tableRow.getContext());
\r
845 margin.setText(" ");
\r
846 tableRow.addView(margin);
\r
848 final TextView bullet = new TextView(tableRow.getContext());
\r
849 bullet.setText(" • ");
\r
850 tableRow.addView(bullet);
\r
852 tableRow.addView(col2, layoutParams);
\r
856 // Set what's in the columns.
\r
858 // TODO: color words by gender
\r
859 final Pair pair = entry.pairs.get(r);
\r
860 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
\r
861 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
\r
863 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
\r
864 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
\r
866 // Bold the token instances in col1.
\r
867 final Spannable col1Spannable = (Spannable) col1.getText();
\r
869 final String token = row.getTokenRow(true).getToken();
\r
870 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
\r
871 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos,
\r
872 startPos + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
873 startPos += token.length();
\r
876 createTokenLinkSpans(col1, col1Spannable, col1Text);
\r
877 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
\r
879 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
880 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
881 // col2.setBackgroundResource(theme.otherLangBg);
\r
883 if (index.swapPairEntries) {
\r
884 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
885 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
887 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
888 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
891 result.addView(tableRow);
\r
897 // final WebView result = (WebView) (convertView instanceof WebView ? convertView : new WebView(parent.getContext()));
\r
899 // final PairEntry entry = row.getEntry();
\r
900 // final int rowCount = entry.pairs.size();
\r
901 // final StringBuilder html = new StringBuilder();
\r
902 // html.append("<html><body><table width=\"100%\">");
\r
903 // for (int r = 0; r < rowCount; ++r) {
\r
904 // html.append("<tr>");
\r
906 // final Pair pair = entry.pairs.get(r);
\r
907 // // TODO: escape both the token and the text.
\r
908 // final String token = row.getTokenRow(true).getToken();
\r
909 // final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
\r
910 // final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
\r
912 // col1Text.replaceAll(token, String.format("<b>%s</b>", token));
\r
915 // html.append("<td width=\"50%\">");
\r
917 // html.append("<li>");
\r
919 // html.append(col1Text);
\r
920 // html.append("</td>");
\r
923 // html.append("<td width=\"50%\">");
\r
925 // html.append("<li>");
\r
927 // html.append(col2Text);
\r
928 // html.append("</td>");
\r
930 //// column1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
931 //// column2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
933 // html.append("</tr>");
\r
935 // html.append("</table></body></html>");
\r
937 // Log.i(LOG, html.toString());
\r
939 // result.getSettings().setRenderPriority(RenderPriority.HIGH);
\r
940 // result.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
\r
942 // 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
947 private View getView(TokenRow row, ViewGroup parent, final View convertView) {
\r
948 final Context context = parent.getContext();
\r
949 final TextView textView = new TextView(context);
\r
950 textView.setText(row.getToken());
\r
951 textView.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg : theme.tokenRowOtherBg);
\r
953 //textView.setTextColor(android.R.color.secondary_text_light);
\r
954 textView.setTextAppearance(context, theme.tokenRowFg);
\r
955 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
\r
961 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}0-9]+");
\r
963 private void createTokenLinkSpans(final TextView textView, final Spannable spannable, final String text) {
\r
964 // Saw from the source code that LinkMovementMethod sets the selection!
\r
965 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
\r
966 textView.setMovementMethod(LinkMovementMethod.getInstance());
\r
967 final Matcher matcher = CHAR_DASH.matcher(text);
\r
968 while (matcher.find()) {
\r
969 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
974 String selectedSpannableText = null;
\r
975 int selectedSpannableIndex = -1;
\r
978 public boolean onTouchEvent(MotionEvent event) {
\r
979 selectedSpannableText = null;
\r
980 selectedSpannableIndex = -1;
\r
981 return super.onTouchEvent(event);
\r
984 private class TextViewLongClickListener implements OnLongClickListener {
\r
987 private TextViewLongClickListener(final int index) {
\r
988 this.index = index;
\r
992 public boolean onLongClick(final View v) {
\r
993 final TextView textView = (TextView) v;
\r
994 final int start = textView.getSelectionStart();
\r
995 final int end = textView.getSelectionEnd();
\r
996 if (start >= 0 && end >= 0) {
\r
997 selectedSpannableText = textView.getText().subSequence(start, end).toString();
\r
998 selectedSpannableIndex = index;
\r
1003 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(0);
\r
1004 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(1);
\r
1007 // --------------------------------------------------------------------------
\r
1009 // --------------------------------------------------------------------------
\r
1011 void onSearchTextChange(final String text) {
\r
1012 if (dictRaf == null) {
\r
1013 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
\r
1016 if (!searchText.isFocused()) {
\r
1017 Log.d(LOG, "searchText changed without focus, doing nothing.");
\r
1020 Log.d(LOG, "onSearchTextChange: " + text);
\r
1021 if (currentSearchOperation != null) {
\r
1022 Log.d(LOG, "Interrupting currentSearchOperation.");
\r
1023 currentSearchOperation.interrupted.set(true);
\r
1025 currentSearchOperation = new SearchOperation(text, index);
\r
1026 searchExecutor.execute(currentSearchOperation);
\r
1029 private class SearchTextWatcher implements TextWatcher {
\r
1030 public void afterTextChanged(final Editable searchTextEditable) {
\r
1031 if (searchText.hasFocus()) {
\r
1032 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
\r
1033 // If they were typing to cause the change, update the UI.
\r
1034 onSearchTextChange(searchText.getText().toString());
\r
1038 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
\r
1042 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
\r