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.content.res.Configuration;
22 import android.net.Uri;
23 import android.os.Build;
24 import android.os.Environment;
25 import android.support.v7.preference.PreferenceManager;
26 import android.support.v4.view.MenuItemCompat;
27 import android.util.Log;
28 import android.util.TypedValue;
29 import android.view.Menu;
30 import android.view.MenuItem;
31 import android.view.MenuItem.OnMenuItemClickListener;
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 public static final boolean USE_COLLATOR = true;
69 public static 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 public static 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")) {
317 } else if (theme.equals("themeSystem")) {
318 int mode = (appContext.getResources().getConfiguration().uiMode &
319 Configuration.UI_MODE_NIGHT_MASK);
320 return ((mode == Configuration.UI_MODE_NIGHT_YES) ?
324 return Theme.DEFAULT;
328 public File getPath(String uncompressedFilename) {
329 return new File(getDictDir(), uncompressedFilename);
332 String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
333 String defaultLangName = null;
334 final Map<String, String> fileToNameCache = new HashMap<>();
336 public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
337 // Hack to put the default locale first in the name.
338 if (indexInfos.size() > 1 &&
339 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
340 List<IndexInfo> result = new ArrayList<>(indexInfos);
341 ListUtil.swap(result, 0, 1);
347 public synchronized String getDictionaryName(final String uncompressedFilename) {
348 final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
349 if (!currentLocale.equals(defaultLangISO2)) {
350 defaultLangISO2 = currentLocale;
351 fileToNameCache.clear();
352 defaultLangName = null;
354 if (defaultLangName == null) {
355 defaultLangName = IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, defaultLangISO2);
358 String name = fileToNameCache.get(uncompressedFilename);
363 final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
364 .get(uncompressedFilename);
365 if (dictionaryInfo != null) {
366 final StringBuilder nameBuilder = new StringBuilder();
368 List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
369 for (int i = 0; i < sortedIndexInfos.size(); ++i) {
371 nameBuilder.append("-");
374 .append(IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, sortedIndexInfos.get(i).shortName));
376 name = nameBuilder.toString();
378 name = uncompressedFilename.replace(".quickdic", "");
380 fileToNameCache.put(uncompressedFilename, name);
384 public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
385 dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
386 dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
387 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
390 public synchronized void sortDictionaries() {
391 Collections.sort(dictionaryConfig.dictionaryFilesOrdered, uncompressedFilenameComparator);
392 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
395 public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
396 while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
398 dictionaryConfig.uncompressedFilenameToDictionaryInfo
399 .remove(dictionaryInfo.uncompressedFilename);
400 getPath(dictionaryInfo.uncompressedFilename).delete();
401 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
404 final Comparator<Object> collator = USE_COLLATOR ? CollatorWrapper.getInstance() : null;
405 final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
407 public int compare(String uncompressedFilename1, String uncompressedFilename2) {
408 final String name1 = getDictionaryName(uncompressedFilename1);
409 final String name2 = getDictionaryName(uncompressedFilename2);
410 if (defaultLangName.length() > 0) {
411 if (name1.startsWith(defaultLangName + "-")
412 && !name2.startsWith(defaultLangName + "-")) {
414 } else if (name2.startsWith(defaultLangName + "-")
415 && !name1.startsWith(defaultLangName + "-")) {
419 return collator != null ? collator.compare(name1, name2) : name1.compareToIgnoreCase(name2);
422 final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
424 public int compare(DictionaryInfo d1, DictionaryInfo d2) {
425 // Single-index dictionaries first.
426 if (d1.indexInfos.size() != d2.indexInfos.size()) {
427 return d1.indexInfos.size() - d2.indexInfos.size();
429 return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
430 d2.uncompressedFilename);
434 public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
435 new Thread(new Runnable() {
438 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
439 synchronized (DictionaryApplication.this) {
440 oldDictionaryConfig.dictionaryFilesOrdered
441 .addAll(dictionaryConfig.dictionaryFilesOrdered);
443 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
444 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
445 final File dictFile = getPath(uncompressedFilename);
446 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
447 if (dictionaryInfo.isValid() || dictFile.exists()) {
448 newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
449 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
450 uncompressedFilename, dictionaryInfo);
454 // Are there dictionaries on the device that we didn't know
456 // Pick them up and put them at the end of the list.
457 final List<String> toAddSorted = new ArrayList<>();
458 final File[] dictDirFiles = getDictDir().listFiles();
459 if (dictDirFiles != null) {
460 for (final File file : dictDirFiles) {
461 if (file.getName().endsWith(".zip")) {
462 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
463 .containsKey(file.getName().replace(".zip", ""))) {
467 if (!file.getName().endsWith(".quickdic")) {
470 if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
471 .containsKey(file.getName())) {
472 // We have it in our list already.
475 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
476 if (!dictionaryInfo.isValid()) {
477 Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
480 toAddSorted.add(file.getName());
481 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
482 file.getName(), dictionaryInfo);
485 Log.w(LOG, "dictDir is not a directory: " + getDictDir().getPath());
487 if (!toAddSorted.isEmpty()) {
488 Collections.sort(toAddSorted, uncompressedFilenameComparator);
489 newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
493 PersistentObjectCache.getInstance()
494 .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
495 } catch (Exception e) {
496 Log.e(LOG, "Failed persisting dictionary configs", e);
499 synchronized (DictionaryApplication.this) {
500 dictionaryConfig = newDictionaryConfig;
504 onUpdateFinished.run();
505 } catch (Exception e) {
506 Log.e(LOG, "Exception running callback.", e);
512 private boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
513 if (filters == null) {
516 for (final String filter : filters) {
517 if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
525 public synchronized List<DictionaryInfo> getDictionariesOnDevice(String[] filters) {
526 final List<DictionaryInfo> result = new ArrayList<>(
527 dictionaryConfig.dictionaryFilesOrdered.size());
528 for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
529 final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo
530 .get(uncompressedFilename);
531 if (dictionaryInfo != null && matchesFilters(dictionaryInfo, filters)) {
532 result.add(dictionaryInfo);
538 public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
539 final List<DictionaryInfo> result = new ArrayList<>(
540 dictionaryConfig.dictionaryFilesOrdered.size());
542 final Map<String, DictionaryInfo> remaining = new HashMap<>(
543 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
544 remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
545 for (final DictionaryInfo dictionaryInfo : remaining.values()) {
546 if (matchesFilters(dictionaryInfo, filters)) {
547 result.add(dictionaryInfo);
550 Collections.sort(result, dictionaryInfoComparator);
554 public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
555 final DictionaryInfo downloadable =
556 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
557 dictionaryInfo.uncompressedFilename);
558 return downloadable != null &&
559 downloadable.creationMillis > dictionaryInfo.creationMillis;
562 public DictionaryInfo getDownloadable(final String uncompressedFilename) {
563 return DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);