1 // Copyright 2011 Google Inc. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 package com.hughes.android.dictionary;
17 import android.content.Context;
18 import android.content.Intent;
19 import android.content.SharedPreferences;
20 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
21 import android.net.Uri;
22 import android.os.Build;
23 import android.os.Environment;
24 import android.preference.PreferenceManager;
25 import android.support.v4.view.MenuItemCompat;
26 import android.util.Log;
27 import android.util.TypedValue;
28 import android.view.Menu;
29 import android.view.MenuItem;
30 import android.view.MenuItem.OnMenuItemClickListener;
32 import com.hughes.android.dictionary.CollatorWrapper;
33 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
34 import com.hughes.android.dictionary.engine.Dictionary;
35 import com.hughes.android.dictionary.engine.TransliteratorManager;
36 import com.hughes.android.util.PersistentObjectCache;
37 import com.hughes.util.ListUtil;
39 import java.io.BufferedReader;
41 import java.io.IOException;
42 import java.io.InputStreamReader;
43 import java.io.Serializable;
44 import java.util.ArrayList;
45 import java.util.Collections;
46 import java.util.Comparator;
47 import java.util.HashMap;
48 import java.util.List;
49 import java.util.Locale;
52 public enum DictionaryApplication {
55 private Context appContext;
57 static final String LOG = "QuickDicApp";
59 // If set to false, avoid use of ICU collator
60 // Works well enough for most european languages,
61 // gives faster startup and avoids crashes on some
62 // devices due to Dalvik bugs (e.g. ARMv6, S5570i, CM11)
64 // Leave it enabled by default for correctness except
65 // for my known broken development/performance test device config.
66 //static public final boolean USE_COLLATOR = !android.os.Build.FINGERPRINT.equals("Samsung/cm_tassve/tassve:4.4.4/KTU84Q/20150211:userdebug/release-keys");
67 static public final boolean USE_COLLATOR = true;
69 static public final TransliteratorManager.ThreadSetup threadBackground = new TransliteratorManager.ThreadSetup() {
71 public void onThreadStart() {
72 // THREAD_PRIORITY_BACKGROUND seemed like a good idea, but it
73 // can make Transliterator go from 20 seconds to 3 minutes (!)
74 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
78 // Static, determined by resources (and locale).
80 static Map<String, DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
83 DEFAULT(R.style.Theme_Default,
84 R.style.Theme_Default_TokenRow_Fg,
85 R.color.theme_default_token_row_fg,
86 R.drawable.theme_default_token_row_main_bg,
87 R.drawable.theme_default_token_row_other_bg,
88 R.drawable.theme_default_normal_row_bg),
90 LIGHT(R.style.Theme_Light,
91 R.style.Theme_Light_TokenRow_Fg,
92 R.color.theme_light_token_row_fg,
93 R.drawable.theme_light_token_row_main_bg,
94 R.drawable.theme_light_token_row_other_bg,
95 R.drawable.theme_light_normal_row_bg);
97 Theme(final int themeId, final int tokenRowFg,
98 final int tokenRowFgColor,
99 final int tokenRowMainBg, final int tokenRowOtherBg,
100 final int normalRowBg) {
101 this.themeId = themeId;
102 this.tokenRowFg = tokenRowFg;
103 this.tokenRowFgColor = tokenRowFgColor;
104 this.tokenRowMainBg = tokenRowMainBg;
105 this.tokenRowOtherBg = tokenRowOtherBg;
106 this.normalRowBg = normalRowBg;
110 final int tokenRowFg;
111 final int tokenRowFgColor;
112 final int tokenRowMainBg;
113 final int tokenRowOtherBg;
114 final int normalRowBg;
117 public static final class DictionaryConfig implements Serializable {
118 private static final long serialVersionUID = -1444177164708201263L;
119 // User-ordered list, persisted, just the ones that are/have been
121 final List<String> dictionaryFilesOrdered = new ArrayList<>();
123 final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new HashMap<>();
126 * Sometimes a deserialized version of this data structure isn't valid.
128 @SuppressWarnings("ConstantConditions")
130 return uncompressedFilenameToDictionaryInfo != null && dictionaryFilesOrdered != null;
134 DictionaryConfig dictionaryConfig = null;
136 public int languageButtonPixels = -1;
138 static synchronized void staticInit(final Context context) {
139 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
142 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new HashMap<>();
143 final BufferedReader reader = new BufferedReader(
144 new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
147 while ((line = reader.readLine()) != null) {
148 if (line.length() == 0 || line.charAt(0) == '#') {
151 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
152 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
153 dictionaryInfo.uncompressedFilename, dictionaryInfo);
155 } catch (IOException e) {
156 Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
160 } catch (IOException ignored) {}
163 public synchronized void init(Context c) {
164 if (appContext != null) {
165 assert c == appContext;
169 Log.d("QuickDic", "Application: onCreate");
170 TransliteratorManager.init(null, threadBackground);
171 staticInit(appContext);
173 languageButtonPixels = (int) TypedValue.applyDimension(
174 TypedValue.COMPLEX_UNIT_DIP, 60, appContext.getResources().getDisplayMetrics());
176 // Load the dictionaries we know about.
177 dictionaryConfig = PersistentObjectCache.init(appContext).read(
178 C.DICTIONARY_CONFIGS, DictionaryConfig.class);
179 if (dictionaryConfig == null) {
180 dictionaryConfig = new DictionaryConfig();
182 if (!dictionaryConfig.isValid()) {
183 dictionaryConfig = new DictionaryConfig();
187 appContext.setTheme(getSelectedTheme().themeId);
188 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
189 prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
191 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
193 Log.d("QuickDic", "prefs changed: " + key);
194 if (key.equals(appContext.getString(R.string.themeKey))) {
195 appContext.setTheme(getSelectedTheme().themeId);
201 public static void onCreateGlobalOptionsMenu(
202 final Context context, final Menu menu) {
203 final Context c = context.getApplicationContext();
205 final MenuItem preferences = menu.add(c.getString(R.string.settings));
206 MenuItemCompat.setShowAsAction(preferences, MenuItem.SHOW_AS_ACTION_NEVER);
207 preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
208 public boolean onMenuItemClick(final MenuItem menuItem) {
209 PreferenceActivity.prefsMightHaveChanged = true;
210 final Intent intent = new Intent(c, PreferenceActivity.class);
211 context.startActivity(intent);
216 final MenuItem help = menu.add(c.getString(R.string.help));
217 MenuItemCompat.setShowAsAction(help, MenuItem.SHOW_AS_ACTION_NEVER);
218 help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
219 public boolean onMenuItemClick(final MenuItem menuItem) {
220 context.startActivity(HtmlDisplayActivity.getHelpLaunchIntent(c));
225 final MenuItem reportIssue = menu.add(c.getString(R.string.reportIssue));
226 MenuItemCompat.setShowAsAction(reportIssue, MenuItem.SHOW_AS_ACTION_NEVER);
227 reportIssue.setOnMenuItemClickListener(new OnMenuItemClickListener() {
228 public boolean onMenuItemClick(final MenuItem menuItem) {
229 final Intent intent = new Intent(Intent.ACTION_VIEW);
231 .parse("https://github.com/rdoeffinger/Dictionary/issues"));
232 context.startActivity(intent);
237 final MenuItem about = menu.add(c.getString(R.string.about));
238 MenuItemCompat.setShowAsAction(about, MenuItem.SHOW_AS_ACTION_NEVER);
239 about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
240 public boolean onMenuItemClick(final MenuItem menuItem) {
241 final Intent intent = new Intent(c, AboutActivity.class);
242 context.startActivity(intent);
248 private String selectDefaultDir() {
249 final File defaultDictDir = new File(Environment.getExternalStorageDirectory(), "quickDic");
250 String dir = defaultDictDir.getAbsolutePath();
251 File dictDir = new File(dir);
252 String[] fileList = dictDir.isDirectory() ? dictDir.list() : null;
253 if (fileList != null && fileList.length > 0) {
258 efd = appContext.getExternalFilesDir(null);
259 } catch (Exception ignored) {
263 if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
264 appContext.getExternalFilesDirs(null);
266 if (efd.isDirectory() && efd.canWrite() && checkFileCreate(efd)) {
267 return efd.getAbsolutePath();
270 if (!dictDir.isDirectory() && !dictDir.mkdirs()) {
271 return appContext.getFilesDir().getAbsolutePath();
276 public synchronized File getDictDir() {
277 // This metaphor doesn't work, because we've already reset
278 // prefsMightHaveChanged.
279 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
280 String dir = prefs.getString(appContext.getString(R.string.quickdicDirectoryKey), "");
282 dir = selectDefaultDir();
284 File dictDir = new File(dir);
286 if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
287 appContext.getExternalFilesDirs(null);
292 static public boolean checkFileCreate(File dir) {
294 File testfile = new File(dir, "quickdic_writetest");
297 res = testfile.createNewFile() & testfile.delete();
298 } catch (Exception ignored) {
303 public File getWordListFile() {
304 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
305 String file = prefs.getString(appContext.getString(R.string.wordListFileKey), "");
306 if (file.isEmpty()) {
307 return new File(getDictDir(), "wordList.txt");
309 return new File(file);
312 public Theme getSelectedTheme() {
313 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
314 final String theme = prefs.getString(appContext.getString(R.string.themeKey), "themeLight");
315 if (theme.equals("themeLight")) {
318 return Theme.DEFAULT;
322 public File getPath(String uncompressedFilename) {
323 return new File(getDictDir(), uncompressedFilename);
326 String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
327 String defaultLangName = null;
328 final Map<String, String> fileToNameCache = new HashMap<>();
330 public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
331 // Hack to put the default locale first in the name.
332 if (indexInfos.size() > 1 &&
333 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
334 List<IndexInfo> result = new ArrayList<>(indexInfos);
335 ListUtil.swap(result, 0, 1);
341 public synchronized String getDictionaryName(final String uncompressedFilename) {
342 final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
343 if (!currentLocale.equals(defaultLangISO2)) {
344 defaultLangISO2 = currentLocale;
345 fileToNameCache.clear();
346 defaultLangName = null;
348 if (defaultLangName == null) {
349 defaultLangName = IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, defaultLangISO2);
352 String name = fileToNameCache.get(uncompressedFilename);
357 final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
358 .get(uncompressedFilename);
359 if (dictionaryInfo != null) {
360 final StringBuilder nameBuilder = new StringBuilder();
362 List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
363 for (int i = 0; i < sortedIndexInfos.size(); ++i) {
365 nameBuilder.append("-");
368 .append(IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, sortedIndexInfos.get(i).shortName));
370 name = nameBuilder.toString();
372 name = uncompressedFilename.replace(".quickdic", "");
374 fileToNameCache.put(uncompressedFilename, name);
378 public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
379 dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
380 dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
381 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
384 public synchronized void sortDictionaries() {
385 Collections.sort(dictionaryConfig.dictionaryFilesOrdered, uncompressedFilenameComparator);
386 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
389 public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
390 while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
392 dictionaryConfig.uncompressedFilenameToDictionaryInfo
393 .remove(dictionaryInfo.uncompressedFilename);
394 getPath(dictionaryInfo.uncompressedFilename).delete();
395 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
398 final Comparator<Object> collator = USE_COLLATOR ? CollatorWrapper.getInstance() : null;
399 final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
401 public int compare(String uncompressedFilename1, String uncompressedFilename2) {
402 final String name1 = getDictionaryName(uncompressedFilename1);
403 final String name2 = getDictionaryName(uncompressedFilename2);
404 if (defaultLangName.length() > 0) {
405 if (name1.startsWith(defaultLangName + "-")
406 && !name2.startsWith(defaultLangName + "-")) {
408 } else if (name2.startsWith(defaultLangName + "-")
409 && !name1.startsWith(defaultLangName + "-")) {
413 return collator != null ? collator.compare(name1, name2) : name1.compareToIgnoreCase(name2);
416 final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
418 public int compare(DictionaryInfo d1, DictionaryInfo d2) {
419 // Single-index dictionaries first.
420 if (d1.indexInfos.size() != d2.indexInfos.size()) {
421 return d1.indexInfos.size() - d2.indexInfos.size();
423 return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
424 d2.uncompressedFilename);
428 public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
429 new Thread(new Runnable() {
432 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
433 synchronized (DictionaryApplication.this) {
434 oldDictionaryConfig.dictionaryFilesOrdered
435 .addAll(dictionaryConfig.dictionaryFilesOrdered);
437 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
438 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
439 final File dictFile = getPath(uncompressedFilename);
440 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
441 if (dictionaryInfo.isValid() || dictFile.exists()) {
442 newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
443 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
444 uncompressedFilename, dictionaryInfo);
448 // Are there dictionaries on the device that we didn't know
450 // Pick them up and put them at the end of the list.
451 final List<String> toAddSorted = new ArrayList<>();
452 final File[] dictDirFiles = getDictDir().listFiles();
453 if (dictDirFiles != null) {
454 for (final File file : dictDirFiles) {
455 if (file.getName().endsWith(".zip")) {
456 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
457 .containsKey(file.getName().replace(".zip", ""))) {
461 if (!file.getName().endsWith(".quickdic")) {
464 if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
465 .containsKey(file.getName())) {
466 // We have it in our list already.
469 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
470 if (!dictionaryInfo.isValid()) {
471 Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
474 toAddSorted.add(file.getName());
475 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
476 file.getName(), dictionaryInfo);
479 Log.w(LOG, "dictDir is not a directory: " + getDictDir().getPath());
481 if (!toAddSorted.isEmpty()) {
482 Collections.sort(toAddSorted, uncompressedFilenameComparator);
483 newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
487 PersistentObjectCache.getInstance()
488 .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
489 } catch (Exception e) {
490 Log.e(LOG, "Failed persisting dictionary configs", e);
493 synchronized (DictionaryApplication.this) {
494 dictionaryConfig = newDictionaryConfig;
498 onUpdateFinished.run();
499 } catch (Exception e) {
500 Log.e(LOG, "Exception running callback.", e);
506 private boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
507 if (filters == null) {
510 for (final String filter : filters) {
511 if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
519 public synchronized List<DictionaryInfo> getDictionariesOnDevice(String[] filters) {
520 final List<DictionaryInfo> result = new ArrayList<>(
521 dictionaryConfig.dictionaryFilesOrdered.size());
522 for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
523 final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo
524 .get(uncompressedFilename);
525 if (dictionaryInfo != null && matchesFilters(dictionaryInfo, filters)) {
526 result.add(dictionaryInfo);
532 public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
533 final List<DictionaryInfo> result = new ArrayList<>(
534 dictionaryConfig.dictionaryFilesOrdered.size());
536 final Map<String, DictionaryInfo> remaining = new HashMap<>(
537 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
538 remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
539 for (final DictionaryInfo dictionaryInfo : remaining.values()) {
540 if (matchesFilters(dictionaryInfo, filters)) {
541 result.add(dictionaryInfo);
544 Collections.sort(result, dictionaryInfoComparator);
548 public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
549 final DictionaryInfo downloadable =
550 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
551 dictionaryInfo.uncompressedFilename);
552 return downloadable != null &&
553 downloadable.creationMillis > dictionaryInfo.creationMillis;
556 public DictionaryInfo getDownloadable(final String uncompressedFilename) {
557 return DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);