}
public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
- final String searchToken) {
+ final String searchToken) {
final Intent intent = new Intent(c, DictionaryActivity.class);
intent.putExtra(C.DICT_FILE, dictFile.getPath());
intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
}
- private int getMatchLen(String search, Index.IndexEntry e)
- {
+ private int getMatchLen(String search, Index.IndexEntry e) {
if (e == null) return 0;
- for (int i = 0; i < search.length(); ++i)
- {
+ for (int i = 0; i < search.length(); ++i) {
String a = search.substring(0, i + 1);
String b = e.token.substring(0, i + 1);
if (!a.equalsIgnoreCase(b))
* -> language in which the phrase is written to -> to which
* language shall be translated
*/
- if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT"))
- {
+ if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT")) {
String query = intent.getStringExtra(SearchManager.QUERY);
String from = intent.getStringExtra("from");
if (from != null)
String to = intent.getStringExtra("to");
if (to != null)
to = to.toLowerCase(Locale.US);
- if (query != null)
- {
+ if (query != null) {
getIntent().putExtra(C.SEARCH_TOKEN, query);
}
- if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null))
- {
+ if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null)) {
Log.d(LOG, "DictSearch: from: " + from + " to " + to);
List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
- for (DictionaryInfo info : dicts)
- {
+ for (DictionaryInfo info : dicts) {
boolean hasFrom = from == null;
boolean hasTo = to == null;
- for (IndexInfo index : info.indexInfos)
- {
+ for (IndexInfo index : info.indexInfos) {
if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
hasFrom = true;
if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
hasTo = true;
}
- if (hasFrom && hasTo)
- {
- if (from != null)
- {
+ if (hasFrom && hasTo) {
+ if (from != null) {
int which_index = 0;
- for (; which_index < info.indexInfos.size(); ++which_index)
- {
+ for (; which_index < info.indexInfos.size(); ++which_index) {
if (info.indexInfos.get(which_index).shortName.toLowerCase(
- Locale.US).equals(from))
+ Locale.US).equals(from))
break;
}
intent.putExtra(C.INDEX_SHORT_NAME,
- info.indexInfos.get(which_index).shortName);
+ info.indexInfos.get(which_index).shortName);
}
intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
- .toString());
+ .toString());
break;
}
}
* simple query Arguments follow from android standard (see
* documentation)
*/
- if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH))
- {
+ if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH)) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (query != null)
getIntent().putExtra(C.SEARCH_TOKEN, query);
}
- if (intentAction != null && intentAction.equals(Intent.ACTION_SEND))
- {
+ if (intentAction != null && intentAction.equals(Intent.ACTION_SEND)) {
String query = intent.getStringExtra(Intent.EXTRA_TEXT);
if (query != null)
getIntent().putExtra(C.SEARCH_TOKEN, query);
* fail (no default dictionary specified), show a toast and
* abort.
*/
- if (intent.getStringExtra(C.DICT_FILE) == null)
- {
+ if (intent.getStringExtra(C.DICT_FILE) == null) {
String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
if (dictfile != null)
intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
}
String dictFilename = intent.getStringExtra(C.DICT_FILE);
- if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null)
- {
+ if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null) {
final List<DictionaryInfo> dics = application.getDictionariesOnDevice(null);
final String search = intent.getStringExtra(C.SEARCH_TOKEN);
String bestFname = null;
String bestIndex = null;
int bestMatchLen = 2; // ignore shorter matches
AtomicBoolean dummy = new AtomicBoolean();
- for (int i = 0; dictFilename == null && i < dics.size(); ++i)
- {
+ for (int i = 0; dictFilename == null && i < dics.size(); ++i) {
try {
Log.d(LOG, "Checking dictionary " + dics.get(i).uncompressedFilename);
final File dictfile = application.getPath(dics.get(i).uncompressedFilename);
for (int j = 0; j < dic.indices.size(); ++j) {
Index idx = dic.indices.get(j);
Log.d(LOG, "Checking index " + idx.shortName);
- if (idx.findExact(search) != null)
- {
+ if (idx.findExact(search) != null) {
Log.d(LOG, "Found exact match");
dictFilename = dictfile.toString();
intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
}
int matchLen = getMatchLen(search, idx.findInsertionPoint(search, dummy));
Log.d(LOG, "Found partial match length " + matchLen);
- if (matchLen > bestMatchLen)
- {
+ if (matchLen > bestMatchLen) {
bestFname = dictfile.toString();
bestIndex = idx.shortName;
bestMatchLen = matchLen;
}
} catch (Exception e) {}
}
- if (dictFilename == null && bestFname != null)
- {
+ if (dictFilename == null && bestFname != null) {
dictFilename = bestFname;
intent.putExtra(C.INDEX_SHORT_NAME, bestIndex);
}
}
- if (dictFilename == null)
- {
+ if (dictFilename == null) {
Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
finish();
dictRaf = null;
}
Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
- Toast.LENGTH_LONG).show();
+ Toast.LENGTH_LONG).show();
startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
finish();
return;
indexPrepFinished = true;
} catch (Exception e) {
Log.w(LOG,
- "Exception while prepping. This can happen if dictionary is closed while search is happening.");
+ "Exception while prepping. This can happen if dictionary is closed while search is happening.");
}
Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
}
String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
if ("SYSTEM".equals(fontName)) {
typeface = Typeface.DEFAULT;
- } else if ("SERIF".equals(fontName)) {
+ } else if ("SERIF".equals(fontName)) {
typeface = Typeface.SERIF;
- } else if ("SANS_SERIF".equals(fontName)) {
+ } else if ("SANS_SERIF".equals(fontName)) {
typeface = Typeface.SANS_SERIF;
- } else if ("MONOSPACE".equals(fontName)) {
+ } else if ("MONOSPACE".equals(fontName)) {
typeface = Typeface.MONOSPACE;
} else {
if ("FreeSerif.ttf.jpg".equals(fontName)) {
} catch (Exception e) {
Log.w(LOG, "Exception trying to use typeface, using default.", e);
Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
- Toast.LENGTH_LONG).show();
+ Toast.LENGTH_LONG).show();
}
}
if (typeface == null) {
// Cache some prefs.
wordList = application.getWordListFile();
saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
- false);
+ false);
clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
- false);
+ false);
Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
onCreateSetupActionBarAndSearchView();
final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
+ ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
customSearchView.setLayoutParams(layoutParams);
listView.setOnItemClickListener(new OnItemClickListener() {
searchView.setSubmitButtonEnabled(false);
searchView.setInputType(InputType.TYPE_CLASS_TEXT);
searchView.setImeOptions(
- EditorInfo.IME_ACTION_DONE |
- EditorInfo.IME_FLAG_NO_EXTRACT_UI |
- // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
- // 11
- EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
+ EditorInfo.IME_ACTION_DONE |
+ EditorInfo.IME_FLAG_NO_EXTRACT_UI |
+ // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
+ // 11
+ EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
onQueryTextListener = new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
actionBar.setCustomView(customSearchView);
actionBar.setDisplayShowCustomEnabled(true);
- // Avoid wasting space on large left inset
+ // Avoid wasting space on large left inset
Toolbar tb = (Toolbar)customSearchView.getParent();
tb.setContentInsetsRelative(0, 0);
}
}
private static void setDictionaryPrefs(final Context context, final File dictFile,
- final String indexShortName, final String searchToken) {
+ final String indexShortName, final String searchToken) {
final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
context).edit();
prefs.putString(C.DICT_FILE, dictFile.getPath());
void updateLangButton() {
final LanguageResources languageResources =
- DictionaryApplication.isoCodeToResources.get(index.shortName);
+ DictionaryApplication.isoCodeToResources.get(index.shortName);
if (languageResources != null && languageResources.flagId != 0) {
languageButton.setImageResource(languageResources.flagId);
} else {
final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
Log.d(LOG, "Setting TTS locale to: " + locale);
try {
- final int ttsResult = textToSpeech.setLanguage(locale);
- if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
- ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
- Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
- }
+ final int ttsResult = textToSpeech.setLanguage(locale);
+ if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
+ ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
+ Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
+ }
} catch (Exception e) {
Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
}
currentSearchOperation = null;
}
setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
- searchView.getQuery().toString(), false);
+ searchView.getQuery().toString(), false);
}
void onLanguageButtonLongClick(final Context context) {
final String name = getString(R.string.dictionaryManager);
button.setText(name);
final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
- DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
+ DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
@Override
protected void onGo() {
dialog.dismiss();
for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
final View button = application.createButton(parent.getContext(),
- dictionaryInfo, indexInfo);
+ dictionaryInfo, indexInfo);
final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
getLaunchIntent(getApplicationContext(),
- application.getPath(dictionaryInfo.uncompressedFilename),
- indexInfo.shortName, searchView.getQuery().toString())) {
+ application.getPath(dictionaryInfo.uncompressedFilename),
+ indexInfo.shortName, searchView.getQuery().toString())) {
@Override
protected void onGo() {
dialog.dismiss();
};
button.setOnClickListener(intentLauncher);
if (i == indexIndex && dictFile != null &&
- dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
+ dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
button.setPressed(true);
}
result.addView(button);
final TextView nameView = new TextView(parent.getContext());
final String name = application
- .getDictionaryName(dictionaryInfo.uncompressedFilename);
+ .getDictionaryName(dictionaryInfo.uncompressedFilename);
nameView.setText(name);
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
+ ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.width = 0;
layoutParams.weight = 1.0f;
nameView.setLayoutParams(layoutParams);
.getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
// Next word.
nextWordMenuItem = menu.add(getString(R.string.nextWord))
- .setIcon(R.drawable.arrow_down_float);
+ .setIcon(R.drawable.arrow_down_float);
MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
// Previous word.
previousWordMenuItem = menu.add(getString(R.string.previousWord))
- .setIcon(R.drawable.arrow_up_float);
+ .setIcon(R.drawable.arrow_up_float);
MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
if (dictionaryInfo != null) {
builder.append(dictionaryInfo.dictInfo).append("\n\n");
builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
- .append("\n");
+ .append("\n");
builder.append(
- getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
- .append("\n");
+ getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
+ .append("\n");
builder.append(
- getString(R.string.dictionaryCreationTime,
- dictionaryInfo.creationMillis)).append("\n");
+ getString(R.string.dictionaryCreationTime,
+ dictionaryInfo.creationMillis)).append("\n");
for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
builder.append("\n");
builder.append(getString(R.string.indexName, indexInfo.shortName))
- .append("\n");
+ .append("\n");
builder.append(
- getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
- .append("\n");
+ getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
+ .append("\n");
}
builder.append("\n");
builder.append(getString(R.string.sources)).append("\n");
for (final EntrySource source : dictionary.sources) {
builder.append(
- getString(R.string.sourceInfo, source.getName(),
- source.getNumEntries())).append("\n");
+ getString(R.string.sourceInfo, source.getName(),
+ source.getNumEntries())).append("\n");
}
}
textView.setText(builder.toString());
final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
wordList.getName()));
addToWordlist
- .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
- public boolean onMenuItemClick(android.view.MenuItem item) {
- onAppendToWordList(row);
- return false;
- }
- });
+ .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
+ public boolean onMenuItemClick(android.view.MenuItem item) {
+ onAppendToWordList(row);
+ return false;
+ }
+ });
final android.view.MenuItem share = menu.add("Share");
share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
- .getToken());
+ .getToken());
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
- row.getRawText(saveOnlyFirstSubentry));
+ row.getRawText(saveOnlyFirstSubentry));
startActivity(shareIntent);
return false;
}
if (selectedSpannableText != null) {
final String selectedText = selectedSpannableText;
final android.view.MenuItem searchForSelection = menu.add(getString(
- R.string.searchForSelection,
- selectedSpannableText));
+ R.string.searchForSelection,
+ selectedSpannableText));
searchForSelection
- .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
- public boolean onMenuItemClick(android.view.MenuItem item) {
- jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
- return false;
- }
- });
+ .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
+ public boolean onMenuItemClick(android.view.MenuItem item) {
+ jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
+ return false;
+ }
+ });
// Rats, this won't be shown:
//searchForSelection.setIcon(R.drawable.abs__ic_search);
}
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
- new HashMap<String, String>());
+ new HashMap<String, String>());
return false;
}
});
}
private void jumpToTextFromHyperLink(
- final String selectedText, final int defaultIndexToUse) {
+ final String selectedText, final int defaultIndexToUse) {
int indexToUse = -1;
int numFound = 0;
for (int i = 0; i < dictionary.indices.size(); ++i) {
final IndexEntry indexEntry = index.findExact(selectedText);
if (indexEntry != null) {
final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
- .getTokenRow(false);
+ .getTokenRow(false);
if (tokenRow != null && tokenRow.hasMainEntry) {
indexToUse = i;
++numFound;
} catch (Exception e) {
Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
Toast.makeText(this,
- getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
- Toast.LENGTH_LONG).show();
+ getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
+ Toast.LENGTH_LONG).show();
}
return;
}
View focus = getCurrentFocus();
if (focus != null) {
inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
- InputMethodManager.HIDE_NOT_ALWAYS);
+ InputMethodManager.HIDE_NOT_ALWAYS);
}
return true;
}
}
private void setSearchText(final String text, final boolean triggerSearch) {
- setSearchText(text, triggerSearch, true);
+ setSearchText(text, triggerSearch, true);
}
// private long cursorDelayMillis = 100;
} else {
searchTokens = Arrays.asList(searchTokenArray);
multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
- interrupted);
+ interrupted);
}
Log.d(LOG,
- "searchText=" + searchText + ", searchDuration="
- + (System.currentTimeMillis() - searchStartMillis)
- + ", interrupted=" + interrupted.get());
+ "searchText=" + searchText + ", searchDuration="
+ + (System.currentTimeMillis() - searchStartMillis)
+ + ", interrupted=" + interrupted.get());
if (!interrupted.get()) {
uiHandler.post(new Runnable() {
@Override
// --------------------------------------------------------------------------
static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
+ ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
+ ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
final class IndexAdapter extends BaseAdapter {
}
private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
- final TableLayout result) {
+ final TableLayout result) {
final PairEntry entry = row.getEntry();
final int rowCount = entry.pairs.size();
final TextView col1 = new TextView(tableRow.getContext());
final TextView col2 = new TextView(tableRow.getContext());
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
- {
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
col1.setTextIsSelectable(true);
col2.setTextIsSelectable(true);
}
// Bold the token instances in col1.
final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections
- .singleton(row.getTokenRow(true).getToken());
+ .singleton(row.getTokenRow(true).getToken());
final Spannable col1Spannable = (Spannable) col1.getText();
for (final String token : toBold) {
int startPos = 0;
while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
- + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
+ + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
startPos += token.length();
}
}
final TableRow tableRow = new TableRow(result.getContext());
tableRow.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
- : theme.tokenRowOtherBg);
+ : theme.tokenRowOtherBg);
if (isTokenRow) {
tableRow.setPadding(mPaddingDefault, mPaddingDefault, mPaddingDefault, 0);
} else {
String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
// Log.d(LOG, "html=" + html);
startActivityForResult(
- HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
- "<html><head></head><body>%s</body></html>", html),
- htmlTextToHighlight, false),
- 0);
+ HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
+ "<html><head></head><body>%s</body></html>", html),
+ htmlTextToHighlight, false),
+ 0);
}
});
}
private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
final IndexEntry indexEntry = row.getIndexEntry();
return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
- indexEntry.htmlEntries, null, parent, result);
+ indexEntry.htmlEntries, null, parent, result);
}
private TableLayout getView(HtmlEntry.Row row, ViewGroup parent, final TableLayout result) {
final HtmlEntry htmlEntry = row.getEntry();
final TokenRow tokenRow = row.getTokenRow(true);
return getPossibleLinkToHtmlEntryView(false,
- getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
- false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
- result);
+ getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
+ false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
+ result);
}
}
static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
- final String text) {
+ final String text) {
// Saw from the source code that LinkMovementMethod sets the selection!
// http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
textView.setMovementMethod(LinkMovementMethod.getInstance());
final Matcher matcher = CHAR_DASH.matcher(text);
while (matcher.find()) {
spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(),
- matcher.end(),
- Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
+ matcher.end(),
+ Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
}
final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
- 0);
+ 0);
final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
- 1);
+ 1);
// --------------------------------------------------------------------------
// SearchText
enum Theme {
DEFAULT(R.style.Theme_Default,
- R.style.Theme_Default_TokenRow_Fg,
- R.color.theme_default_token_row_fg,
- R.drawable.theme_default_token_row_main_bg,
- R.drawable.theme_default_token_row_other_bg,
- R.drawable.theme_default_normal_row_bg),
+ R.style.Theme_Default_TokenRow_Fg,
+ R.color.theme_default_token_row_fg,
+ R.drawable.theme_default_token_row_main_bg,
+ R.drawable.theme_default_token_row_other_bg,
+ R.drawable.theme_default_normal_row_bg),
LIGHT(R.style.Theme_Light,
- R.style.Theme_Light_TokenRow_Fg,
- R.color.theme_light_token_row_fg,
- R.drawable.theme_light_token_row_main_bg,
- R.drawable.theme_light_token_row_other_bg,
- R.drawable.theme_light_normal_row_bg);
+ R.style.Theme_Light_TokenRow_Fg,
+ R.color.theme_light_token_row_fg,
+ R.drawable.theme_light_token_row_main_bg,
+ R.drawable.theme_light_token_row_other_bg,
+ R.drawable.theme_light_normal_row_bg);
Theme(final int themeId, final int tokenRowFg,
- final int tokenRowFgColor,
- final int tokenRowMainBg, final int tokenRowOtherBg,
- final int normalRowBg) {
+ final int tokenRowFgColor,
+ final int tokenRowMainBg, final int tokenRowOtherBg,
+ final int normalRowBg) {
this.themeId = themeId;
this.tokenRowFg = tokenRowFg;
this.tokenRowFgColor = tokenRowFgColor;
public static final Map<String, LanguageResources> isoCodeToResources = new HashMap<String, LanguageResources>();
static {
isoCodeToResources.put("AF", new LanguageResources("Afrikaans", R.string.AF,
- R.drawable.flag_of_south_africa));
+ R.drawable.flag_of_south_africa));
isoCodeToResources.put("SQ", new LanguageResources("Albanian", R.string.SQ,
- R.drawable.flag_of_albania));
+ R.drawable.flag_of_albania));
isoCodeToResources.put("AR",
- new LanguageResources("Arabic", R.string.AR, R.drawable.arabic));
+ new LanguageResources("Arabic", R.string.AR, R.drawable.arabic));
isoCodeToResources.put("HY", new LanguageResources("Armenian", R.string.HY,
- R.drawable.flag_of_armenia));
+ R.drawable.flag_of_armenia));
isoCodeToResources.put("BE", new LanguageResources("Belarusian", R.string.BE,
- R.drawable.flag_of_belarus));
+ R.drawable.flag_of_belarus));
isoCodeToResources.put("BN", new LanguageResources("Bengali", R.string.BN));
isoCodeToResources.put("BS", new LanguageResources("Bosnian", R.string.BS,
- R.drawable.flag_of_bosnia_and_herzegovina));
+ R.drawable.flag_of_bosnia_and_herzegovina));
isoCodeToResources.put("BG", new LanguageResources("Bulgarian", R.string.BG,
- R.drawable.flag_of_bulgaria));
+ R.drawable.flag_of_bulgaria));
isoCodeToResources.put("MY", new LanguageResources("Burmese", R.string.MY,
- R.drawable.flag_of_myanmar));
+ R.drawable.flag_of_myanmar));
isoCodeToResources.put("ZH", new LanguageResources("Chinese", R.string.ZH,
- R.drawable.flag_of_the_peoples_republic_of_china));
+ R.drawable.flag_of_the_peoples_republic_of_china));
isoCodeToResources.put("cmn", new LanguageResources("Mandarin", R.string.cmn,
- R.drawable.flag_of_the_peoples_republic_of_china));
+ R.drawable.flag_of_the_peoples_republic_of_china));
isoCodeToResources.put("yue", new LanguageResources("Cantonese", R.string.yue,
- R.drawable.flag_of_hong_kong));
+ R.drawable.flag_of_hong_kong));
isoCodeToResources.put("CA", new LanguageResources("Catalan", R.string.CA));
isoCodeToResources.put("HR", new LanguageResources("Croatian", R.string.HR,
- R.drawable.flag_of_croatia));
+ R.drawable.flag_of_croatia));
isoCodeToResources.put("CS", new LanguageResources("Czech", R.string.CS,
- R.drawable.flag_of_the_czech_republic));
+ R.drawable.flag_of_the_czech_republic));
isoCodeToResources.put("DA", new LanguageResources("Danish", R.string.DA,
- R.drawable.flag_of_denmark));
+ R.drawable.flag_of_denmark));
isoCodeToResources.put("NL", new LanguageResources("Dutch", R.string.NL,
- R.drawable.flag_of_the_netherlands));
+ R.drawable.flag_of_the_netherlands));
isoCodeToResources.put("EN", new LanguageResources("English", R.string.EN,
- R.drawable.flag_of_the_united_kingdom));
+ R.drawable.flag_of_the_united_kingdom));
isoCodeToResources.put("EO", new LanguageResources("Esperanto", R.string.EO,
- R.drawable.flag_of_esperanto));
+ R.drawable.flag_of_esperanto));
isoCodeToResources.put("ET", new LanguageResources("Estonian", R.string.ET,
- R.drawable.flag_of_estonia));
+ R.drawable.flag_of_estonia));
isoCodeToResources.put("FI", new LanguageResources("Finnish", R.string.FI,
- R.drawable.flag_of_finland));
+ R.drawable.flag_of_finland));
isoCodeToResources.put("FR", new LanguageResources("French", R.string.FR,
- R.drawable.flag_of_france));
+ R.drawable.flag_of_france));
isoCodeToResources.put("DE", new LanguageResources("German", R.string.DE,
- R.drawable.flag_of_germany));
+ R.drawable.flag_of_germany));
isoCodeToResources.put("EL", new LanguageResources("Greek", R.string.EL,
- R.drawable.flag_of_greece));
+ R.drawable.flag_of_greece));
isoCodeToResources.put("grc", new LanguageResources("Ancient Greek", R.string.grc));
isoCodeToResources.put("haw", new LanguageResources("Hawaiian", R.string.haw,
- R.drawable.flag_of_hawaii));
+ R.drawable.flag_of_hawaii));
isoCodeToResources.put("HE", new LanguageResources("Hebrew", R.string.HE,
- R.drawable.flag_of_israel));
+ R.drawable.flag_of_israel));
isoCodeToResources.put("HI", new LanguageResources("Hindi", R.string.HI, R.drawable.hindi));
isoCodeToResources.put("HU", new LanguageResources("Hungarian", R.string.HU,
- R.drawable.flag_of_hungary));
+ R.drawable.flag_of_hungary));
isoCodeToResources.put("IS", new LanguageResources("Icelandic", R.string.IS,
- R.drawable.flag_of_iceland));
+ R.drawable.flag_of_iceland));
isoCodeToResources.put("ID", new LanguageResources("Indonesian", R.string.ID,
- R.drawable.flag_of_indonesia));
+ R.drawable.flag_of_indonesia));
isoCodeToResources.put("GA", new LanguageResources("Irish", R.string.GA,
- R.drawable.flag_of_ireland));
+ R.drawable.flag_of_ireland));
isoCodeToResources.put("GD", new LanguageResources("Scottish Gaelic", R.string.GD,
- R.drawable.flag_of_scotland));
+ R.drawable.flag_of_scotland));
isoCodeToResources.put("GV", new LanguageResources("Manx", R.string.GV,
- R.drawable.flag_of_the_isle_of_man));
+ R.drawable.flag_of_the_isle_of_man));
isoCodeToResources.put("IT", new LanguageResources("Italian", R.string.IT,
- R.drawable.flag_of_italy));
+ R.drawable.flag_of_italy));
isoCodeToResources.put("LA", new LanguageResources("Latin", R.string.LA));
isoCodeToResources.put("LV", new LanguageResources("Latvian", R.string.LV,
- R.drawable.flag_of_latvia));
+ R.drawable.flag_of_latvia));
isoCodeToResources.put("LT", new LanguageResources("Lithuanian", R.string.LT,
- R.drawable.flag_of_lithuania));
+ R.drawable.flag_of_lithuania));
isoCodeToResources.put("JA", new LanguageResources("Japanese", R.string.JA,
- R.drawable.flag_of_japan));
+ R.drawable.flag_of_japan));
isoCodeToResources.put("KO", new LanguageResources("Korean", R.string.KO,
- R.drawable.flag_of_south_korea));
+ R.drawable.flag_of_south_korea));
isoCodeToResources.put("KU", new LanguageResources("Kurdish", R.string.KU));
isoCodeToResources.put("MS", new LanguageResources("Malay", R.string.MS,
- R.drawable.flag_of_malaysia));
+ R.drawable.flag_of_malaysia));
isoCodeToResources.put("MI", new LanguageResources("Maori", R.string.MI,
- R.drawable.flag_of_new_zealand));
+ R.drawable.flag_of_new_zealand));
isoCodeToResources.put("MN", new LanguageResources("Mongolian", R.string.MN,
- R.drawable.flag_of_mongolia));
+ R.drawable.flag_of_mongolia));
isoCodeToResources.put("NE", new LanguageResources("Nepali", R.string.NE,
- R.drawable.flag_of_nepal));
+ R.drawable.flag_of_nepal));
isoCodeToResources.put("NO", new LanguageResources("Norwegian", R.string.NO,
- R.drawable.flag_of_norway));
+ R.drawable.flag_of_norway));
isoCodeToResources.put("FA", new LanguageResources("Persian", R.string.FA,
- R.drawable.flag_of_iran));
+ R.drawable.flag_of_iran));
isoCodeToResources.put("PL", new LanguageResources("Polish", R.string.PL,
- R.drawable.flag_of_poland));
+ R.drawable.flag_of_poland));
isoCodeToResources.put("PT", new LanguageResources("Portuguese", R.string.PT,
- R.drawable.flag_of_portugal));
+ R.drawable.flag_of_portugal));
isoCodeToResources.put("PA", new LanguageResources("Punjabi", R.string.PA));
isoCodeToResources.put("RO", new LanguageResources("Romanian", R.string.RO,
- R.drawable.flag_of_romania));
+ R.drawable.flag_of_romania));
isoCodeToResources.put("RU", new LanguageResources("Russian", R.string.RU,
- R.drawable.flag_of_russia));
+ R.drawable.flag_of_russia));
isoCodeToResources.put("SA", new LanguageResources("Sanskrit", R.string.SA));
isoCodeToResources.put("SR", new LanguageResources("Serbian", R.string.SR,
- R.drawable.flag_of_serbia));
+ R.drawable.flag_of_serbia));
isoCodeToResources.put("SK", new LanguageResources("Slovak", R.string.SK,
- R.drawable.flag_of_slovakia));
+ R.drawable.flag_of_slovakia));
isoCodeToResources.put("SL", new LanguageResources("Slovenian", R.string.SL,
- R.drawable.flag_of_slovenia));
+ R.drawable.flag_of_slovenia));
isoCodeToResources.put("SO", new LanguageResources("Somali", R.string.SO,
- R.drawable.flag_of_somalia));
+ R.drawable.flag_of_somalia));
isoCodeToResources.put("ES", new LanguageResources("Spanish", R.string.ES,
- R.drawable.flag_of_spain));
+ R.drawable.flag_of_spain));
isoCodeToResources.put("SW", new LanguageResources("Swahili", R.string.SW));
isoCodeToResources.put("SV", new LanguageResources("Swedish", R.string.SV,
- R.drawable.flag_of_sweden));
+ R.drawable.flag_of_sweden));
isoCodeToResources.put("TL", new LanguageResources("Tagalog", R.string.TL));
isoCodeToResources.put("TG", new LanguageResources("Tajik", R.string.TG,
- R.drawable.flag_of_tajikistan));
+ R.drawable.flag_of_tajikistan));
isoCodeToResources.put("TH", new LanguageResources("Thai", R.string.TH,
- R.drawable.flag_of_thailand));
+ R.drawable.flag_of_thailand));
isoCodeToResources.put("BO", new LanguageResources("Tibetan", R.string.BO));
isoCodeToResources.put("TR", new LanguageResources("Turkish", R.string.TR,
- R.drawable.flag_of_turkey));
+ R.drawable.flag_of_turkey));
isoCodeToResources.put("UK", new LanguageResources("Ukrainian", R.string.UK,
- R.drawable.flag_of_ukraine));
+ R.drawable.flag_of_ukraine));
isoCodeToResources.put("UR", new LanguageResources("Urdu", R.string.UR));
isoCodeToResources.put("VI", new LanguageResources("Vietnamese", R.string.VI,
- R.drawable.flag_of_vietnam));
+ R.drawable.flag_of_vietnam));
isoCodeToResources.put("CI", new LanguageResources("Welsh", R.string.CI,
- R.drawable.flag_of_wales_2));
+ R.drawable.flag_of_wales_2));
isoCodeToResources.put("YI", new LanguageResources("Yiddish", R.string.YI));
isoCodeToResources.put("ZU", new LanguageResources("Zulu", R.string.ZU));
isoCodeToResources.put("AZ", new LanguageResources("Azeri", R.string.AZ,
- R.drawable.flag_of_azerbaijan));
+ R.drawable.flag_of_azerbaijan));
isoCodeToResources.put("EU", new LanguageResources("Basque", R.string.EU,
- R.drawable.flag_of_the_basque_country));
+ R.drawable.flag_of_the_basque_country));
isoCodeToResources.put("BR", new LanguageResources("Breton", R.string.BR));
isoCodeToResources.put("MR", new LanguageResources("Marathi", R.string.MR));
isoCodeToResources.put("FO", new LanguageResources("Faroese", R.string.FO));
isoCodeToResources.put("GL", new LanguageResources("Galician", R.string.GL,
- R.drawable.flag_of_galicia));
+ R.drawable.flag_of_galicia));
isoCodeToResources.put("KA", new LanguageResources("Georgian", R.string.KA,
- R.drawable.flag_of_georgia));
+ R.drawable.flag_of_georgia));
isoCodeToResources.put("HT", new LanguageResources("Haitian Creole", R.string.HT,
- R.drawable.flag_of_haiti));
+ R.drawable.flag_of_haiti));
isoCodeToResources.put("LB", new LanguageResources("Luxembourgish", R.string.LB,
- R.drawable.flag_of_luxembourg));
+ R.drawable.flag_of_luxembourg));
isoCodeToResources.put("MK", new LanguageResources("Macedonian", R.string.MK,
- R.drawable.flag_of_macedonia));
+ R.drawable.flag_of_macedonia));
isoCodeToResources.put("LO", new LanguageResources("Lao", R.string.LO,
- R.drawable.flag_of_laos));
+ R.drawable.flag_of_laos));
isoCodeToResources.put("ML", new LanguageResources("Malayalam", R.string.ML));
isoCodeToResources.put("SL", new LanguageResources("Slovenian", R.string.SL,
- R.drawable.flag_of_slovenia));
+ R.drawable.flag_of_slovenia));
isoCodeToResources.put("TA", new LanguageResources("Tamil", R.string.TA));
isoCodeToResources.put("SH", new LanguageResources("Serbo-Croatian", R.string.SH));
isoCodeToResources.put("SD", new LanguageResources("Sindhi", R.string.SD));
}
DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new HashMap<String, DictionaryInfo>();
final BufferedReader reader = new BufferedReader(
- new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
+ new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
try {
String line;
while ((line = reader.readLine()) != null) {
}
final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
- dictionaryInfo.uncompressedFilename, dictionaryInfo);
+ dictionaryInfo.uncompressedFilename, dictionaryInfo);
}
} catch (IOException e) {
Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
}
- try { reader.close(); } catch (IOException e) {}
+ try {
+ reader.close();
+ } catch (IOException e) {}
}
private File dictDir;
staticInit(getApplicationContext());
languageButtonPixels = (int) TypedValue.applyDimension(
- TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics());
+ TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics());
// Load the dictionaries we know about.
dictionaryConfig = PersistentObjectCache.init(getApplicationContext()).read(
- C.DICTIONARY_CONFIGS, DictionaryConfig.class);
+ C.DICTIONARY_CONFIGS, DictionaryConfig.class);
if (dictionaryConfig == null) {
dictionaryConfig = new DictionaryConfig();
}
prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
- String key) {
+ String key) {
Log.d("QuickDic", "prefs changed: " + key);
if (key.equals(getString(R.string.themeKey))) {
setTheme(getSelectedTheme().themeId);
}
public void onCreateGlobalOptionsMenu(
- final Context context, final Menu menu) {
+ final Context context, final Menu menu) {
final MenuItem about = menu.add(getString(R.string.about));
MenuItemCompat.setShowAsAction(about, MenuItem.SHOW_AS_ACTION_NEVER);
about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem menuItem) {
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri
- .parse("http://github.com/rdoeffinger/Dictionary/issues"));
+ .parse("http://github.com/rdoeffinger/Dictionary/issues"));
context.startActivity(intent);
return false;
}
dictDir = new File(dir);
dictDir.mkdirs();
if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
- getApplicationContext().getExternalFilesDirs(null);
+ getApplicationContext().getExternalFilesDirs(null);
}
return dictDir;
}
final Language.LanguageResources languageResources = isoCodeToResources
.get(isoCode);
final String lang = languageResources != null ? getApplicationContext().getString(
- languageResources.nameId) : isoCode;
+ languageResources.nameId) : isoCode;
return lang;
}
}
final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
- .get(uncompressedFilename);
+ .get(uncompressedFilename);
if (dictionaryInfo != null) {
final StringBuilder nameBuilder = new StringBuilder();
nameBuilder.append("-");
}
nameBuilder
- .append(isoCodeToLocalizedLanguageName(sortedIndexInfos.get(i).shortName));
+ .append(isoCodeToLocalizedLanguageName(sortedIndexInfos.get(i).shortName));
}
name = nameBuilder.toString();
} else {
}
public View createButton(final Context context, final DictionaryInfo dictionaryInfo,
- final IndexInfo indexInfo) {
+ final IndexInfo indexInfo) {
LanguageResources languageResources = isoCodeToResources.get(indexInfo.shortName);
View result;
while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
}
dictionaryConfig.uncompressedFilenameToDictionaryInfo
- .remove(dictionaryInfo.uncompressedFilename);
+ .remove(dictionaryInfo.uncompressedFilename);
getPath(dictionaryInfo.uncompressedFilename).delete();
PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
}
&& !name2.startsWith(defaultLangName + "-")) {
return -1;
} else if (name2.startsWith(defaultLangName + "-")
- && !name1.startsWith(defaultLangName + "-")) {
+ && !name1.startsWith(defaultLangName + "-")) {
return 1;
}
}
final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
synchronized (DictionaryApplication.this) {
oldDictionaryConfig.dictionaryFilesOrdered
- .addAll(dictionaryConfig.dictionaryFilesOrdered);
+ .addAll(dictionaryConfig.dictionaryFilesOrdered);
}
final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
if (dictionaryInfo.isValid() || dictFile.exists()) {
newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
- uncompressedFilename, dictionaryInfo);
+ uncompressedFilename, dictionaryInfo);
}
}
toAddSorted.add(file.getName());
newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
- file.getName(), dictionaryInfo);
+ file.getName(), dictionaryInfo);
}
} else {
Log.w(LOG, "dictDir is not a directory: " + getDictDir().getPath());
try {
PersistentObjectCache.getInstance()
- .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
+ .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
} catch (Exception e) {
Log.e(LOG, "Failed persisting dictionary configs", e);
}
}
for (final String filter : filters) {
if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
- filter)) {
+ filter)) {
return false;
}
}
public synchronized List<DictionaryInfo> getDictionariesOnDevice(String[] filters) {
final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
- dictionaryConfig.dictionaryFilesOrdered.size());
+ dictionaryConfig.dictionaryFilesOrdered.size());
for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo
- .get(uncompressedFilename);
+ .get(uncompressedFilename);
if (dictionaryInfo != null && matchesFilters(dictionaryInfo, filters)) {
result.add(dictionaryInfo);
}
public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
- dictionaryConfig.dictionaryFilesOrdered.size());
+ dictionaryConfig.dictionaryFilesOrdered.size());
final Map<String, DictionaryInfo> remaining = new HashMap<String, DictionaryInfo>(
- DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
+ DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
for (final DictionaryInfo dictionaryInfo : remaining.values()) {
if (matchesFilters(dictionaryInfo, filters)) {
public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
final DictionaryInfo downloadable =
- DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
- dictionaryInfo.uncompressedFilename);
+ DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
+ dictionaryInfo.uncompressedFilename);
return downloadable != null &&
- downloadable.creationMillis > dictionaryInfo.creationMillis;
+ downloadable.creationMillis > dictionaryInfo.creationMillis;
}
public DictionaryInfo getDownloadable(final String uncompressedFilename) {
final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
- .get(uncompressedFilename);
+ .get(uncompressedFilename);
return downloadable;
}
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
final long downloadId = intent.getLongExtra(
- DownloadManager.EXTRA_DOWNLOAD_ID, 0);
+ DownloadManager.EXTRA_DOWNLOAD_ID, 0);
if (finishedDownloadIds.contains(downloadId)) return; // ignore double notifications
final DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
}
final String dest = cursor
- .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
+ .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
final int status = cursor
- .getInt(cursor
- .getColumnIndex(DownloadManager.COLUMN_STATUS));
+ .getInt(cursor
+ .getColumnIndex(DownloadManager.COLUMN_STATUS));
if (DownloadManager.STATUS_SUCCESSFUL != status) {
final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
Log.w(LOG,
- "Download failed: status=" + status +
- ", reason=" + reason);
+ "Download failed: status=" + status +
+ ", reason=" + reason);
String msg = Integer.toString(reason);
switch (reason) {
- case DownloadManager.ERROR_FILE_ALREADY_EXISTS: msg = "File exists"; break;
- case DownloadManager.ERROR_FILE_ERROR: msg = "File error"; break;
- case DownloadManager.ERROR_INSUFFICIENT_SPACE: msg = "Not enough space"; break;
+ case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
+ msg = "File exists";
+ break;
+ case DownloadManager.ERROR_FILE_ERROR:
+ msg = "File error";
+ break;
+ case DownloadManager.ERROR_INSUFFICIENT_SPACE:
+ msg = "Not enough space";
+ break;
}
new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, msg)).setNeutralButton("Close", null).show();
return;
Log.w(LOG, "Download finished: " + dest + " Id: " + downloadId);
Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
- Toast.LENGTH_LONG).show();
+ Toast.LENGTH_LONG).show();
final Uri zipUri = Uri.parse(dest);
copyStream(zipFile, zipOut);
application.backgroundUpdateDictionaries(dictionaryUpdater);
Toast.makeText(context, getString(R.string.installationFinished, dest),
- Toast.LENGTH_LONG).show();
+ Toast.LENGTH_LONG).show();
finishedDownloadIds.add(downloadId);
Log.w(LOG, "Unzipping finished: " + dest + " Id: " + downloadId);
} catch (Exception e) {
new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
Log.e(LOG, "Failed to unzip.", e);
} finally {
- try { if (zipOut != null) zipOut.close(); } catch (IOException e) {}
- try { if (zipFile != null) zipFile.close(); } catch (IOException e) {}
- try { if (zipFileStream != null) zipFileStream.close(); } catch (IOException e) {}
+ try {
+ if (zipOut != null) zipOut.close();
+ } catch (IOException e) {}
+ try {
+ if (zipFile != null) zipFile.close();
+ } catch (IOException e) {}
+ try {
+ if (zipFileStream != null) zipFileStream.close();
+ } catch (IOException e) {}
if (localZipFile != null) localZipFile.delete();
}
}
if (dictDir.canRead() && dictDir.canExecute()) return;
blockAutoLaunch = true;
if (requestPermission &&
- ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
+ ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
- new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
- Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
+ new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
+ Manifest.permission.WRITE_EXTERNAL_STORAGE
+ }, 0);
return;
}
blockAutoLaunch = true;
AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
builder.setTitle(getString(R.string.error));
builder.setMessage(getString(
- R.string.unableToReadDictionaryDir,
- dictDir.getAbsolutePath(),
- Environment.getExternalStorageDirectory()));
+ R.string.unableToReadDictionaryDir,
+ dictDir.getAbsolutePath(),
+ Environment.getExternalStorageDirectory()));
builder.setNeutralButton("Close", null);
builder.create().show();
}
setContentView(R.layout.dictionary_manager_activity);
dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
- getListView().getContext()).inflate(
- R.layout.dictionary_manager_header_row_on_device, getListView(), false);
+ getListView().getContext()).inflate(
+ R.layout.dictionary_manager_header_row_on_device, getListView(), false);
downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
- getListView().getContext()).inflate(
- R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
+ getListView().getContext()).inflate(
+ R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
- .findViewById(R.id.hideDownloadable);
+ .findViewById(R.id.hideDownloadable);
showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
- thanksForUpdatingLatestVersion)) {
+ thanksForUpdatingLatestVersion)) {
blockAutoLaunch = true;
startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
- .commit();
+ .commit();
}
registerReceiver(broadcastReceiver, new IntentFilter(
- DownloadManager.ACTION_DOWNLOAD_COMPLETE));
+ DownloadManager.ACTION_DOWNLOAD_COMPLETE));
setMyListAdapater();
registerForContextMenu(getListView());
filterSearchView.setLayoutParams(lp);
filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
filterSearchView.setImeOptions(
- EditorInfo.IME_ACTION_DONE |
- EditorInfo.IME_FLAG_NO_EXTRACT_UI |
- // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
- // 11
- EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
+ EditorInfo.IME_ACTION_DONE |
+ EditorInfo.IME_FLAG_NO_EXTRACT_UI |
+ // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
+ // 11
+ EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
}
private static int copyStream(final InputStream in, final OutputStream out)
- throws IOException {
+ throws IOException {
int bytesRead;
final byte[] bytes = new byte[1024 * 16];
while ((bytesRead = in.read(bytes)) != -1) {
prefs.contains(C.INDEX_SHORT_NAME)) {
Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
- new File(prefs.getString(C.DICT_FILE, "")),
- prefs.getString(C.INDEX_SHORT_NAME, ""),
- prefs.getString(C.SEARCH_TOKEN, "")));
+ new File(prefs.getString(C.DICT_FILE, "")),
+ prefs.getString(C.INDEX_SHORT_NAME, ""),
+ prefs.getString(C.SEARCH_TOKEN, "")));
finish();
return;
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View view,
- final ContextMenuInfo menuInfo) {
+ final ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
Log.d(LOG, "onCreateContextMenu, " + menuInfo);
final AdapterContextMenuInfo adapterContextMenuInfo =
- (AdapterContextMenuInfo) menuInfo;
+ (AdapterContextMenuInfo) menuInfo;
final int position = adapterContextMenuInfo.position;
final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
if (position > 0 && row.onDevice) {
final android.view.MenuItem moveToTopMenuItem =
- menu.add(R.string.moveToTop);
+ menu.add(R.string.moveToTop);
moveToTopMenuItem.setOnMenuItemClickListener(new
- android.view.MenuItem.OnMenuItemClickListener() {
- @Override
- public boolean onMenuItemClick(android.view.MenuItem item) {
- application.moveDictionaryToTop(row.dictionaryInfo);
- setMyListAdapater();
- return true;
- }
- });
+ android.view.MenuItem.OnMenuItemClickListener() {
+ @Override
+ public boolean onMenuItemClick(android.view.MenuItem item) {
+ application.moveDictionaryToTop(row.dictionaryInfo);
+ setMyListAdapater();
+ return true;
+ }
+ });
}
if (row.onDevice) {
final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
deleteMenuItem
- .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
- @Override
- public boolean onMenuItemClick(android.view.MenuItem item) {
- application.deleteDictionary(row.dictionaryInfo);
- setMyListAdapater();
- return true;
- }
- });
+ .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
+ @Override
+ public boolean onMenuItemClick(android.view.MenuItem item) {
+ application.deleteDictionary(row.dictionaryInfo);
+ setMyListAdapater();
+ return true;
+ }
+ });
}
}
private void setMyListAdapater() {
final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
- .toString();
+ .toString();
final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
setListAdapter(new MyListAdapter(filters));
}
private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
- final ViewGroup parent, boolean canLaunch) {
+ final ViewGroup parent, boolean canLaunch) {
View row = LayoutInflater.from(parent.getContext()).inflate(
- R.layout.dictionary_manager_row, parent, false);
+ R.layout.dictionary_manager_row, parent, false);
final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
}
if (downloadable != null && (!canLaunch || updateAvailable)) {
downloadButton
- .setText(getString(
- R.string.downloadButton,
- downloadable.zipBytes / 1024.0 / 1024.0));
+ .setText(getString(
+ R.string.downloadButton,
+ downloadable.zipBytes / 1024.0 / 1024.0));
downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
downloadButton.setOnClickListener(new OnClickListener() {
@Override
}
for (IndexInfo indexInfo : sortedIndexInfos) {
final View button = application.createButton(buttons.getContext(), dictionaryInfo,
- indexInfo);
+ indexInfo);
buttons.addView(button);
if (canLaunch) {
button.setOnClickListener(
- new IntentLauncher(buttons.getContext(),
- DictionaryActivity.getLaunchIntent(getApplicationContext(),
- application.getPath(dictionaryInfo.uncompressedFilename),
- indexInfo.shortName, "")));
+ new IntentLauncher(buttons.getContext(),
+ DictionaryActivity.getLaunchIntent(getApplicationContext(),
+ application.getPath(dictionaryInfo.uncompressedFilename),
+ indexInfo.shortName, "")));
} else {
button.setEnabled(false);
builder.append("; ");
}
builder.append(getString(R.string.indexInfo, indexInfo.shortName,
- indexInfo.mainTokenCount));
+ indexInfo.mainTokenCount));
}
builder.append("; ");
builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
if (canLaunch) {
row.setClickable(true);
row.setOnClickListener(new IntentLauncher(parent.getContext(),
- DictionaryActivity.getLaunchIntent(getApplicationContext(),
- application.getPath(dictionaryInfo.uncompressedFilename),
- dictionaryInfo.indexInfos.get(0).shortName, "")));
+ DictionaryActivity.getLaunchIntent(getApplicationContext(),
+ application.getPath(dictionaryInfo.uncompressedFilename),
+ dictionaryInfo.indexInfos.get(0).shortName, "")));
row.setFocusable(true);
row.setLongClickable(true);
}
// the download manager is disabled.
if (cursor == null) {
new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
- .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
- .setNeutralButton("Close", null).show();
+ .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
+ .setNeutralButton("Close", null).show();
return;
}
if (!cursor.isAfterLast()) {
downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
downloadButton
- .setText(getString(
- R.string.downloadButton,
- bytes / 1024.0 / 1024.0));
+ .setText(getString(
+ R.string.downloadButton,
+ bytes / 1024.0 / 1024.0));
cursor.close();
return;
}
cursor.close();
Request request = new Request(
- Uri.parse(downloadUrl));
+ Uri.parse(downloadUrl));
Log.d(LOG, "Downloading to: " + destFile);
request.setTitle(destFile);
}
public static Intent getHtmlIntent(Context c, final String html, final String textToHighlight,
- final boolean showOkButton) {
+ final boolean showOkButton) {
final Intent intent = new Intent(c, HtmlDisplayActivity.class);
intent.putExtra(HTML, html);
intent.putExtra(TEXT_TO_HIGHLIGHT, textToHighlight);
public boolean onOptionsItemSelected(MenuItem item) {
// Explicitly handle the up button press so
// we return to the dictionary.
- if (item.getItemId() == android.R.id.home)
- {
+ if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
ListPreference defaultDic = (ListPreference) findPreference(getResources().getString(
- R.string.defaultDicKey));
+ R.string.defaultDicKey));
List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
final CharSequence[] entries = new CharSequence[dicts.size()];
final CharSequence[] entryvalues = new CharSequence[dicts.size()];
- for (int i = 0; i < entries.length; ++i)
- {
+ for (int i = 0; i < entries.length; ++i) {
entries[i] = dicts.get(i).dictInfo;
entryvalues[i] = dicts.get(i).uncompressedFilename;
}
final DictionaryApplication application = (DictionaryApplication)getApplication();
File dictDir = application.getDictDir();
if (!dictDir.isDirectory() || !dictDir.canWrite() ||
- !application.checkFileCreate(dictDir)) {
+ !application.checkFileCreate(dictDir)) {
String dirs = "";
String externalDir = Environment.getExternalStorageDirectory().getAbsolutePath();
if (new File(externalDir).canWrite())
if (fd.canWrite())
dirs += "\n" + fd.getAbsolutePath();
new AlertDialog.Builder(this).setTitle(getString(R.string.error))
- .setMessage(getString(R.string.chosenNotWritable) + dirs)
- .setNeutralButton("Close", null).show();
+ .setMessage(getString(R.string.chosenNotWritable) + dirs)
+ .setNeutralButton("Close", null).show();
}
}
}
}
public AbstractEntry(Dictionary dictionary, DataInput raf, final int index)
- throws IOException {
+ throws IOException {
super(index);
if (dictionary.dictFileVersion >= 1) {
final int entrySouceIdx = dictionary.dictFileVersion >= 7 ? StringUtil.readVarInt(raf) : raf.readShort();
raf.seek(rafSources.getEndOffset());
pairEntries = CachingList.create(
- RAFList.create(raf, new PairEntry.Serializer(this), raf.getFilePointer(), dictFileVersion, dictInfo + " pairs: "),
- CACHE_SIZE);
+ RAFList.create(raf, new PairEntry.Serializer(this), raf.getFilePointer(), dictFileVersion, dictInfo + " pairs: "),
+ CACHE_SIZE);
textEntries = CachingList.create(
- RAFList.create(raf, new TextEntry.Serializer(this), raf.getFilePointer(), dictFileVersion, dictInfo + " text: "),
- CACHE_SIZE);
+ RAFList.create(raf, new TextEntry.Serializer(this), raf.getFilePointer(), dictFileVersion, dictInfo + " text: "),
+ CACHE_SIZE);
if (dictFileVersion >= 5) {
htmlEntries = CachingList.create(
- RAFList.create(raf, new HtmlEntry.Serializer(this), raf.getFilePointer(), dictFileVersion, dictInfo + " html: "),
- CACHE_SIZE);
+ RAFList.create(raf, new HtmlEntry.Serializer(this), raf.getFilePointer(), dictFileVersion, dictInfo + " html: "),
+ CACHE_SIZE);
} else {
htmlEntries = Collections.emptyList();
}
htmlData = null;
}
indices = CachingList.createFullyCached(RAFList.create(raf, indexSerializer,
- raf.getFilePointer(), dictFileVersion, dictInfo + " index: "));
+ raf.getFilePointer(), dictFileVersion, dictInfo + " index: "));
} catch (RuntimeException e) {
final IOException ioe = new IOException("RuntimeException loading dictionary");
ioe.initCause(e);
@Override
public EntrySource read(DataInput raf, int readIndex)
- throws IOException {
+ throws IOException {
final String name = raf.readUTF();
final int numEntries = dictionary.dictFileVersion >= 3 ? raf.readInt() : 0;
return new EntrySource(readIndex, name, numEntries);
// The next two are how we file entries like: "sono: {form of|essere}" under
// "essere".
WIKTIONARY_BASE_FORM_SINGLE(), // These two should be eligible for removal
- // if the links are otherwise present.
+ // if the links are otherwise present.
WIKTIONARY_BASE_FORM_MULTI(false, false, WIKTIONARY_BASE_FORM_SINGLE),
PART_OF_HYPHENATED(),
BRACKETED(),
}
EntryTypeName(final boolean mainWord, final boolean overridesStopList,
- final EntryTypeName singleWordInstance) {
+ final EntryTypeName singleWordInstance) {
this.mainWord = mainWord;
this.overridesStopList = overridesStopList;
this.singleWordInstance = singleWordInstance == null ? this : singleWordInstance;
}
public HtmlEntry(Dictionary dictionary, DataInput raf, final int index)
- throws IOException {
+ throws IOException {
super(dictionary, raf, index);
title = raf.readUTF();
lazyHtmlLoader = new LazyHtmlLoader(raf, dictionary.htmlData, index);
boolean isExpanded = false;
Row(final DataInput raf, final int thisRowIndex,
- final Index index, int extra) throws IOException {
+ final Index index, int extra) throws IOException {
super(raf, thisRowIndex, index, extra);
}
Row(final int referenceIndex, final int thisRowIndex,
- final Index index) {
+ final Index index) {
super(referenceIndex, thisRowIndex, index);
}
@Override
public RowMatchType matches(final List<String> searchTokens,
- final Pattern orderedMatchPattern, final Transliterator normalizer,
- final boolean swapPairEntries) {
+ final Pattern orderedMatchPattern, final Transliterator normalizer,
+ final boolean swapPairEntries) {
final String text = normalizer.transform(getRawText(false));
if (orderedMatchPattern.matcher(text).find()) {
return RowMatchType.ORDERED_MATCH;
for (final HtmlEntry htmlEntry : htmlEntries) {
final String titleEscaped = StringUtil.escapeUnicodeToPureHtml(htmlEntry.title);
result.append(String.format("<h1><a href=\"%s\">%s</a></h1>\n<p>%s\n",
- formatQuickdicUrl(indexShortName, htmlEntry.title), titleEscaped,
- htmlEntry.getHtml()));
+ formatQuickdicUrl(indexShortName, htmlEntry.title), titleEscaped,
+ htmlEntry.getHtml()));
}
return result.toString();
}
return html;
}
System.out.println("Loading Html: numBytes=" + numBytes + ", numZipBytes="
- + numZipBytes);
+ + numZipBytes);
final byte[] zipBytes = new byte[numZipBytes];
synchronized (raf) {
try {
// --------------------------------------------------------------------------
public Index(final Dictionary dict, final String shortName, final String longName,
- final Language sortLanguage, final String normalizerRules,
- final boolean swapPairEntries, final Set<String> stoplist) {
+ final Language sortLanguage, final String normalizerRules,
+ final boolean swapPairEntries, final Set<String> stoplist) {
this.dict = dict;
this.shortName = shortName;
this.longName = longName;
mainTokenCount = raf.readInt();
}
sortedIndexEntries = CachingList.create(
- RAFList.create(raf, indexEntrySerializer, raf.getFilePointer(),
- dict.dictFileVersion, dict.dictInfo + " idx " + languageCode + ": "), CACHE_SIZE);
+ RAFList.create(raf, indexEntrySerializer, raf.getFilePointer(),
+ dict.dictFileVersion, dict.dictInfo + " idx " + languageCode + ": "), CACHE_SIZE);
if (dict.dictFileVersion >= 7) {
int count = StringUtil.readVarInt(raf);
stoplist = new HashSet<String>(count);
for (int i = 0; i < count; ++i) {
stoplist.add(raf.readUTF());
}
- } else if (dict.dictFileVersion >= 4) {
+ } else if (dict.dictFileVersion >= 4) {
stoplist = new SerializableSerializer<Set<String>>().read(raf);
} else {
stoplist = Collections.emptySet();
}
rows = CachingList.create(
- UniformRAFList.create(raf, new RowBase.Serializer(this), raf.getFilePointer()),
- CACHE_SIZE);
+ UniformRAFList.create(raf, new RowBase.Serializer(this), raf.getFilePointer()),
+ CACHE_SIZE);
}
@Override
public List<HtmlEntry> htmlEntries;
public IndexEntry(final Index index, final String token, final String normalizedToken,
- final int startRow, final int numRows) {
+ final int startRow, final int numRows) {
assert token.equals(token.trim());
assert token.length() > 0;
this.token = token;
public int size() {
return htmlEntryIndices.length;
}
- };
+ };
}
} else if (index.dict.dictFileVersion >= 6) {
this.htmlEntries = CachingList.create(
- RAFList.create((RandomAccessFile)raf, index.dict.htmlEntryIndexSerializer,
- ((RandomAccessFile)raf).getFilePointer(), index.dict.dictFileVersion,
- index.dict.dictInfo + " htmlEntries: "), 1);
+ RAFList.create((RandomAccessFile)raf, index.dict.htmlEntryIndexSerializer,
+ ((RandomAccessFile)raf).getFilePointer(), index.dict.dictFileVersion,
+ index.dict.dictInfo + " htmlEntries: "), 1);
} else {
this.htmlEntries = Collections.emptyList();
}
public IndexEntry findExact(final String exactToken) {
final int result = Collections.binarySearch(
- TransformingList.create(sortedIndexEntries, INDEX_ENTRY_TO_TOKEN), exactToken,
- getSortComparator());
+ TransformingList.create(sortedIndexEntries, INDEX_ENTRY_TO_TOKEN), exactToken,
+ getSortComparator());
if (result >= 0) {
return sortedIndexEntries.get(result);
}
}
public final List<RowBase> multiWordSearch(
- final String searchText, final List<String> searchTokens,
- final AtomicBoolean interrupted) {
+ final String searchText, final List<String> searchTokens,
+ final AtomicBoolean interrupted) {
final long startMills = System.currentTimeMillis();
final List<RowBase> result = new ArrayList<RowBase>();
if (!stoplist.contains(searchToken)) {
if (normalizedNonStoplist.add(normalized)) {
final int numRows = getUpperBoundOnRowsStartingWith(normalized,
- MAX_SEARCH_ROWS, interrupted);
+ MAX_SEARCH_ROWS, interrupted);
if (numRows != -1 && numRows < leastRows) {
if (numRows == 0) {
// We really are done here.
System.out.println("Everything was in the stoplist!");
}
System.out.println("Searching using prefix: " + bestPrefix + ", leastRows=" + leastRows
- + ", searchTokens=" + searchTokens);
+ + ", searchTokens=" + searchTokens);
// Place to store the things that match.
final Map<RowMatchType, List<RowBase>> matches = new EnumMap<RowMatchType, List<RowBase>>(
- RowMatchType.class);
+ RowMatchType.class);
for (final RowMatchType rowMatchType : RowMatchType.values()) {
if (rowMatchType != RowMatchType.NO_MATCH) {
matches.put(rowMatchType, new ArrayList<RowBase>());
}
rowsAlreadySeen.add(rowKey);
final RowMatchType matchType = row.matches(searchTokens, pattern, normalizer(),
- swapPairEntries);
+ swapPairEntries);
if (matchType != RowMatchType.NO_MATCH) {
matches.get(matchType).add(row);
++matchCount;
// Sort them into a reasonable order.
final RowBase.LengthComparator lengthComparator = new RowBase.LengthComparator(
- swapPairEntries);
+ swapPairEntries);
for (final Collection<RowBase> rows : matches.values()) {
final List<RowBase> ordered = new ArrayList<RowBase>(rows);
Collections.sort(ordered, lengthComparator);
* simplified for performance and small code size.
*/
private static final String rtlChars =
- "\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC";
+ "\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC";
private static final String puncChars =
- "\\[\\]\\(\\)\\{\\}\\=";
+ "\\[\\]\\(\\)\\{\\}\\=";
private static final Pattern RTL_LEFT_BOUNDARY = Pattern.compile("([" + puncChars + "])(["
+ rtlChars + "])");
int version;
public NormalizeComparator(final Transliterator normalizer,
- final Comparator<Object> comparator, int version) {
+ final Comparator<Object> comparator, int version) {
this.normalizer = normalizer;
this.comparator = comparator;
- this.version = version;
+ this.version = version;
}
// Handles comparison between items containing "-".
import java.util.regex.Pattern;
public class PairEntry extends AbstractEntry implements RAFSerializable<PairEntry>,
- Comparable<PairEntry> {
+ Comparable<PairEntry> {
public final List<Pair> pairs;
}
public PairEntry(final Dictionary dictionary, final DataInput raf, final int index)
- throws IOException {
+ throws IOException {
super(dictionary, raf, index);
final int size = dictionary.dictFileVersion >= 7 ? StringUtil.readVarInt(raf) : raf.readInt();
pairs = new ArrayList<PairEntry.Pair>(size);
public static class Row extends RowBase {
Row(final DataInput raf, final int thisRowIndex,
- final Index index, int extra) throws IOException {
+ final Index index, int extra) throws IOException {
super(raf, thisRowIndex, index, extra);
}
Row(final int referenceIndex, final int thisRowIndex,
- final Index index) {
+ final Index index) {
super(referenceIndex, thisRowIndex, index);
}
@Override
public RowMatchType matches(final List<String> searchTokens,
- final Pattern orderedMatchPattern, final Transliterator normalizer,
- final boolean swapPairEntries) {
+ final Pattern orderedMatchPattern, final Transliterator normalizer,
+ final boolean swapPairEntries) {
final int side = swapPairEntries ? 1 : 0;
final List<Pair> pairs = getEntry().pairs;
final String[] pairSides = new String[pairs.size()];
private TokenRow tokenRow = null;
RowBase(final DataInput raf, final int thisRowIndex, final Index index, final int extra)
- throws IOException {
+ throws IOException {
super(thisRowIndex);
this.index = index;
this.referenceIndex = extra == -1 ? raf.readInt() : ((extra << 16) + raf.readUnsignedShort()); // what this points to.
}
final RowKey that = (RowKey) o;
return this.referenceIndex == that.referenceIndex
- && this.rowClass.equals(that.rowClass);
+ && this.rowClass.equals(that.rowClass);
}
@Override
// Did we hit the next set of TokenRows?
if (candidateUp.index() > this.index()) {
final int tokenIndex = index.sortedIndexEntries
- .get(candidateUp.referenceIndex - 1).startRow;
+ .get(candidateUp.referenceIndex - 1).startRow;
candidateUp = (TokenRow) index.rows.get(tokenIndex);
}
for (--rUp; rUp >= index(); --rUp) {
public abstract String getRawText(final boolean compact);
public abstract RowMatchType matches(final List<String> searchTokens,
- final Pattern orderedMatch, final Transliterator normalizer, boolean swapPairEntries);
+ final Pattern orderedMatch, final Transliterator normalizer, boolean swapPairEntries);
// RowBase must manage "disk-based" polymorphism. All other polymorphism is
// dealt with in the normal manner.
final String text;
public TextEntry(final Dictionary dictionary, final DataInput raf, final int index)
- throws IOException {
+ throws IOException {
super(dictionary, raf, index);
text = raf.readUTF();
throw new RuntimeException("TextEntry constructor should be unreachable");
public static class Row extends RowBase {
Row(final DataInput raf, final int thisRowIndex,
- final Index index, int extra) throws IOException {
+ final Index index, int extra) throws IOException {
super(raf, thisRowIndex, index, extra);
}
@Override
public RowMatchType matches(final List<String> searchTokens,
- final Pattern orderedMatchPattern, Transliterator normalizer,
- boolean swapPairEntries) {
+ final Pattern orderedMatchPattern, Transliterator normalizer,
+ boolean swapPairEntries) {
return null;
}
}
public final boolean hasMainEntry;
TokenRow(final DataInput raf, final int thisRowIndex, final Index index,
- final boolean hasMainEntry, int extra) throws IOException {
+ final boolean hasMainEntry, int extra) throws IOException {
super(raf, thisRowIndex, index, extra);
this.hasMainEntry = hasMainEntry;
}
TokenRow(final int referenceIndex, final int thisRowIndex, final Index index,
- final boolean hasMainEntry) {
+ final boolean hasMainEntry) {
super(referenceIndex, thisRowIndex, index);
this.hasMainEntry = hasMainEntry;
}
@Override
public RowMatchType matches(List<String> searchTokens, final Pattern orderedMatchPattern,
- Transliterator normalizer, boolean swapPairEntries) {
+ Transliterator normalizer, boolean swapPairEntries) {
return RowMatchType.NO_MATCH;
}
private final Map<String, Object> objects = new LinkedHashMap<String, Object>();
class ConstrainedOIS extends ObjectInputStream {
- public ConstrainedOIS(InputStream in) throws IOException {
- super(in);
- }
+ public ConstrainedOIS(InputStream in) throws IOException {
+ super(in);
+ }
- protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
- String name = desc.getName();
- // Note: try to avoid adding more classes.
- // LinkedHashMap is already more than enough for a DoS
- if (!name.equals(ArrayList.class.getName()) &&
- !name.equals(HashMap.class.getName()) &&
- !name.equals(LinkedHashMap.class.getName()) &&
- !name.equals(String.class.getName()) &&
- !name.equals(DictionaryApplication.DictionaryConfig.class.getName()) &&
- !name.equals(DictionaryInfo.class.getName()) &&
- !name.equals(DictionaryInfo.IndexInfo.class.getName()))
- {
- throw new InvalidClassException("Not allowed to deserialize class", name);
+ protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
+ String name = desc.getName();
+ // Note: try to avoid adding more classes.
+ // LinkedHashMap is already more than enough for a DoS
+ if (!name.equals(ArrayList.class.getName()) &&
+ !name.equals(HashMap.class.getName()) &&
+ !name.equals(LinkedHashMap.class.getName()) &&
+ !name.equals(String.class.getName()) &&
+ !name.equals(DictionaryApplication.DictionaryConfig.class.getName()) &&
+ !name.equals(DictionaryInfo.class.getName()) &&
+ !name.equals(DictionaryInfo.IndexInfo.class.getName())) {
+ throw new InvalidClassException("Not allowed to deserialize class", name);
+ }
+ return super.resolveClass(desc);
}
- return super.resolveClass(desc);
- }
}
public synchronized <T extends Serializable> T read(final String filename, final Class<T> resultClass) {
Log.d(getClass().getSimpleName(), "File empty: " + src);
return null;
}
- ObjectInputStream in = null;
+ ObjectInputStream in = null;
try {
in = new ConstrainedOIS(new FileInputStream(src));
object = in.readObject();
in.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Deserialization failed: " + src, e);
- try { if (in != null) in.close(); } catch (IOException e2) {}
+ try {
+ if (in != null) in.close();
+ } catch (IOException e2) {}
return null;
}
objects.put(filename, object);
public synchronized void write(final String filename, final Serializable object) {
objects.put(filename, object);
final File dest = new File(dir, filename);
- ObjectOutputStream out = null;
+ ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(dest));
out.writeObject(object);
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Serialization failed: " + dest, e);
}
- try { if (out != null) out.close(); } catch (IOException e) {}
+ try {
+ if (out != null) out.close();
+ } catch (IOException e) {}
}
private PersistentObjectCache(final Context context) {
dir = filesDir != null ? filesDir : Environment.getExternalStorageDirectory();
if (dir == null) {
throw new RuntimeException("context.getFilesDir() == " + context.getFilesDir()
- + ", Environment.getExternalStorageDirectory()="
- + Environment.getExternalStorageDirectory());
+ + ", Environment.getExternalStorageDirectory()="
+ + Environment.getExternalStorageDirectory());
}
}
} else {
if (!instance.dir.equals(context.getFilesDir())) {
throw new RuntimeException("File dir changed. old=" + instance.dir + ", new="
- + context.getFilesDir());
+ + context.getFilesDir());
}
}
return instance;