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.DictionaryInfo.IndexInfo;
33 import com.hughes.android.dictionary.engine.Dictionary;
34 import com.hughes.android.dictionary.engine.TransliteratorManager;
35 import com.hughes.android.util.PersistentObjectCache;
36 import com.hughes.util.ListUtil;
38 import java.io.BufferedReader;
40 import java.io.IOException;
41 import java.io.InputStreamReader;
42 import java.io.Serializable;
43 import java.util.ArrayList;
44 import java.util.Collections;
45 import java.util.Comparator;
46 import java.util.HashMap;
47 import java.util.List;
48 import java.util.Locale;
51 public enum DictionaryApplication {
54 private Context appContext;
56 static final String LOG = "QuickDicApp";
58 // If set to false, avoid use of ICU collator
59 // Works well enough for most european languages,
60 // gives faster startup and avoids crashes on some
61 // devices due to Dalvik bugs (e.g. ARMv6, S5570i, CM11)
63 // Leave it enabled by default for correctness except
64 // for my known broken development/performance test device config.
65 //static public final boolean USE_COLLATOR = !android.os.Build.FINGERPRINT.equals("Samsung/cm_tassve/tassve:4.4.4/KTU84Q/20150211:userdebug/release-keys");
66 public static final boolean USE_COLLATOR = true;
68 public static final TransliteratorManager.ThreadSetup threadBackground = new TransliteratorManager.ThreadSetup() {
70 public void onThreadStart() {
71 // THREAD_PRIORITY_BACKGROUND seemed like a good idea, but it
72 // can make Transliterator go from 20 seconds to 3 minutes (!)
73 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
77 // Static, determined by resources (and locale).
79 static Map<String, DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
82 DEFAULT(R.style.Theme_Default,
83 R.style.Theme_Default_TokenRow_Fg,
84 R.color.theme_default_token_row_fg,
85 R.drawable.theme_default_token_row_main_bg,
86 R.drawable.theme_default_token_row_other_bg,
87 R.drawable.theme_default_normal_row_bg),
89 LIGHT(R.style.Theme_Light,
90 R.style.Theme_Light_TokenRow_Fg,
91 R.color.theme_light_token_row_fg,
92 R.drawable.theme_light_token_row_main_bg,
93 R.drawable.theme_light_token_row_other_bg,
94 R.drawable.theme_light_normal_row_bg);
96 Theme(final int themeId, final int tokenRowFg,
97 final int tokenRowFgColor,
98 final int tokenRowMainBg, final int tokenRowOtherBg,
99 final int normalRowBg) {
100 this.themeId = themeId;
101 this.tokenRowFg = tokenRowFg;
102 this.tokenRowFgColor = tokenRowFgColor;
103 this.tokenRowMainBg = tokenRowMainBg;
104 this.tokenRowOtherBg = tokenRowOtherBg;
105 this.normalRowBg = normalRowBg;
109 final int tokenRowFg;
110 final int tokenRowFgColor;
111 final int tokenRowMainBg;
112 final int tokenRowOtherBg;
113 final int normalRowBg;
116 public static final class DictionaryConfig implements Serializable {
117 private static final long serialVersionUID = -1444177164708201263L;
118 // User-ordered list, persisted, just the ones that are/have been
120 final List<String> dictionaryFilesOrdered = new ArrayList<>();
122 final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new HashMap<>();
125 * Sometimes a deserialized version of this data structure isn't valid.
127 @SuppressWarnings("ConstantConditions")
129 return uncompressedFilenameToDictionaryInfo != null && dictionaryFilesOrdered != null;
133 DictionaryConfig dictionaryConfig = null;
135 public int languageButtonPixels = -1;
137 static synchronized void staticInit(final Context context) {
138 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
141 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new HashMap<>();
142 final BufferedReader reader = new BufferedReader(
143 new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
146 while ((line = reader.readLine()) != null) {
147 if (line.length() == 0 || line.charAt(0) == '#') {
150 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
151 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
152 dictionaryInfo.uncompressedFilename, dictionaryInfo);
154 } catch (IOException e) {
155 Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
159 } catch (IOException ignored) {}
162 public synchronized void init(Context c) {
163 if (appContext != null) {
164 assert c == appContext;
168 Log.d("QuickDic", "Application: onCreate");
169 TransliteratorManager.init(null, threadBackground);
170 staticInit(appContext);
172 languageButtonPixels = (int) TypedValue.applyDimension(
173 TypedValue.COMPLEX_UNIT_DIP, 60, appContext.getResources().getDisplayMetrics());
175 // Load the dictionaries we know about.
176 dictionaryConfig = PersistentObjectCache.init(appContext).read(
177 C.DICTIONARY_CONFIGS, DictionaryConfig.class);
178 if (dictionaryConfig == null) {
179 dictionaryConfig = new DictionaryConfig();
181 if (!dictionaryConfig.isValid()) {
182 dictionaryConfig = new DictionaryConfig();
186 appContext.setTheme(getSelectedTheme().themeId);
187 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
188 prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
190 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
192 Log.d("QuickDic", "prefs changed: " + key);
193 if (key.equals(appContext.getString(R.string.themeKey))) {
194 appContext.setTheme(getSelectedTheme().themeId);
200 public static void onCreateGlobalOptionsMenu(
201 final Context context, final Menu menu) {
202 final Context c = context.getApplicationContext();
204 final MenuItem preferences = menu.add(c.getString(R.string.settings));
205 MenuItemCompat.setShowAsAction(preferences, MenuItem.SHOW_AS_ACTION_NEVER);
206 preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
207 public boolean onMenuItemClick(final MenuItem menuItem) {
208 PreferenceActivity.prefsMightHaveChanged = true;
209 final Intent intent = new Intent(c, PreferenceActivity.class);
210 context.startActivity(intent);
215 final MenuItem help = menu.add(c.getString(R.string.help));
216 MenuItemCompat.setShowAsAction(help, MenuItem.SHOW_AS_ACTION_NEVER);
217 help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
218 public boolean onMenuItemClick(final MenuItem menuItem) {
219 context.startActivity(HtmlDisplayActivity.getHelpLaunchIntent(c));
224 final MenuItem reportIssue = menu.add(c.getString(R.string.reportIssue));
225 MenuItemCompat.setShowAsAction(reportIssue, MenuItem.SHOW_AS_ACTION_NEVER);
226 reportIssue.setOnMenuItemClickListener(new OnMenuItemClickListener() {
227 public boolean onMenuItemClick(final MenuItem menuItem) {
228 final Intent intent = new Intent(Intent.ACTION_VIEW);
230 .parse("https://github.com/rdoeffinger/Dictionary/issues"));
231 context.startActivity(intent);
236 final MenuItem about = menu.add(c.getString(R.string.about));
237 MenuItemCompat.setShowAsAction(about, MenuItem.SHOW_AS_ACTION_NEVER);
238 about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
239 public boolean onMenuItemClick(final MenuItem menuItem) {
240 final Intent intent = new Intent(c, AboutActivity.class);
241 context.startActivity(intent);
247 private String selectDefaultDir() {
248 final File defaultDictDir = new File(Environment.getExternalStorageDirectory(), "quickDic");
249 String dir = defaultDictDir.getAbsolutePath();
250 File dictDir = new File(dir);
251 String[] fileList = dictDir.isDirectory() ? dictDir.list() : null;
252 if (fileList != null && fileList.length > 0) {
257 efd = appContext.getExternalFilesDir(null);
258 } catch (Exception ignored) {
262 if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
263 appContext.getExternalFilesDirs(null);
265 if (efd.isDirectory() && efd.canWrite() && checkFileCreate(efd)) {
266 return efd.getAbsolutePath();
269 if (!dictDir.isDirectory() && !dictDir.mkdirs()) {
270 return appContext.getFilesDir().getAbsolutePath();
275 public synchronized File getDictDir() {
276 // This metaphor doesn't work, because we've already reset
277 // prefsMightHaveChanged.
278 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
279 String dir = prefs.getString(appContext.getString(R.string.quickdicDirectoryKey), "");
281 dir = selectDefaultDir();
283 File dictDir = new File(dir);
285 if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
286 appContext.getExternalFilesDirs(null);
291 public static boolean checkFileCreate(File dir) {
293 File testfile = new File(dir, "quickdic_writetest");
296 res = testfile.createNewFile() & testfile.delete();
297 } catch (Exception ignored) {
302 public File getWordListFile() {
303 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
304 String file = prefs.getString(appContext.getString(R.string.wordListFileKey), "");
305 if (file.isEmpty()) {
306 return new File(getDictDir(), "wordList.txt");
308 return new File(file);
311 public Theme getSelectedTheme() {
312 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
313 final String theme = prefs.getString(appContext.getString(R.string.themeKey), "themeLight");
314 if (theme.equals("themeLight")) {
317 return Theme.DEFAULT;
321 public File getPath(String uncompressedFilename) {
322 return new File(getDictDir(), uncompressedFilename);
325 String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
326 String defaultLangName = null;
327 final Map<String, String> fileToNameCache = new HashMap<>();
329 public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
330 // Hack to put the default locale first in the name.
331 if (indexInfos.size() > 1 &&
332 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
333 List<IndexInfo> result = new ArrayList<>(indexInfos);
334 ListUtil.swap(result, 0, 1);
340 public synchronized String getDictionaryName(final String uncompressedFilename) {
341 final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
342 if (!currentLocale.equals(defaultLangISO2)) {
343 defaultLangISO2 = currentLocale;
344 fileToNameCache.clear();
345 defaultLangName = null;
347 if (defaultLangName == null) {
348 defaultLangName = IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, defaultLangISO2);
351 String name = fileToNameCache.get(uncompressedFilename);
356 final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
357 .get(uncompressedFilename);
358 if (dictionaryInfo != null) {
359 final StringBuilder nameBuilder = new StringBuilder();
361 List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
362 for (int i = 0; i < sortedIndexInfos.size(); ++i) {
364 nameBuilder.append("-");
367 .append(IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, sortedIndexInfos.get(i).shortName));
369 name = nameBuilder.toString();
371 name = uncompressedFilename.replace(".quickdic", "");
373 fileToNameCache.put(uncompressedFilename, name);
377 public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
378 dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
379 dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
380 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
383 public synchronized void sortDictionaries() {
384 Collections.sort(dictionaryConfig.dictionaryFilesOrdered, uncompressedFilenameComparator);
385 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
388 public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
389 while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
391 dictionaryConfig.uncompressedFilenameToDictionaryInfo
392 .remove(dictionaryInfo.uncompressedFilename);
393 getPath(dictionaryInfo.uncompressedFilename).delete();
394 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
397 final Comparator<Object> collator = USE_COLLATOR ? CollatorWrapper.getInstance() : null;
398 final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
400 public int compare(String uncompressedFilename1, String uncompressedFilename2) {
401 final String name1 = getDictionaryName(uncompressedFilename1);
402 final String name2 = getDictionaryName(uncompressedFilename2);
403 if (defaultLangName.length() > 0) {
404 if (name1.startsWith(defaultLangName + "-")
405 && !name2.startsWith(defaultLangName + "-")) {
407 } else if (name2.startsWith(defaultLangName + "-")
408 && !name1.startsWith(defaultLangName + "-")) {
412 return collator != null ? collator.compare(name1, name2) : name1.compareToIgnoreCase(name2);
415 final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
417 public int compare(DictionaryInfo d1, DictionaryInfo d2) {
418 // Single-index dictionaries first.
419 if (d1.indexInfos.size() != d2.indexInfos.size()) {
420 return d1.indexInfos.size() - d2.indexInfos.size();
422 return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
423 d2.uncompressedFilename);
427 public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
428 new Thread(new Runnable() {
431 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
432 synchronized (DictionaryApplication.this) {
433 oldDictionaryConfig.dictionaryFilesOrdered
434 .addAll(dictionaryConfig.dictionaryFilesOrdered);
436 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
437 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
438 final File dictFile = getPath(uncompressedFilename);
439 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
440 if (dictionaryInfo.isValid() || dictFile.exists()) {
441 newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
442 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
443 uncompressedFilename, dictionaryInfo);
447 // Are there dictionaries on the device that we didn't know
449 // Pick them up and put them at the end of the list.
450 final List<String> toAddSorted = new ArrayList<>();
451 final File[] dictDirFiles = getDictDir().listFiles();
452 if (dictDirFiles != null) {
453 for (final File file : dictDirFiles) {
454 if (file.getName().endsWith(".zip")) {
455 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
456 .containsKey(file.getName().replace(".zip", ""))) {
460 if (!file.getName().endsWith(".quickdic")) {
463 if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
464 .containsKey(file.getName())) {
465 // We have it in our list already.
468 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
469 if (!dictionaryInfo.isValid()) {
470 Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
473 toAddSorted.add(file.getName());
474 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
475 file.getName(), dictionaryInfo);
478 Log.w(LOG, "dictDir is not a directory: " + getDictDir().getPath());
480 if (!toAddSorted.isEmpty()) {
481 Collections.sort(toAddSorted, uncompressedFilenameComparator);
482 newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
486 PersistentObjectCache.getInstance()
487 .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
488 } catch (Exception e) {
489 Log.e(LOG, "Failed persisting dictionary configs", e);
492 synchronized (DictionaryApplication.this) {
493 dictionaryConfig = newDictionaryConfig;
497 onUpdateFinished.run();
498 } catch (Exception e) {
499 Log.e(LOG, "Exception running callback.", e);
505 private boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
506 if (filters == null) {
509 for (final String filter : filters) {
510 if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
518 public synchronized List<DictionaryInfo> getDictionariesOnDevice(String[] filters) {
519 final List<DictionaryInfo> result = new ArrayList<>(
520 dictionaryConfig.dictionaryFilesOrdered.size());
521 for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
522 final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo
523 .get(uncompressedFilename);
524 if (dictionaryInfo != null && matchesFilters(dictionaryInfo, filters)) {
525 result.add(dictionaryInfo);
531 public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
532 final List<DictionaryInfo> result = new ArrayList<>(
533 dictionaryConfig.dictionaryFilesOrdered.size());
535 final Map<String, DictionaryInfo> remaining = new HashMap<>(
536 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
537 remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
538 for (final DictionaryInfo dictionaryInfo : remaining.values()) {
539 if (matchesFilters(dictionaryInfo, filters)) {
540 result.add(dictionaryInfo);
543 Collections.sort(result, dictionaryInfoComparator);
547 public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
548 final DictionaryInfo downloadable =
549 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
550 dictionaryInfo.uncompressedFilename);
551 return downloadable != null &&
552 downloadable.creationMillis > dictionaryInfo.creationMillis;
555 public DictionaryInfo getDownloadable(final String uncompressedFilename) {
556 return DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);