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
251 final int fontWorkAround = prefs.getInt(C.FONT_WORKAROUND, 1);
\r
252 if (fontWorkAround == 0) {
\r
253 Log.w(LOG, "Loading font seemed to fail last time, trying with default font.");
\r
254 Toast.makeText(this, getString(R.string.fontWorkaround), Toast.LENGTH_LONG).show();
\r
255 prefs.edit().putString(getString(R.string.fontKey), "SYSTEM").commit();
\r
257 prefs.edit().putInt(C.FONT_WORKAROUND, 0).commit();
\r
258 String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
\r
259 if (fontWorkAround == 0 || "SYSTEM".equals(fontName)) {
\r
260 typeface = Typeface.DEFAULT;
\r
263 typeface = Typeface.createFromAsset(getAssets(), fontName);
\r
264 } catch (Exception e) {
\r
265 Log.w(LOG, "Exception trying to use typeface, using default.", e);
\r
266 Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()), Toast.LENGTH_LONG).show();
\r
269 // if (!"SYSTEM".equals(fontName)) {
\r
270 // throw new RuntimeException("Test force using system font: " + fontName);
\r
272 if (typeface == null) {
\r
273 Log.w(LOG, "Unable to create typeface, using default.");
\r
274 typeface = Typeface.DEFAULT;
\r
276 final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
\r
278 fontSizeSp = Integer.parseInt(fontSize.trim());
\r
279 } catch (NumberFormatException e) {
\r
284 setContentView(R.layout.dictionary_activity);
\r
285 searchText = (EditText) findViewById(R.id.SearchText);
\r
286 searchText.setTypeface(typeface);
\r
287 searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
289 langButton = (Button) findViewById(R.id.LangButton);
\r
291 searchText.requestFocus();
\r
292 searchText.addTextChangedListener(searchTextWatcher);
\r
294 // Set the search text from the intent, then the saved state.
\r
295 String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
\r
296 if (savedInstanceState != null) {
\r
297 text = savedInstanceState.getString(C.SEARCH_TOKEN);
\r
299 if (text == null) {
\r
302 setSearchText(text, true);
\r
303 Log.d(LOG, "Trying to restore searchText=" + text);
\r
305 final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
\r
306 clearSearchTextButton.setOnClickListener(new OnClickListener() {
\r
307 public void onClick(View v) {
\r
308 onClearSearchTextButton(clearSearchTextButton);
\r
311 clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
\r
312 getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
\r
315 final Button langButton = (Button) findViewById(R.id.LangButton);
\r
316 langButton.setOnClickListener(new OnClickListener() {
\r
317 public void onClick(View v) {
\r
318 onLanguageButton();
\r
321 langButton.setOnLongClickListener(new OnLongClickListener() {
\r
323 public boolean onLongClick(View v) {
\r
324 onLanguageButtonLongClick(v.getContext());
\r
328 updateLangButton();
\r
330 final Button upButton = (Button) findViewById(R.id.UpButton);
\r
331 upButton.setOnClickListener(new OnClickListener() {
\r
332 public void onClick(View v) {
\r
333 onUpDownButton(true);
\r
336 final Button downButton = (Button) findViewById(R.id.DownButton);
\r
337 downButton.setOnClickListener(new OnClickListener() {
\r
338 public void onClick(View v) {
\r
339 onUpDownButton(false);
\r
343 getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
\r
345 public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
\r
347 if (!searchText.isFocused()) {
\r
348 if (!isFiltered()) {
\r
349 final RowBase row = (RowBase) getListAdapter().getItem(position);
\r
350 Log.d(LOG, "onItemSelected: " + row.index());
\r
351 final TokenRow tokenRow = row.getTokenRow(true);
\r
352 searchText.setText(tokenRow.getToken());
\r
358 public void onNothingSelected(AdapterView<?> arg0) {
\r
363 registerForContextMenu(getListView());
\r
366 wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
\r
367 getString(R.string.wordListFileDefault)));
\r
368 saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey), false);
\r
369 clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey), false);
\r
370 //if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey), true)) {
\r
371 // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
\r
373 Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
\r
375 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
\r
379 protected void onResume() {
\r
381 if (PreferenceActivity.prefsMightHaveChanged) {
\r
382 PreferenceActivity.prefsMightHaveChanged = false;
\r
384 startActivity(getIntent());
\r
386 if (initialSearchText != null) {
\r
387 setSearchText(initialSearchText, true);
\r
392 protected void onPause() {
\r
395 // If the app exits normally, this will happen.
\r
396 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
\r
397 Log.d(LOG, "Loading font seemed to work.");
\r
398 prefs.edit().putInt(C.FONT_WORKAROUND, 1).commit();
\r
401 private static void setDictionaryPrefs(final Context context,
\r
402 final File dictFile, final int indexIndex, final String searchToken) {
\r
403 final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
\r
404 prefs.putString(C.DICT_FILE, dictFile.getPath());
\r
405 prefs.putInt(C.INDEX_INDEX, indexIndex);
\r
406 prefs.putString(C.SEARCH_TOKEN, searchToken);
\r
411 protected void onDestroy() {
\r
413 if (dictRaf == null) {
\r
417 final SearchOperation searchOperation = currentSearchOperation;
\r
418 currentSearchOperation = null;
\r
420 // Before we close the RAF, we have to wind the current search down.
\r
421 if (searchOperation != null) {
\r
422 Log.d(LOG, "Interrupting search to shut down.");
\r
423 currentSearchOperation = null;
\r
424 searchOperation.interrupted.set(true);
\r
428 Log.d(LOG, "Closing RAF.");
\r
430 } catch (IOException e) {
\r
431 Log.e(LOG, "Failed to close dictionary", e);
\r
436 // --------------------------------------------------------------------------
\r
438 // --------------------------------------------------------------------------
\r
440 private void onClearSearchTextButton(final Button clearSearchTextButton) {
\r
441 setSearchText("", true);
\r
442 Log.d(LOG, "Trying to show soft keyboard.");
\r
443 final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
444 manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
\r
447 void updateLangButton() {
\r
448 // final LanguageResources languageResources = Language.isoCodeToResources.get(index.shortName);
\r
449 // if (languageResources != null && languageResources.flagId != 0) {
\r
450 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, languageResources.flagId, 0);
\r
452 // langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
\r
453 langButton.setText(index.shortName);
\r
457 void onLanguageButton() {
\r
458 if (currentSearchOperation != null) {
\r
459 currentSearchOperation.interrupted.set(true);
\r
460 currentSearchOperation = null;
\r
462 changeIndexGetFocusAndResearch((indexIndex + 1)% dictionary.indices.size());
\r
465 void onLanguageButtonLongClick(final Context context) {
\r
466 final Dialog dialog = new Dialog(context);
\r
467 dialog.setContentView(R.layout.select_dictionary_dialog);
\r
468 dialog.setTitle(R.string.selectDictionary);
\r
470 final List<DictionaryInfo> installedDicts = ((DictionaryApplication)getApplication()).getUsableDicts();
\r
472 ListView listView = (ListView) dialog.findViewById(android.R.id.list);
\r
474 // final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
\r
475 // layoutParams.width = 0;
\r
476 // layoutParams.weight = 1.0f;
\r
478 final Button button = new Button(listView.getContext());
\r
479 final String name = getString(R.string.dictionaryManager);
\r
480 button.setText(name);
\r
481 final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(), DictionaryManagerActivity.getLaunchIntent()) {
\r
483 protected void onGo() {
\r
485 DictionaryActivity.this.finish();
\r
488 button.setOnClickListener(intentLauncher);
\r
489 // button.setLayoutParams(layoutParams);
\r
490 listView.addHeaderView(button);
\r
491 // listView.setHeaderDividersEnabled(true);
\r
493 listView.setAdapter(new BaseAdapter() {
\r
495 public View getView(int position, View convertView, ViewGroup parent) {
\r
496 final LinearLayout result = new LinearLayout(parent.getContext());
\r
498 final DictionaryInfo dictionaryInfo = getItem(position);
\r
499 final Button button = new Button(parent.getContext());
\r
500 final String name = application.getDictionaryName(dictionaryInfo.uncompressedFilename);
\r
501 button.setText(name);
\r
502 final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(), getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename), 0, searchText.getText().toString())) {
\r
504 protected void onGo() {
\r
506 DictionaryActivity.this.finish();
\r
509 button.setOnClickListener(intentLauncher);
\r
510 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
\r
511 layoutParams.width = 0;
\r
512 layoutParams.weight = 1.0f;
\r
513 button.setLayoutParams(layoutParams);
\r
514 result.addView(button);
\r
519 public long getItemId(int position) {
\r
524 public DictionaryInfo getItem(int position) {
\r
525 return installedDicts.get(position);
\r
529 public int getCount() {
\r
530 return installedDicts.size();
\r
538 private void changeIndexGetFocusAndResearch(final int newIndex) {
\r
539 indexIndex = newIndex;
\r
540 index = dictionary.indices.get(indexIndex);
\r
541 indexAdapter = new IndexAdapter(index);
\r
542 Log.d(LOG, "changingIndex, newLang=" + index.longName);
\r
543 setListAdapter(indexAdapter);
\r
544 updateLangButton();
\r
545 searchText.requestFocus(); // Otherwise, nothing may happen.
\r
546 onSearchTextChange(searchText.getText().toString());
\r
547 setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
\r
550 void onUpDownButton(final boolean up) {
\r
551 if (isFiltered()) {
\r
554 final int firstVisibleRow = getListView().getFirstVisiblePosition();
\r
555 final RowBase row = index.rows.get(firstVisibleRow);
\r
556 final TokenRow tokenRow = row.getTokenRow(true);
\r
557 final int destIndexEntry;
\r
559 if (row != tokenRow) {
\r
560 destIndexEntry = tokenRow.referenceIndex;
\r
562 destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
\r
566 destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
\r
568 final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
\r
569 Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
\r
570 searchText.removeTextChangedListener(searchTextWatcher);
\r
571 searchText.setText(dest.token);
\r
572 if (searchText.getLayout() != null) {
\r
573 // Surprising, but this can otherwise crash sometimes...
\r
574 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
\r
576 jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
\r
577 searchText.addTextChangedListener(searchTextWatcher);
\r
580 // --------------------------------------------------------------------------
\r
582 // --------------------------------------------------------------------------
\r
584 final Random random = new Random();
\r
587 public boolean onCreateOptionsMenu(final Menu menu) {
\r
588 application.onCreateGlobalOptionsMenu(this, menu);
\r
591 final MenuItem randomWord = menu.add(getString(R.string.randomWord));
\r
592 randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
593 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
594 final String word = index.sortedIndexEntries.get(random.nextInt(index.sortedIndexEntries.size())).token;
\r
595 setSearchText(word, true);
\r
602 final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
\r
603 dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
604 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
605 startActivity(DictionaryManagerActivity.getLaunchIntent());
\r
613 final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
\r
614 aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
615 public boolean onMenuItemClick(final MenuItem menuItem) {
\r
616 final Context context = getListView().getContext();
\r
617 final Dialog dialog = new Dialog(context);
\r
618 dialog.setContentView(R.layout.about_dictionary_dialog);
\r
619 final TextView textView = (TextView) dialog.findViewById(R.id.text);
\r
621 final String name = application.getDictionaryName(dictFile.getName());
\r
622 dialog.setTitle(name);
\r
624 final StringBuilder builder = new StringBuilder();
\r
625 final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
\r
626 dictionaryInfo.uncompressedBytes = dictFile.length();
\r
627 if (dictionaryInfo != null) {
\r
628 builder.append(dictionaryInfo.dictInfo).append("\n\n");
\r
629 builder.append(getString(R.string.dictionaryPath, dictFile.getPath())).append("\n");
\r
630 builder.append(getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes)).append("\n");
\r
631 builder.append(getString(R.string.dictionaryCreationTime, dictionaryInfo.creationMillis)).append("\n");
\r
632 for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
\r
633 builder.append("\n");
\r
634 builder.append(getString(R.string.indexName, indexInfo.shortName)).append("\n");
\r
635 builder.append(getString(R.string.mainTokenCount, indexInfo.mainTokenCount)).append("\n");
\r
637 builder.append("\n");
\r
638 builder.append(getString(R.string.sources)).append("\n");
\r
639 for (final EntrySource source : dictionary.sources) {
\r
640 builder.append(getString(R.string.sourceInfo, source.getName(), source.getNumEntries())).append("\n");
\r
644 // builder.append(getString(R.string.invalidDictionary));
\r
646 textView.setText(builder.toString());
\r
649 final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
\r
650 layoutParams.width = WindowManager.LayoutParams.FILL_PARENT;
\r
651 layoutParams.height = WindowManager.LayoutParams.FILL_PARENT;
\r
652 dialog.getWindow().setAttributes(layoutParams);
\r
662 // --------------------------------------------------------------------------
\r
663 // Context Menu + clicks
\r
664 // --------------------------------------------------------------------------
\r
667 public void onCreateContextMenu(ContextMenu menu, View v,
\r
668 ContextMenuInfo menuInfo) {
\r
669 AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
\r
670 final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
\r
672 final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList, wordList.getName()));
\r
673 addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
674 public boolean onMenuItemClick(MenuItem item) {
\r
675 onAppendToWordList(row);
\r
680 final MenuItem copy = menu.add(android.R.string.copy);
\r
681 copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
682 public boolean onMenuItemClick(MenuItem item) {
\r
688 if (selectedSpannableText != null) {
\r
689 final String selectedText = selectedSpannableText;
\r
690 final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection, selectedSpannableText));
\r
691 searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
\r
692 public boolean onMenuItemClick(MenuItem item) {
\r
693 int indexToUse = -1;
\r
694 for (int i = 0; i < dictionary.indices.size(); ++i) {
\r
695 final Index index = dictionary.indices.get(i);
\r
696 if (indexPrepFinished) {
\r
697 System.out.println("Doing index lookup: on " + selectedText);
\r
698 final IndexEntry indexEntry = index.findExact(selectedText);
\r
699 if (indexEntry != null) {
\r
700 final TokenRow tokenRow = index.rows.get(indexEntry.startRow).getTokenRow(false);
\r
701 if (tokenRow != null && tokenRow.hasMainEntry) {
\r
707 Log.w(LOG, "Skipping findExact on index " + index.shortName);
\r
710 if (indexToUse == -1) {
\r
711 indexToUse = selectedSpannableIndex;
\r
713 final boolean changeIndex = indexIndex != indexToUse;
\r
714 setSearchText(selectedText, !changeIndex); // If we're not changing index, we have to triggerSearch.
\r
716 changeIndexGetFocusAndResearch(indexToUse);
\r
718 // Give focus back to list view because typing is done.
\r
719 getListView().requestFocus();
\r
729 protected void onListItemClick(ListView l, View v, int row, long id) {
\r
730 defocusSearchText();
\r
731 if (clickOpensContextMenu && dictRaf != null) {
\r
732 openContextMenu(v);
\r
736 void onAppendToWordList(final RowBase row) {
\r
737 defocusSearchText();
\r
739 final StringBuilder rawText = new StringBuilder();
\r
741 new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date()))
\r
743 rawText.append(index.longName).append("\t");
\r
744 rawText.append(row.getTokenRow(true).getToken()).append("\t");
\r
745 rawText.append(row.getRawText(saveOnlyFirstSubentry));
\r
746 Log.d(LOG, "Writing : " + rawText);
\r
749 wordList.getParentFile().mkdirs();
\r
750 final PrintWriter out = new PrintWriter(
\r
751 new FileWriter(wordList, true));
\r
752 out.println(rawText.toString());
\r
754 } catch (IOException e) {
\r
755 Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
\r
756 Toast.makeText(this, getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()), Toast.LENGTH_LONG);
\r
762 * Called when user clicks outside of search text, so that they can start
\r
763 * typing again immediately.
\r
765 void defocusSearchText() {
\r
766 //Log.d(LOG, "defocusSearchText");
\r
767 // Request focus so that if we start typing again, it clears the text input.
\r
768 getListView().requestFocus();
\r
770 // Visual indication that a new keystroke will clear the search text.
\r
771 searchText.selectAll();
\r
774 void onCopy(final RowBase row) {
\r
775 defocusSearchText();
\r
777 Log.d(LOG, "Copy, row=" + row);
\r
778 final StringBuilder result = new StringBuilder();
\r
779 result.append(row.getRawText(false));
\r
780 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
\r
781 clipboardManager.setText(result.toString());
\r
782 Log.d(LOG, "Copied: " + result);
\r
786 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
\r
787 if (event.getUnicodeChar() != 0) {
\r
788 if (!searchText.hasFocus()) {
\r
789 setSearchText("" + (char) event.getUnicodeChar(), true);
\r
793 if (keyCode == KeyEvent.KEYCODE_BACK) {
\r
794 //Log.d(LOG, "Clearing dictionary prefs.");
\r
795 // Pretend that we just autolaunched so that we won't do it again.
\r
796 //DictionaryManagerActivity.lastAutoLaunchMillis = System.currentTimeMillis();
\r
798 if (keyCode == KeyEvent.KEYCODE_ENTER) {
\r
799 Log.d(LOG, "Trying to hide soft keyboard.");
\r
800 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
\r
801 inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
\r
804 return super.onKeyDown(keyCode, event);
\r
807 private void setSearchText(final String text, final boolean triggerSearch) {
\r
808 if (!triggerSearch) {
\r
809 getListView().requestFocus();
\r
811 searchText.setText(text);
\r
812 searchText.requestFocus();
\r
813 moveCursorToRight();
\r
814 if (triggerSearch) {
\r
815 onSearchTextChange(text);
\r
819 private long cursorDelayMillis = 100;
\r
820 private void moveCursorToRight() {
\r
821 if (searchText.getLayout() != null) {
\r
822 cursorDelayMillis = 100;
\r
823 // Surprising, but this can crash when you rotate...
\r
824 Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
\r
826 uiHandler.postDelayed(new Runnable() {
\r
828 public void run() {
\r
829 moveCursorToRight();
\r
831 }, cursorDelayMillis);
\r
832 cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
\r
837 // --------------------------------------------------------------------------
\r
839 // --------------------------------------------------------------------------
\r
841 private void searchFinished(final SearchOperation searchOperation) {
\r
842 if (searchOperation.interrupted.get()) {
\r
843 Log.d(LOG, "Search operation was interrupted: " + searchOperation);
\r
846 if (searchOperation != this.currentSearchOperation) {
\r
847 Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
\r
851 final Index.IndexEntry searchResult = searchOperation.searchResult;
\r
852 Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
\r
854 currentSearchOperation = null;
\r
855 uiHandler.postDelayed(new Runnable() {
\r
857 public void run() {
\r
858 if (currentSearchOperation == null) {
\r
859 if (searchResult != null) {
\r
860 if (isFiltered()) {
\r
863 jumpToRow(searchResult.startRow);
\r
864 } else if (searchOperation.multiWordSearchResult != null) {
\r
865 // Multi-row search....
\r
866 setFiltered(searchOperation);
\r
868 throw new IllegalStateException("This should never happen.");
\r
871 Log.d(LOG, "More coming, waiting for currentSearchOperation.");
\r
878 private final void jumpToRow(final int row) {
\r
880 getListView().setSelected(true);
\r
883 static final Pattern WHITESPACE = Pattern.compile("\\s+");
\r
884 final class SearchOperation implements Runnable {
\r
886 final AtomicBoolean interrupted = new AtomicBoolean(false);
\r
887 final String searchText;
\r
888 List<String> searchTokens; // filled in for multiWord.
\r
891 long searchStartMillis;
\r
893 Index.IndexEntry searchResult;
\r
894 List<RowBase> multiWordSearchResult;
\r
896 boolean done = false;
\r
898 SearchOperation(final String searchText, final Index index) {
\r
899 this.searchText = searchText.trim();
\r
900 this.index = index;
\r
903 public String toString() {
\r
904 return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
\r
908 public void run() {
\r
910 searchStartMillis = System.currentTimeMillis();
\r
911 final String[] searchTokenArray = WHITESPACE.split(searchText);
\r
912 if (searchTokenArray.length == 1) {
\r
913 searchResult = index.findInsertionPoint(searchText, interrupted);
\r
915 searchTokens = Arrays.asList(searchTokenArray);
\r
916 multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
\r
918 Log.d(LOG, "searchText=" + searchText + ", searchDuration="
\r
919 + (System.currentTimeMillis() - searchStartMillis) + ", interrupted="
\r
920 + interrupted.get());
\r
921 if (!interrupted.get()) {
\r
922 uiHandler.post(new Runnable() {
\r
924 public void run() {
\r
925 searchFinished(SearchOperation.this);
\r
929 } catch (Exception e) {
\r
930 Log.e(LOG, "Failure during search (can happen during Activity close.");
\r
932 synchronized (this) {
\r
941 // --------------------------------------------------------------------------
\r
943 // --------------------------------------------------------------------------
\r
945 final class IndexAdapter extends BaseAdapter {
\r
948 final List<RowBase> rows;
\r
949 final Set<String> toHighlight;
\r
951 IndexAdapter(final Index index) {
\r
952 this.index = index;
\r
954 this.toHighlight = null;
\r
957 IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
\r
958 this.index = index;
\r
960 this.toHighlight = new LinkedHashSet<String>(toHighlight);
\r
964 public int getCount() {
\r
965 return rows.size();
\r
969 public RowBase getItem(int position) {
\r
970 return rows.get(position);
\r
974 public long getItemId(int position) {
\r
975 return getItem(position).index();
\r
979 public TableLayout getView(int position, View convertView, ViewGroup parent) {
\r
980 final TableLayout result;
\r
981 if (convertView instanceof TableLayout) {
\r
982 result = (TableLayout) convertView;
\r
983 result.removeAllViews();
\r
985 result = new TableLayout(parent.getContext());
\r
987 final RowBase row = getItem(position);
\r
988 if (row instanceof PairEntry.Row) {
\r
989 return getView(position, (PairEntry.Row) row, parent, result);
\r
990 } else if (row instanceof TokenRow) {
\r
991 return getView((TokenRow) row, parent, result);
\r
993 throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
\r
997 private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent, final TableLayout result) {
\r
998 final PairEntry entry = row.getEntry();
\r
999 final int rowCount = entry.pairs.size();
\r
1001 final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
\r
1002 layoutParams.weight = 0.5f;
\r
1004 for (int r = 0; r < rowCount; ++r) {
\r
1005 final TableRow tableRow = new TableRow(result.getContext());
\r
1007 final TextView col1 = new TextView(tableRow.getContext());
\r
1008 final TextView col2 = new TextView(tableRow.getContext());
\r
1010 // Set the columns in the table.
\r
1012 final TextView bullet = new TextView(tableRow.getContext());
\r
1013 bullet.setText(" • ");
\r
1014 tableRow.addView(bullet);
\r
1016 tableRow.addView(col1, layoutParams);
\r
1017 final TextView margin = new TextView(tableRow.getContext());
\r
1018 margin.setText(" ");
\r
1019 tableRow.addView(margin);
\r
1021 final TextView bullet = new TextView(tableRow.getContext());
\r
1022 bullet.setText(" • ");
\r
1023 tableRow.addView(bullet);
\r
1025 tableRow.addView(col2, layoutParams);
\r
1029 // Set what's in the columns.
\r
1031 final Pair pair = entry.pairs.get(r);
\r
1032 final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
\r
1033 final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
\r
1035 col1.setText(col1Text, TextView.BufferType.SPANNABLE);
\r
1036 col2.setText(col2Text, TextView.BufferType.SPANNABLE);
\r
1038 // Bold the token instances in col1.
\r
1039 final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections.singleton(row.getTokenRow(true).getToken());
\r
1040 final Spannable col1Spannable = (Spannable) col1.getText();
\r
1041 for (final String token : toBold) {
\r
1043 while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
\r
1044 col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos,
\r
1045 startPos + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
1046 startPos += token.length();
\r
1050 createTokenLinkSpans(col1, col1Spannable, col1Text);
\r
1051 createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
\r
1053 col1.setTypeface(typeface);
\r
1054 col2.setTypeface(typeface);
\r
1055 col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
1056 col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
\r
1057 // col2.setBackgroundResource(theme.otherLangBg);
\r
1059 if (index.swapPairEntries) {
\r
1060 col2.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
1061 col1.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
1063 col1.setOnLongClickListener(textViewLongClickListenerIndex0);
\r
1064 col2.setOnLongClickListener(textViewLongClickListenerIndex1);
\r
1067 result.addView(tableRow);
\r
1070 // Because we have a Button inside a ListView row:
\r
1071 // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
\r
1072 result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
\r
1073 result.setClickable(true);
\r
1074 result.setFocusable(true);
\r
1075 result.setLongClickable(true);
\r
1076 result.setBackgroundResource(android.R.drawable.menuitem_background);
\r
1077 result.setOnClickListener(new TextView.OnClickListener() {
\r
1079 public void onClick(View v) {
\r
1080 DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
\r
1087 private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
\r
1088 final Context context = parent.getContext();
\r
1089 final TextView textView = new TextView(context);
\r
1090 textView.setText(row.getToken());
\r
1092 //textView.setTextColor(android.R.color.secondary_text_light);
\r
1093 textView.setTextAppearance(context, theme.tokenRowFg);
\r
1094 textView.setTypeface(typeface);
\r
1095 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
\r
1097 final TableRow tableRow = new TableRow(result.getContext());
\r
1098 tableRow.addView(textView);
\r
1099 tableRow.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg : theme.tokenRowOtherBg);
\r
1100 result.addView(tableRow);
\r
1106 static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
\r
1108 private void createTokenLinkSpans(final TextView textView, final Spannable spannable, final String text) {
\r
1109 // Saw from the source code that LinkMovementMethod sets the selection!
\r
1110 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
\r
1111 textView.setMovementMethod(LinkMovementMethod.getInstance());
\r
1112 final Matcher matcher = CHAR_DASH.matcher(text);
\r
1113 while (matcher.find()) {
\r
1114 spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
\r
1119 String selectedSpannableText = null;
\r
1120 int selectedSpannableIndex = -1;
\r
1123 public boolean onTouchEvent(MotionEvent event) {
\r
1124 selectedSpannableText = null;
\r
1125 selectedSpannableIndex = -1;
\r
1126 return super.onTouchEvent(event);
\r
1129 private class TextViewLongClickListener implements OnLongClickListener {
\r
1132 private TextViewLongClickListener(final int index) {
\r
1133 this.index = index;
\r
1137 public boolean onLongClick(final View v) {
\r
1138 final TextView textView = (TextView) v;
\r
1139 final int start = textView.getSelectionStart();
\r
1140 final int end = textView.getSelectionEnd();
\r
1141 if (start >= 0 && end >= 0) {
\r
1142 selectedSpannableText = textView.getText().subSequence(start, end).toString();
\r
1143 selectedSpannableIndex = index;
\r
1148 final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(0);
\r
1149 final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(1);
\r
1152 // --------------------------------------------------------------------------
\r
1154 // --------------------------------------------------------------------------
\r
1156 void onSearchTextChange(final String text) {
\r
1157 if ("thadolina".equals(text)) {
\r
1158 final Dialog dialog = new Dialog(getListView().getContext());
\r
1159 dialog.setContentView(R.layout.thadolina_dialog);
\r
1160 dialog.setTitle("Ti amo, amore mio!");
\r
1161 final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
\r
1162 imageView.setOnClickListener(new OnClickListener() {
\r
1164 public void onClick(View v) {
\r
1165 final Intent intent = new Intent(Intent.ACTION_VIEW);
\r
1166 intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
\r
1167 startActivity(intent);
\r
1172 if (dictRaf == null) {
\r
1173 Log.d(LOG, "searchText changed during shutdown, doing nothing.");
\r
1176 if (!searchText.isFocused()) {
\r
1177 Log.d(LOG, "searchText changed without focus, doing nothing.");
\r
1180 Log.d(LOG, "onSearchTextChange: " + text);
\r
1181 if (currentSearchOperation != null) {
\r
1182 Log.d(LOG, "Interrupting currentSearchOperation.");
\r
1183 currentSearchOperation.interrupted.set(true);
\r
1185 currentSearchOperation = new SearchOperation(text, index);
\r
1186 searchExecutor.execute(currentSearchOperation);
\r
1189 private class SearchTextWatcher implements TextWatcher {
\r
1190 public void afterTextChanged(final Editable searchTextEditable) {
\r
1191 if (searchText.hasFocus()) {
\r
1192 Log.d(LOG, "Search text changed with focus: " + searchText.getText());
\r
1193 // If they were typing to cause the change, update the UI.
\r
1194 onSearchTextChange(searchText.getText().toString());
\r
1198 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
\r
1202 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
\r
1206 // --------------------------------------------------------------------------
\r
1207 // Filtered results.
\r
1208 // --------------------------------------------------------------------------
\r
1210 boolean isFiltered() {
\r
1211 return rowsToShow != null;
\r
1214 void setFiltered(final SearchOperation searchOperation) {
\r
1215 ((Button) findViewById(R.id.UpButton)).setEnabled(false);
\r
1216 ((Button) findViewById(R.id.DownButton)).setEnabled(false);
\r
1217 rowsToShow = searchOperation.multiWordSearchResult;
\r
1218 setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
\r
1221 void clearFiltered() {
\r
1222 ((Button) findViewById(R.id.UpButton)).setEnabled(true);
\r
1223 ((Button) findViewById(R.id.DownButton)).setEnabled(true);
\r
1224 setListAdapter(new IndexAdapter(index));
\r
1225 rowsToShow = null;
\r