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.Arrays;
\r
24 import java.util.Collections;
\r
25 import java.util.Date;
\r
26 import java.util.LinkedHashSet;
\r
27 import java.util.List;
\r
28 import java.util.Random;
\r
29 import java.util.Set;
\r
30 import java.util.concurrent.Executor;
\r
31 import java.util.concurrent.Executors;
\r
32 import java.util.concurrent.ThreadFactory;
\r
33 import java.util.concurrent.atomic.AtomicBoolean;
\r
34 import java.util.regex.Matcher;
\r
35 import java.util.regex.Pattern;
\r
37 import android.app.Dialog;
\r
38 import android.app.ListActivity;
\r
39 import android.content.Context;
\r
40 import android.content.Intent;
\r
41 import android.content.SharedPreferences;
\r
42 import android.graphics.Typeface;
\r
43 import android.net.Uri;
\r
44 import android.os.Bundle;
\r
45 import android.os.Handler;
\r
46 import android.preference.PreferenceManager;
\r
47 import android.text.ClipboardManager;
\r
48 import android.text.Editable;
\r
49 import android.text.Selection;
\r
50 import android.text.Spannable;
\r
51 import android.text.TextWatcher;
\r
52 import android.text.method.LinkMovementMethod;
\r
53 import android.text.style.StyleSpan;
\r
54 import android.util.Log;
\r
55 import android.util.TypedValue;
\r
56 import android.view.ContextMenu;
\r
57 import android.view.ContextMenu.ContextMenuInfo;
\r
58 import android.view.KeyEvent;
\r
59 import android.view.Menu;
\r
60 import android.view.MenuItem;
\r
61 import android.view.MenuItem.OnMenuItemClickListener;
\r
62 import android.view.MotionEvent;
\r
63 import android.view.View;
\r
64 import android.view.View.OnClickListener;
\r
65 import android.view.View.OnLongClickListener;
\r
66 import android.view.ViewGroup;
\r
67 import android.view.WindowManager;
\r
68 import android.view.inputmethod.InputMethodManager;
\r
69 import android.widget.AdapterView;
\r
70 import android.widget.AdapterView.AdapterContextMenuInfo;
\r
71 import android.widget.BaseAdapter;
\r
72 import android.widget.Button;
\r
73 import android.widget.EditText;
\r
74 import android.widget.ImageView;
\r
75 import android.widget.LinearLayout;
\r
76 import android.widget.ListAdapter;
\r
77 import android.widget.ListView;
\r
78 import android.widget.TableLayout;
\r
79 import android.widget.TableRow;
\r
80 import android.widget.TextView;
\r
81 import android.widget.Toast;
\r
83 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
\r
84 import com.hughes.android.dictionary.engine.Dictionary;
\r
85 import com.hughes.android.dictionary.engine.EntrySource;
\r
86 import com.hughes.android.dictionary.engine.Index;
\r
87 import com.hughes.android.dictionary.engine.Index.IndexEntry;
\r
88 import com.hughes.android.dictionary.engine.PairEntry;
\r
89 import com.hughes.android.dictionary.engine.PairEntry.Pair;
\r
90 import com.hughes.android.dictionary.engine.RowBase;
\r
91 import com.hughes.android.dictionary.engine.TokenRow;
\r
92 import com.hughes.android.dictionary.engine.TransliteratorManager;
\r
93 import com.hughes.android.util.IntentLauncher;
\r
94 import com.hughes.android.util.NonLinkClickableSpan;
\r
96 public class DictionaryActivity extends ListActivity {
\r
98 static final String LOG = "QuickDic";
\r
100 private String initialSearchText;
\r
102 DictionaryApplication application;
\r
103 File dictFile = null;
\r
104 RandomAccessFile dictRaf = null;
\r
105 Dictionary dictionary = null;
\r
106 int indexIndex = 0;
\r
107 Index index = null;
\r
108 List<RowBase> rowsToShow = null; // if not null, just show these rows.
\r
110 // package for test.
\r
111 final Handler uiHandler = new Handler();
\r
112 private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
\r
114 public Thread newThread(Runnable r) {
\r
115 return new Thread(r, "searchExecutor");
\r
118 private SearchOperation currentSearchOperation = null;
\r
120 C.Theme theme = C.Theme.LIGHT;
\r
123 EditText searchText;
\r
127 private File wordList = null;
\r
128 private boolean saveOnlyFirstSubentry = false;
\r
129 private boolean clickOpensContextMenu = false;
\r
131 // Visible for testing.
\r
132 ListAdapter indexAdapter = null;
\r
134 final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
\r
137 * For some languages, loading the transliterators used in this search takes
\r
138 * a long time, so we fire it up on a different thread, and don't invoke it
\r
139 * from the main thread until it's already finished once.
\r
141 private volatile boolean indexPrepFinished = false;
\r
145 public DictionaryActivity() {
\r
148 public static Intent getLaunchIntent(final File dictFile, final int indexIndex, final String searchToken) {
\r
149 final Intent intent = new Intent();
\r
150 intent.setClassName(DictionaryActivity.class.getPackage().getName(), DictionaryActivity.class.getName());
\r
151 intent.putExtra(C.DICT_FILE, dictFile.getPath());
\r
152 intent.putExtra(C.INDEX_INDEX, indexIndex);
\r
153 intent.putExtra(C.SEARCH_TOKEN, searchToken);
\r
158 protected void onSaveInstanceState(final Bundle outState) {
\r
159 super.onSaveInstanceState(outState);
\r
160 Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
\r
161 outState.putInt(C.INDEX_INDEX, indexIndex);
\r
162 outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
\r
166 protected void onRestoreInstanceState(final Bundle outState) {
\r
167 super.onRestoreInstanceState(outState);
\r
168 Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
\r
169 onCreate(outState);
\r
173 public void onCreate(Bundle savedInstanceState) {
\r
174 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
\r
175 prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if this fails.
\r
177 setTheme(((DictionaryApplication)getApplication()).getSelectedTheme().themeId);
\r
179 Log.d(LOG, "onCreate:" + this);
\r
180 super.onCreate(savedInstanceState);
\r
182 application = (DictionaryApplication) getApplication();
\r
183 theme = application.getSelectedTheme();
\r
185 final Intent intent = getIntent();
\r
186 dictFile = new File(intent.getStringExtra(C.DICT_FILE));
\r
189 final String name = application.getDictionaryName(dictFile.getName());
\r
190 this.setTitle("QuickDic: " + name);
\r
191 dictRaf = new RandomAccessFile(dictFile, "r");
\r
192 dictionary = new Dictionary(dictRaf);
\r
193 } catch (Exception e) {
\r
194 Log.e(LOG, "Unable to load dictionary.", e);
\r
195 if (dictRaf != null) {
\r
198 } catch (IOException e1) {
\r
199 Log.e(LOG, "Unable to close dictRaf.", e1);
\r
203 Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()), Toast.LENGTH_LONG).show();
\r
204 startActivity(DictionaryManagerActivity.getLaunchIntent());
\r
208 indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
\r
209 if (savedInstanceState != null) {
\r
210 indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
\r
212 indexIndex %= dictionary.indices.size();
\r
213 Log.d(LOG, "Loading index " + indexIndex);
\r
214 index = dictionary.indices.get(indexIndex);
\r
215 setListAdapter(new IndexAdapter(index));
\r
217 // Pre-load the collators.
\r
218 new Thread(new Runnable() {
\r
219 public void run() {
\r
220 final long startMillis = System.currentTimeMillis();
\r
222 TransliteratorManager.init(new TransliteratorManager.Callback() {
\r
224 public void onTransliteratorReady() {
\r
225 uiHandler.post(new Runnable() {
\r
227 public void run() {
\r
228 onSearchTextChange(searchText.getText().toString());
\r
234 for (final Index index : dictionary.indices) {
\r
235 final String searchToken = index.sortedIndexEntries.get(0).token;
\r
236 final IndexEntry entry = index.findExact(searchToken);
\r
237 if (!searchToken.equals(entry.token)) {
\r
238 Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
\r
241 indexPrepFinished = true;
\r
242 } catch (Exception e) {
\r
243 Log.w(LOG, "Exception while prepping. This can happen if dictionary is closed while search is happening.");
\r
245 Log.d(LOG, "Prepping indices took:"
\r
246 + (System.currentTimeMillis() - startMillis));
\r
250 final String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
\r
251 if ("SYSTEM".equals(fontName)) {
\r
252 typeface = Typeface.DEFAULT;
\r
255 typeface = Typeface.createFromAsset(getAssets(), fontName);
\r
256 } catch (Exception e) {
\r
257 Log.w(LOG, "Exception trying to use typeface, using default.", e);
\r
258 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()), Toast.LENGTH_LONG).show();
\r
261 if (typeface == null) {
\r
262 Log.w(LOG, "Unable to create typeface, using default.");
\r
263 typeface = Typeface.DEFAULT;
\r
265 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
\r
267 fontSizeSp = Integer.parseInt(fontSize.trim());
\r
268 } catch (NumberFormatException e) {
\r
272 setContentView(R.layout.dictionary_activity);
\r
273 searchText = (EditText) findViewById(R.id.SearchText);
\r
274 searchText.setTypeface(typeface);
\r
275 searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
277 langButton = (Button) findViewById(R.id.LangButton);
\r
279 searchText.requestFocus();
\r
280 searchText.addTextChangedListener(searchTextWatcher);
\r
282 if (savedInstanceState != null) {
\r
283 text = savedInstanceState.getString(C.SEARCH_TOKEN);
\r
284 if (text == null) {
\r
288 setSearchText(text, true);
\r
289 Log.d(LOG, "Trying to restore searchText=" + text);
\r
291 final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
\r
292 clearSearchTextButton.setOnClickListener(new OnClickListener() {
\r
293 public void onClick(View v) {
\r
294 onClearSearchTextButton(clearSearchTextButton);
\r
297 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
\r
298 getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
\r
301 final Button langButton = (Button) findViewById(R.id.LangButton);
\r
302 langButton.setOnClickListener(new OnClickListener() {
\r
303 public void onClick(View v) {
\r
304 onLanguageButton();
\r
307 langButton.setOnLongClickListener(new OnLongClickListener() {
\r
309 public boolean onLongClick(View v) {
\r
310 onLanguageButtonLongClick(v.getContext());
\r
314 updateLangButton();
\r
316 final Button upButton = (Button) findViewById(R.id.UpButton);
\r
317 upButton.setOnClickListener(new OnClickListener() {
\r
318 public void onClick(View v) {
\r
319 onUpDownButton(true);
\r
322 final Button downButton = (Button) findViewById(R.id.DownButton);
\r
323 downButton.setOnClickListener(new OnClickListener() {
\r
324 public void onClick(View v) {
\r
325 onUpDownButton(false);
\r
329 getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
\r
331 public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
\r
333 if (!searchText.isFocused()) {
\r
334 if (!isFiltered()) {
\r
335 final RowBase row = (RowBase) getListAdapter().getItem(position);
\r
336 Log.d(LOG, "onItemSelected: " + row.index());
\r
337 final TokenRow tokenRow = row.getTokenRow(true);
\r
338 searchText.setText(tokenRow.getToken());
\r
344 public void onNothingSelected(AdapterView<?> arg0) {
\r
349 registerForContextMenu(getListView());
\r
352 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
\r
353 getString(R.string.wordListFileDefault)));
\r
354 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey), false);
\r
355 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey), false);
\r
356 //if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey), true)) {
\r
357 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
\r
359 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
\r
361 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
\r
365 protected void onResume() {
\r
367 if (PreferenceActivity.prefsMightHaveChanged) {
\r
368 PreferenceActivity.prefsMightHaveChanged = false;
\r
370 startActivity(getIntent());
\r
372 if (initialSearchText != null) {
\r
373 setSearchText(initialSearchText, true);
\r
378 protected void onPause() {
\r
382 private static void setDictionaryPrefs(final Context context,
\r
383 final File dictFile, final int indexIndex, final String searchToken) {
\r
384 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
\r
385 prefs.putString(C.DICT_FILE, dictFile.getPath());
\r
386 prefs.putInt(C.INDEX_INDEX, indexIndex);
\r
387 prefs.putString(C.SEARCH_TOKEN, searchToken);
\r
392 protected void onDestroy() {
\r
394 if (dictRaf == null) {
\r
398 final SearchOperation searchOperation = currentSearchOperation;
\r
399 currentSearchOperation = null;
\r
401 // Before we close the RAF, we have to wind the current search down.
\r
402 if (searchOperation != null) {
\r
403 Log.d(LOG, "Interrupting search to shut down.");
\r
404 currentSearchOperation = null;
\r
405 searchOperation.interrupted.set(true);
\r
409 Log.d(LOG, "Closing RAF.");
\r
411 } catch (IOException e) {
\r
412 Log.e(LOG, "Failed to close dictionary", e);
\r
417 // --------------------------------------------------------------------------
\r
419 // --------------------------------------------------------------------------
\r
421 private void onClearSearchTextButton(final Button clearSearchTextButton) {
\r
422 setSearchText("", true);
\r
423 Log.d(LOG, "Trying to show soft keyboard.");
\r
424 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
425 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
\r
428 void updateLangButton() {
\r
429 // final LanguageResources languageResources = Language.isoCodeToResources.get(index.shortName);
\r
430 // if (languageResources != null && languageResources.flagId != 0) {
\r
431 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, languageResources.flagId, 0);
\r
433 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
\r
434 langButton.setText(index.shortName);
\r
438 void onLanguageButton() {
\r
439 if (currentSearchOperation != null) {
\r
440 currentSearchOperation.interrupted.set(true);
\r
441 currentSearchOperation = null;
\r
443 changeIndexGetFocusAndResearch((indexIndex + 1)% dictionary.indices.size());
\r
446 void onLanguageButtonLongClick(final Context context) {
\r
447 final Dialog dialog = new Dialog(context);
\r
448 dialog.setContentView(R.layout.select_dictionary_dialog);
\r
449 dialog.setTitle(R.string.selectDictionary);
\r
451 final List<DictionaryInfo> installedDicts = ((DictionaryApplication)getApplication()).getUsableDicts();
\r
453 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
\r
455 // final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
\r
456 // layoutParams.width = 0;
\r
457 // layoutParams.weight = 1.0f;
\r
459 final Button button = new Button(listView.getContext());
\r
460 final String name = getString(R.string.dictionaryManager);
\r
461 button.setText(name);
\r
462 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(), DictionaryManagerActivity.getLaunchIntent()) {
\r
464 protected void onGo() {
\r
466 DictionaryActivity.this.finish();
\r
469 button.setOnClickListener(intentLauncher);
\r
470 // button.setLayoutParams(layoutParams);
\r
471 listView.addHeaderView(button);
\r
472 // listView.setHeaderDividersEnabled(true);
\r
474 listView.setAdapter(new BaseAdapter() {
\r
476 public View getView(int position, View convertView, ViewGroup parent) {
\r
477 final LinearLayout result = new LinearLayout(parent.getContext());
\r
479 final DictionaryInfo dictionaryInfo = getItem(position);
\r
480 final Button button = new Button(parent.getContext());
\r
481 final String name = application.getDictionaryName(dictionaryInfo.uncompressedFilename);
\r
482 button.setText(name);
\r
483 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(), getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename), 0, searchText.getText().toString())) {
\r
485 protected void onGo() {
\r
487 DictionaryActivity.this.finish();
\r
490 button.setOnClickListener(intentLauncher);
\r
491 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
\r
492 layoutParams.width = 0;
\r
493 layoutParams.weight = 1.0f;
\r
494 button.setLayoutParams(layoutParams);
\r
495 result.addView(button);
\r
500 public long getItemId(int position) {
\r
505 public DictionaryInfo getItem(int position) {
\r
506 return installedDicts.get(position);
\r
510 public int getCount() {
\r
511 return installedDicts.size();
\r
519 private void changeIndexGetFocusAndResearch(final int newIndex) {
\r
520 indexIndex = newIndex;
\r
521 index = dictionary.indices.get(indexIndex);
\r
522 indexAdapter = new IndexAdapter(index);
\r
523 Log.d(LOG, "changingIndex, newLang=" + index.longName);
\r
524 setListAdapter(indexAdapter);
\r
525 updateLangButton();
\r
526 searchText.requestFocus(); // Otherwise, nothing may happen.
\r
527 onSearchTextChange(searchText.getText().toString());
\r
528 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
\r
531 void onUpDownButton(final boolean up) {
\r
532 if (isFiltered()) {
\r
535 final int firstVisibleRow = getListView().getFirstVisiblePosition();
\r
536 final RowBase row = index.rows.get(firstVisibleRow);
\r
537 final TokenRow tokenRow = row.getTokenRow(true);
\r
538 final int destIndexEntry;
\r
540 if (row != tokenRow) {
\r
541 destIndexEntry = tokenRow.referenceIndex;
\r
543 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
\r
547 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
\r
549 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
\r
550 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
\r
551 searchText.removeTextChangedListener(searchTextWatcher);
\r
552 searchText.setText(dest.token);
\r
553 if (searchText.getLayout() != null) {
\r
554 // Surprising, but this can otherwise crash sometimes...
\r
555 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
\r
557 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
\r
558 searchText.addTextChangedListener(searchTextWatcher);
\r
561 // --------------------------------------------------------------------------
\r
563 // --------------------------------------------------------------------------
\r
565 final Random random = new Random();
\r
568 public boolean onCreateOptionsMenu(final Menu menu) {
\r
569 application.onCreateGlobalOptionsMenu(this, menu);
\r
572 final MenuItem randomWord = menu.add(getString(R.string.randomWord));
\r
573 randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
574 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
575 final String word = index.sortedIndexEntries.get(random.nextInt(index.sortedIndexEntries.size())).token;
\r
576 setSearchText(word, true);
\r
583 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
\r
584 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
585 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
586 startActivity(DictionaryManagerActivity.getLaunchIntent());
\r
594 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
\r
595 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
596 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
597 final Context context = getListView().getContext();
\r
598 final Dialog dialog = new Dialog(context);
\r
599 dialog.setContentView(R.layout.about_dictionary_dialog);
\r
600 final TextView textView = (TextView) dialog.findViewById(R.id.text);
\r
602 final String name = application.getDictionaryName(dictFile.getName());
\r
603 dialog.setTitle(name);
\r
605 final StringBuilder builder = new StringBuilder();
\r
606 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
\r
607 dictionaryInfo.uncompressedBytes = dictFile.length();
\r
608 if (dictionaryInfo != null) {
\r
609 builder.append(dictionaryInfo.dictInfo).append("\n\n");
\r
610 builder.append(getString(R.string.dictionaryPath, dictFile.getPath())).append("\n");
\r
611 builder.append(getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes)).append("\n");
\r
612 builder.append(getString(R.string.dictionaryCreationTime, dictionaryInfo.creationMillis)).append("\n");
\r
613 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
\r
614 builder.append("\n");
\r
615 builder.append(getString(R.string.indexName, indexInfo.shortName)).append("\n");
\r
616 builder.append(getString(R.string.mainTokenCount, indexInfo.mainTokenCount)).append("\n");
\r
618 builder.append("\n");
\r
619 builder.append(getString(R.string.sources)).append("\n");
\r
620 for (final EntrySource source : dictionary.sources) {
\r
621 builder.append(getString(R.string.sourceInfo, source.getName(), source.getNumEntries())).append("\n");
\r
625 // builder.append(getString(R.string.invalidDictionary));
\r
627 textView.setText(builder.toString());
\r
630 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
\r
631 layoutParams.width = WindowManager.LayoutParams.FILL_PARENT;
\r
632 layoutParams.height = WindowManager.LayoutParams.FILL_PARENT;
\r
633 dialog.getWindow().setAttributes(layoutParams);
\r
643 // --------------------------------------------------------------------------
\r
644 // Context Menu + clicks
\r
645 // --------------------------------------------------------------------------
\r
648 public void onCreateContextMenu(ContextMenu menu, View v,
\r
649 ContextMenuInfo menuInfo) {
\r
650 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
\r
651 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
\r
653 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList, wordList.getName()));
\r
654 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
655 public boolean onMenuItemClick(MenuItem item) {
\r
656 onAppendToWordList(row);
\r
661 final MenuItem copy = menu.add(android.R.string.copy);
\r
662 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
663 public boolean onMenuItemClick(MenuItem item) {
\r
669 if (selectedSpannableText != null) {
\r
670 final String selectedText = selectedSpannableText;
\r
671 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection, selectedSpannableText));
\r
672 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
673 public boolean onMenuItemClick(MenuItem item) {
\r
674 int indexToUse = -1;
\r
675 for (int i = 0; i < dictionary.indices.size(); ++i) {
\r
676 final Index index = dictionary.indices.get(i);
\r
677 if (indexPrepFinished) {
\r
678 System.out.println("Doing index lookup: on " + selectedText);
\r
679 final IndexEntry indexEntry = index.findExact(selectedText);
\r
680 if (indexEntry != null) {
\r
681 final TokenRow tokenRow = index.rows.get(indexEntry.startRow).getTokenRow(false);
\r
682 if (tokenRow != null && tokenRow.hasMainEntry) {
\r
688 Log.w(LOG, "Skipping findExact on index " + index.shortName);
\r
691 if (indexToUse == -1) {
\r
692 indexToUse = selectedSpannableIndex;
\r
694 final boolean changeIndex = indexIndex != indexToUse;
\r
695 setSearchText(selectedText, !changeIndex); // If we're not changing index, we have to triggerSearch.
\r
697 changeIndexGetFocusAndResearch(indexToUse);
\r
699 // Give focus back to list view because typing is done.
\r
700 getListView().requestFocus();
\r
710 protected void onListItemClick(ListView l, View v, int row, long id) {
\r
711 defocusSearchText();
\r
712 if (clickOpensContextMenu && dictRaf != null) {
\r
713 openContextMenu(v);
\r
717 void onAppendToWordList(final RowBase row) {
\r
718 defocusSearchText();
\r
720 final StringBuilder rawText = new StringBuilder();
\r
722 new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date()))
\r
724 rawText.append(index.longName).append("\t");
\r
725 rawText.append(row.getTokenRow(true).getToken()).append("\t");
\r
726 rawText.append(row.getRawText(saveOnlyFirstSubentry));
\r
727 Log.d(LOG, "Writing : " + rawText);
\r
730 wordList.getParentFile().mkdirs();
\r
731 final PrintWriter out = new PrintWriter(
\r
732 new FileWriter(wordList, true));
\r
733 out.println(rawText.toString());
\r
735 } catch (IOException e) {
\r
736 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
\r
737 Toast.makeText(this, getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()), Toast.LENGTH_LONG);
\r
743 * Called when user clicks outside of search text, so that they can start
\r
744 * typing again immediately.
\r
746 void defocusSearchText() {
\r
747 //Log.d(LOG, "defocusSearchText");
\r
748 // Request focus so that if we start typing again, it clears the text input.
\r
749 getListView().requestFocus();
\r
751 // Visual indication that a new keystroke will clear the search text.
\r
752 searchText.selectAll();
\r
755 void onCopy(final RowBase row) {
\r
756 defocusSearchText();
\r
758 Log.d(LOG, "Copy, row=" + row);
\r
759 final StringBuilder result = new StringBuilder();
\r
760 result.append(row.getRawText(false));
\r
761 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
\r
762 clipboardManager.setText(result.toString());
\r
763 Log.d(LOG, "Copied: " + result);
\r
767 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
\r
768 if (event.getUnicodeChar() != 0) {
\r
769 if (!searchText.hasFocus()) {
\r
770 setSearchText("" + (char) event.getUnicodeChar(), true);
\r
774 if (keyCode == KeyEvent.KEYCODE_BACK) {
\r
775 //Log.d(LOG, "Clearing dictionary prefs.");
\r
776 // Pretend that we just autolaunched so that we won't do it again.
\r
777 //DictionaryManagerActivity.lastAutoLaunchMillis = System.currentTimeMillis();
\r
779 if (keyCode == KeyEvent.KEYCODE_ENTER) {
\r
780 Log.d(LOG, "Trying to hide soft keyboard.");
\r
781 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
782 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
\r
785 return super.onKeyDown(keyCode, event);
\r
788 private void setSearchText(final String text, final boolean triggerSearch) {
\r
789 if (!triggerSearch) {
\r
790 getListView().requestFocus();
\r
792 searchText.setText(text);
\r
793 searchText.requestFocus();
\r
794 if (searchText.getLayout() != null) {
\r
795 // Surprising, but this can crash when you rotate...
\r
796 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
\r
798 if (triggerSearch) {
\r
799 onSearchTextChange(text);
\r
804 // --------------------------------------------------------------------------
\r
806 // --------------------------------------------------------------------------
\r
808 private void searchFinished(final SearchOperation searchOperation) {
\r
809 if (searchOperation.interrupted.get()) {
\r
810 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
\r
813 if (searchOperation != this.currentSearchOperation) {
\r
814 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
\r
818 final Index.IndexEntry searchResult = searchOperation.searchResult;
\r
819 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
\r
821 currentSearchOperation = null;
\r
822 uiHandler.postDelayed(new Runnable() {
\r
824 public void run() {
\r
825 if (currentSearchOperation == null) {
\r
826 if (searchResult != null) {
\r
827 if (isFiltered()) {
\r
830 jumpToRow(searchResult.startRow);
\r
831 } else if (searchOperation.multiWordSearchResult != null) {
\r
832 // Multi-row search....
\r
833 setFiltered(searchOperation);
\r
835 throw new IllegalStateException("This should never happen.");
\r
838 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
\r
845 private final void jumpToRow(final int row) {
\r
847 getListView().setSelected(true);
\r
850 static final Pattern WHITESPACE = Pattern.compile("\\s+");
\r
851 final class SearchOperation implements Runnable {
\r
853 final AtomicBoolean interrupted = new AtomicBoolean(false);
\r
854 final String searchText;
\r
855 List<String> searchTokens; // filled in for multiWord.
\r
858 long searchStartMillis;
\r
860 Index.IndexEntry searchResult;
\r
861 List<RowBase> multiWordSearchResult;
\r
863 boolean done = false;
\r
865 SearchOperation(final String searchText, final Index index) {
\r
866 this.searchText = searchText.trim();
\r
867 this.index = index;
\r
870 public String toString() {
\r
871 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
\r
875 public void run() {
\r
877 searchStartMillis = System.currentTimeMillis();
\r
878 final String[] searchTokenArray = WHITESPACE.split(searchText);
\r
879 if (searchTokenArray.length == 1) {
\r
880 searchResult = index.findInsertionPoint(searchText, interrupted);
\r
882 searchTokens = Arrays.asList(searchTokenArray);
\r
883 multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
\r
885 Log.d(LOG, "searchText=" + searchText + ", searchDuration="
\r
886 + (System.currentTimeMillis() - searchStartMillis) + ", interrupted="
\r
887 + interrupted.get());
\r
888 if (!interrupted.get()) {
\r
889 uiHandler.post(new Runnable() {
\r
891 public void run() {
\r
892 searchFinished(SearchOperation.this);
\r
896 } catch (Exception e) {
\r
897 Log.e(LOG, "Failure during search (can happen during Activity close.");
\r
899 synchronized (this) {
\r
908 // --------------------------------------------------------------------------
\r
910 // --------------------------------------------------------------------------
\r
912 final class IndexAdapter extends BaseAdapter {
\r
915 final List<RowBase> rows;
\r
916 final Set<String> toHighlight;
\r
918 IndexAdapter(final Index index) {
\r
919 this.index = index;
\r
921 this.toHighlight = null;
\r
924 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
\r
925 this.index = index;
\r
927 this.toHighlight = new LinkedHashSet<String>(toHighlight);
\r
931 public int getCount() {
\r
932 return rows.size();
\r
936 public RowBase getItem(int position) {
\r
937 return rows.get(position);
\r
941 public long getItemId(int position) {
\r
942 return getItem(position).index();
\r
946 public TableLayout getView(int position, View convertView, ViewGroup parent) {
\r
947 final TableLayout result;
\r
948 if (convertView instanceof TableLayout) {
\r
949 result = (TableLayout) convertView;
\r
950 result.removeAllViews();
\r
952 result = new TableLayout(parent.getContext());
\r
954 final RowBase row = getItem(position);
\r
955 if (row instanceof PairEntry.Row) {
\r
956 return getView(position, (PairEntry.Row) row, parent, result);
\r
957 } else if (row instanceof TokenRow) {
\r
958 return getView((TokenRow) row, parent, result);
\r
960 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
\r
964 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent, final TableLayout result) {
\r
965 final PairEntry entry = row.getEntry();
\r
966 final int rowCount = entry.pairs.size();
\r
968 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
\r
969 layoutParams.weight = 0.5f;
\r
971 for (int r = 0; r < rowCount; ++r) {
\r
972 final TableRow tableRow = new TableRow(result.getContext());
\r
974 final TextView col1 = new TextView(tableRow.getContext());
\r
975 final TextView col2 = new TextView(tableRow.getContext());
\r
977 // Set the columns in the table.
\r
979 final TextView bullet = new TextView(tableRow.getContext());
\r
980 bullet.setText(" • ");
\r
981 tableRow.addView(bullet);
\r
983 tableRow.addView(col1, layoutParams);
\r
984 final TextView margin = new TextView(tableRow.getContext());
\r
985 margin.setText(" ");
\r
986 tableRow.addView(margin);
\r
988 final TextView bullet = new TextView(tableRow.getContext());
\r
989 bullet.setText(" • ");
\r
990 tableRow.addView(bullet);
\r
992 tableRow.addView(col2, layoutParams);
\r
996 // Set what's in the columns.
\r
998 final Pair pair = entry.pairs.get(r);
\r
999 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
\r
1000 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
\r
1002 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
\r
1003 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
\r
1005 // Bold the token instances in col1.
\r
1006 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections.singleton(row.getTokenRow(true).getToken());
\r
1007 final Spannable col1Spannable = (Spannable) col1.getText();
\r
1008 for (final String token : toBold) {
\r
1010 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
\r
1011 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos,
\r
1012 startPos + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
1013 startPos += token.length();
\r
1017 createTokenLinkSpans(col1, col1Spannable, col1Text);
\r
1018 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
\r
1020 col1.setTypeface(typeface);
\r
1021 col2.setTypeface(typeface);
\r
1022 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
1023 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
1024 // col2.setBackgroundResource(theme.otherLangBg);
\r
1026 if (index.swapPairEntries) {
\r
1027 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
1028 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
1030 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
1031 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
1034 result.addView(tableRow);
\r
1037 // Because we have a Button inside a ListView row:
\r
1038 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
\r
1039 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
\r
1040 result.setClickable(true);
\r
1041 result.setFocusable(true);
\r
1042 result.setLongClickable(true);
\r
1043 result.setBackgroundResource(android.R.drawable.menuitem_background);
\r
1044 result.setOnClickListener(new TextView.OnClickListener() {
\r
1046 public void onClick(View v) {
\r
1047 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
\r
1054 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
\r
1055 final Context context = parent.getContext();
\r
1056 final TextView textView = new TextView(context);
\r
1057 textView.setText(row.getToken());
\r
1059 //textView.setTextColor(android.R.color.secondary_text_light);
\r
1060 textView.setTextAppearance(context, theme.tokenRowFg);
\r
1061 textView.setTypeface(typeface);
\r
1062 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
\r
1064 final TableRow tableRow = new TableRow(result.getContext());
\r
1065 tableRow.addView(textView);
\r
1066 tableRow.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg : theme.tokenRowOtherBg);
\r
1067 result.addView(tableRow);
\r
1073 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
\r
1075 private void createTokenLinkSpans(final TextView textView, final Spannable spannable, final String text) {
\r
1076 // Saw from the source code that LinkMovementMethod sets the selection!
\r
1077 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
\r
1078 textView.setMovementMethod(LinkMovementMethod.getInstance());
\r
1079 final Matcher matcher = CHAR_DASH.matcher(text);
\r
1080 while (matcher.find()) {
\r
1081 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
1086 String selectedSpannableText = null;
\r
1087 int selectedSpannableIndex = -1;
\r
1090 public boolean onTouchEvent(MotionEvent event) {
\r
1091 selectedSpannableText = null;
\r
1092 selectedSpannableIndex = -1;
\r
1093 return super.onTouchEvent(event);
\r
1096 private class TextViewLongClickListener implements OnLongClickListener {
\r
1099 private TextViewLongClickListener(final int index) {
\r
1100 this.index = index;
\r
1104 public boolean onLongClick(final View v) {
\r
1105 final TextView textView = (TextView) v;
\r
1106 final int start = textView.getSelectionStart();
\r
1107 final int end = textView.getSelectionEnd();
\r
1108 if (start >= 0 && end >= 0) {
\r
1109 selectedSpannableText = textView.getText().subSequence(start, end).toString();
\r
1110 selectedSpannableIndex = index;
\r
1115 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(0);
\r
1116 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(1);
\r
1119 // --------------------------------------------------------------------------
\r
1121 // --------------------------------------------------------------------------
\r
1123 void onSearchTextChange(final String text) {
\r
1124 if ("thadolina".equals(text)) {
\r
1125 final Dialog dialog = new Dialog(getListView().getContext());
\r
1126 dialog.setContentView(R.layout.thadolina_dialog);
\r
1127 dialog.setTitle("Ti amo, amore mio!");
\r
1128 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
\r
1129 imageView.setOnClickListener(new OnClickListener() {
\r
1131 public void onClick(View v) {
\r
1132 final Intent intent = new Intent(Intent.ACTION_VIEW);
\r
1133 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
\r
1134 startActivity(intent);
\r
1139 if (dictRaf == null) {
\r
1140 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
\r
1143 if (!searchText.isFocused()) {
\r
1144 Log.d(LOG, "searchText changed without focus, doing nothing.");
\r
1147 Log.d(LOG, "onSearchTextChange: " + text);
\r
1148 if (currentSearchOperation != null) {
\r
1149 Log.d(LOG, "Interrupting currentSearchOperation.");
\r
1150 currentSearchOperation.interrupted.set(true);
\r
1152 currentSearchOperation = new SearchOperation(text, index);
\r
1153 searchExecutor.execute(currentSearchOperation);
\r
1156 private class SearchTextWatcher implements TextWatcher {
\r
1157 public void afterTextChanged(final Editable searchTextEditable) {
\r
1158 if (searchText.hasFocus()) {
\r
1159 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
\r
1160 // If they were typing to cause the change, update the UI.
\r
1161 onSearchTextChange(searchText.getText().toString());
\r
1165 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
\r
1169 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
\r
1173 // --------------------------------------------------------------------------
\r
1174 // Filtered results.
\r
1175 // --------------------------------------------------------------------------
\r
1177 boolean isFiltered() {
\r
1178 return rowsToShow != null;
\r
1181 void setFiltered(final SearchOperation searchOperation) {
\r
1182 ((Button) findViewById(R.id.UpButton)).setEnabled(false);
\r
1183 ((Button) findViewById(R.id.DownButton)).setEnabled(false);
\r
1184 rowsToShow = searchOperation.multiWordSearchResult;
\r
1185 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
\r
1188 void clearFiltered() {
\r
1189 ((Button) findViewById(R.id.UpButton)).setEnabled(true);
\r
1190 ((Button) findViewById(R.id.DownButton)).setEnabled(true);
\r
1191 setListAdapter(new IndexAdapter(index));
\r
1192 rowsToShow = null;
\r