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.app.Application;
18 import android.content.Context;
19 import android.content.Intent;
20 import android.content.SharedPreferences;
21 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
22 import android.net.Uri;
23 import android.os.Build;
24 import android.os.Environment;
25 import android.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;
32 import android.view.View;
33 import android.widget.Button;
34 import android.widget.ImageButton;
35 import android.widget.ImageView.ScaleType;
36 import android.widget.LinearLayout;
37 import android.widget.Toast;
39 import com.hughes.android.dictionary.CollatorWrapper;
40 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
41 import com.hughes.android.dictionary.engine.Dictionary;
42 import com.hughes.android.dictionary.engine.Language;
43 import com.hughes.android.dictionary.engine.Language.LanguageResources;
44 import com.hughes.android.dictionary.engine.TransliteratorManager;
45 import com.hughes.android.util.PersistentObjectCache;
46 import com.hughes.util.ListUtil;
48 import java.io.BufferedReader;
50 import java.io.IOException;
51 import java.io.InputStreamReader;
52 import java.io.Serializable;
53 import java.util.ArrayList;
54 import java.util.Collections;
55 import java.util.Comparator;
56 import java.util.HashMap;
57 import java.util.List;
58 import java.util.Locale;
61 public enum DictionaryApplication {
64 private Context appContext;
66 static final String LOG = "QuickDicApp";
68 // If set to false, avoid use of ICU collator
69 // Works well enough for most european languages,
70 // gives faster startup and avoids crashes on some
71 // devices due to Dalvik bugs (e.g. ARMv6, S5570i, CM11)
73 // Leave it enabled by default for correctness except
74 // for my known broken development/performance test device config.
75 //static public final boolean USE_COLLATOR = !android.os.Build.FINGERPRINT.equals("Samsung/cm_tassve/tassve:4.4.4/KTU84Q/20150211:userdebug/release-keys");
76 static public final boolean USE_COLLATOR = true;
78 static public final TransliteratorManager.ThreadSetup threadBackground = new TransliteratorManager.ThreadSetup() {
80 public void onThreadStart() {
81 // THREAD_PRIORITY_BACKGROUND seemed like a good idea, but it
82 // can make Transliterator go from 20 seconds to 3 minutes (!)
83 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
87 // Static, determined by resources (and locale).
89 static Map<String, DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
92 DEFAULT(R.style.Theme_Default,
93 R.style.Theme_Default_TokenRow_Fg,
94 R.color.theme_default_token_row_fg,
95 R.drawable.theme_default_token_row_main_bg,
96 R.drawable.theme_default_token_row_other_bg,
97 R.drawable.theme_default_normal_row_bg),
99 LIGHT(R.style.Theme_Light,
100 R.style.Theme_Light_TokenRow_Fg,
101 R.color.theme_light_token_row_fg,
102 R.drawable.theme_light_token_row_main_bg,
103 R.drawable.theme_light_token_row_other_bg,
104 R.drawable.theme_light_normal_row_bg);
106 Theme(final int themeId, final int tokenRowFg,
107 final int tokenRowFgColor,
108 final int tokenRowMainBg, final int tokenRowOtherBg,
109 final int normalRowBg) {
110 this.themeId = themeId;
111 this.tokenRowFg = tokenRowFg;
112 this.tokenRowFgColor = tokenRowFgColor;
113 this.tokenRowMainBg = tokenRowMainBg;
114 this.tokenRowOtherBg = tokenRowOtherBg;
115 this.normalRowBg = normalRowBg;
119 final int tokenRowFg;
120 final int tokenRowFgColor;
121 final int tokenRowMainBg;
122 final int tokenRowOtherBg;
123 final int normalRowBg;
126 public static final class DictionaryConfig implements Serializable {
127 private static final long serialVersionUID = -1444177164708201263L;
128 // User-ordered list, persisted, just the ones that are/have been
130 final List<String> dictionaryFilesOrdered = new ArrayList<String>();
132 final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new HashMap<String, DictionaryInfo>();
135 * Sometimes a deserialized version of this data structure isn't valid.
139 return uncompressedFilenameToDictionaryInfo != null && dictionaryFilesOrdered != null;
143 DictionaryConfig dictionaryConfig = null;
145 public int languageButtonPixels = -1;
147 static synchronized void staticInit(final Context context) {
148 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
151 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new HashMap<String, DictionaryInfo>();
152 final BufferedReader reader = new BufferedReader(
153 new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
156 while ((line = reader.readLine()) != null) {
157 if (line.length() == 0 || line.charAt(0) == '#') {
160 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
161 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
162 dictionaryInfo.uncompressedFilename, dictionaryInfo);
164 } catch (IOException e) {
165 Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
169 } catch (IOException e) {}
172 private File dictDir;
174 public synchronized void init(Context c) {
175 if (appContext != null) {
176 assert c == appContext;
180 Log.d("QuickDic", "Application: onCreate");
181 TransliteratorManager.init(null, threadBackground);
182 staticInit(appContext);
184 languageButtonPixels = (int) TypedValue.applyDimension(
185 TypedValue.COMPLEX_UNIT_DIP, 60, appContext.getResources().getDisplayMetrics());
187 // Load the dictionaries we know about.
188 dictionaryConfig = PersistentObjectCache.init(appContext).read(
189 C.DICTIONARY_CONFIGS, DictionaryConfig.class);
190 if (dictionaryConfig == null) {
191 dictionaryConfig = new DictionaryConfig();
193 if (!dictionaryConfig.isValid()) {
194 dictionaryConfig = new DictionaryConfig();
198 appContext.setTheme(getSelectedTheme().themeId);
199 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
200 prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
202 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
204 Log.d("QuickDic", "prefs changed: " + key);
205 if (key.equals(appContext.getString(R.string.themeKey))) {
206 appContext.setTheme(getSelectedTheme().themeId);
212 public static void onCreateGlobalOptionsMenu(
213 final Context context, final Menu menu) {
214 final Context c = context.getApplicationContext();
216 final MenuItem preferences = menu.add(c.getString(R.string.settings));
217 MenuItemCompat.setShowAsAction(preferences, MenuItem.SHOW_AS_ACTION_NEVER);
218 preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
219 public boolean onMenuItemClick(final MenuItem menuItem) {
220 PreferenceActivity.prefsMightHaveChanged = true;
221 final Intent intent = new Intent(c, PreferenceActivity.class);
222 context.startActivity(intent);
227 final MenuItem help = menu.add(c.getString(R.string.help));
228 MenuItemCompat.setShowAsAction(help, MenuItem.SHOW_AS_ACTION_NEVER);
229 help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
230 public boolean onMenuItemClick(final MenuItem menuItem) {
231 context.startActivity(HtmlDisplayActivity.getHelpLaunchIntent(c));
236 final MenuItem reportIssue = menu.add(c.getString(R.string.reportIssue));
237 MenuItemCompat.setShowAsAction(reportIssue, MenuItem.SHOW_AS_ACTION_NEVER);
238 reportIssue.setOnMenuItemClickListener(new OnMenuItemClickListener() {
239 public boolean onMenuItemClick(final MenuItem menuItem) {
240 final Intent intent = new Intent(Intent.ACTION_VIEW);
242 .parse("https://github.com/rdoeffinger/Dictionary/issues"));
243 context.startActivity(intent);
248 final MenuItem about = menu.add(c.getString(R.string.about));
249 MenuItemCompat.setShowAsAction(about, MenuItem.SHOW_AS_ACTION_NEVER);
250 about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
251 public boolean onMenuItemClick(final MenuItem menuItem) {
252 final Intent intent = new Intent(c, AboutActivity.class);
253 context.startActivity(intent);
259 private String selectDefaultDir() {
260 final File defaultDictDir = new File(Environment.getExternalStorageDirectory(), "quickDic");
261 String dir = defaultDictDir.getAbsolutePath();
262 File dictDir = new File(dir);
263 String[] fileList = dictDir.isDirectory() ? dictDir.list() : null;
264 if (fileList != null && fileList.length > 0) {
269 efd = appContext.getExternalFilesDir(null);
270 } catch (Exception e) {
274 if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
275 appContext.getExternalFilesDirs(null);
277 if (efd.isDirectory() && efd.canWrite() && checkFileCreate(efd)) {
278 return efd.getAbsolutePath();
281 if (!dictDir.isDirectory() && !dictDir.mkdirs()) {
282 return appContext.getFilesDir().getAbsolutePath();
287 public synchronized File getDictDir() {
288 // This metaphor doesn't work, because we've already reset
289 // prefsMightHaveChanged.
290 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
291 String dir = prefs.getString(appContext.getString(R.string.quickdicDirectoryKey), "");
293 dir = selectDefaultDir();
295 dictDir = new File(dir);
297 if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
298 appContext.getExternalFilesDirs(null);
303 static public boolean checkFileCreate(File dir) {
305 File testfile = new File(dir, "quickdic_writetest");
308 res = testfile.createNewFile() & testfile.delete();
309 } catch (Exception e) {
314 public File getWordListFile() {
315 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
316 String file = prefs.getString(appContext.getString(R.string.wordListFileKey), "");
317 if (file.isEmpty()) {
318 return new File(getDictDir(), "wordList.txt");
320 return new File(file);
323 public Theme getSelectedTheme() {
324 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
325 final String theme = prefs.getString(appContext.getString(R.string.themeKey), "themeLight");
326 if (theme.equals("themeLight")) {
329 return Theme.DEFAULT;
333 public File getPath(String uncompressedFilename) {
334 return new File(getDictDir(), uncompressedFilename);
337 String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
338 String defaultLangName = null;
339 final Map<String, String> fileToNameCache = new HashMap<String, String>();
341 public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
342 // Hack to put the default locale first in the name.
343 if (indexInfos.size() > 1 &&
344 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
345 List<IndexInfo> result = new ArrayList<DictionaryInfo.IndexInfo>(indexInfos);
346 ListUtil.swap(result, 0, 1);
352 public synchronized String getDictionaryName(final String uncompressedFilename) {
353 final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
354 if (!currentLocale.equals(defaultLangISO2)) {
355 defaultLangISO2 = currentLocale;
356 fileToNameCache.clear();
357 defaultLangName = null;
359 if (defaultLangName == null) {
360 defaultLangName = IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, defaultLangISO2);
363 String name = fileToNameCache.get(uncompressedFilename);
368 final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
369 .get(uncompressedFilename);
370 if (dictionaryInfo != null) {
371 final StringBuilder nameBuilder = new StringBuilder();
373 List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
374 for (int i = 0; i < sortedIndexInfos.size(); ++i) {
376 nameBuilder.append("-");
379 .append(IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, sortedIndexInfos.get(i).shortName));
381 name = nameBuilder.toString();
383 name = uncompressedFilename.replace(".quickdic", "");
385 fileToNameCache.put(uncompressedFilename, name);
389 public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
390 dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
391 dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
392 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
395 public synchronized void sortDictionaries() {
396 Collections.sort(dictionaryConfig.dictionaryFilesOrdered, uncompressedFilenameComparator);
397 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
400 public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
401 while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
403 dictionaryConfig.uncompressedFilenameToDictionaryInfo
404 .remove(dictionaryInfo.uncompressedFilename);
405 getPath(dictionaryInfo.uncompressedFilename).delete();
406 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
409 final Comparator collator = USE_COLLATOR ? CollatorWrapper.getInstance() : String.CASE_INSENSITIVE_ORDER;
410 final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
412 public int compare(String uncompressedFilename1, String uncompressedFilename2) {
413 final String name1 = getDictionaryName(uncompressedFilename1);
414 final String name2 = getDictionaryName(uncompressedFilename2);
415 if (defaultLangName.length() > 0) {
416 if (name1.startsWith(defaultLangName + "-")
417 && !name2.startsWith(defaultLangName + "-")) {
419 } else if (name2.startsWith(defaultLangName + "-")
420 && !name1.startsWith(defaultLangName + "-")) {
424 return collator.compare(name1, name2);
427 final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
429 public int compare(DictionaryInfo d1, DictionaryInfo d2) {
430 // Single-index dictionaries first.
431 if (d1.indexInfos.size() != d2.indexInfos.size()) {
432 return d1.indexInfos.size() - d2.indexInfos.size();
434 return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
435 d2.uncompressedFilename);
439 public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
440 new Thread(new Runnable() {
443 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
444 synchronized (DictionaryApplication.this) {
445 oldDictionaryConfig.dictionaryFilesOrdered
446 .addAll(dictionaryConfig.dictionaryFilesOrdered);
448 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
449 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
450 final File dictFile = getPath(uncompressedFilename);
451 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
452 if (dictionaryInfo.isValid() || dictFile.exists()) {
453 newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
454 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
455 uncompressedFilename, dictionaryInfo);
459 // Are there dictionaries on the device that we didn't know
461 // Pick them up and put them at the end of the list.
462 final List<String> toAddSorted = new ArrayList<String>();
463 final File[] dictDirFiles = getDictDir().listFiles();
464 if (dictDirFiles != null) {
465 for (final File file : dictDirFiles) {
466 if (file.getName().endsWith(".zip")) {
467 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
468 .containsKey(file.getName().replace(".zip", ""))) {
472 if (!file.getName().endsWith(".quickdic")) {
475 if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
476 .containsKey(file.getName())) {
477 // We have it in our list already.
480 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
481 if (!dictionaryInfo.isValid()) {
482 Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
485 toAddSorted.add(file.getName());
486 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
487 file.getName(), dictionaryInfo);
490 Log.w(LOG, "dictDir is not a directory: " + getDictDir().getPath());
492 if (!toAddSorted.isEmpty()) {
493 Collections.sort(toAddSorted, uncompressedFilenameComparator);
494 newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
498 PersistentObjectCache.getInstance()
499 .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
500 } catch (Exception e) {
501 Log.e(LOG, "Failed persisting dictionary configs", e);
504 synchronized (DictionaryApplication.this) {
505 dictionaryConfig = newDictionaryConfig;
509 onUpdateFinished.run();
510 } catch (Exception e) {
511 Log.e(LOG, "Exception running callback.", e);
517 public boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
518 if (filters == null) {
521 for (final String filter : filters) {
522 if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
530 public synchronized List<DictionaryInfo> getDictionariesOnDevice(String[] filters) {
531 final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
532 dictionaryConfig.dictionaryFilesOrdered.size());
533 for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
534 final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo
535 .get(uncompressedFilename);
536 if (dictionaryInfo != null && matchesFilters(dictionaryInfo, filters)) {
537 result.add(dictionaryInfo);
543 public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
544 final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
545 dictionaryConfig.dictionaryFilesOrdered.size());
547 final Map<String, DictionaryInfo> remaining = new HashMap<String, DictionaryInfo>(
548 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
549 remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
550 for (final DictionaryInfo dictionaryInfo : remaining.values()) {
551 if (matchesFilters(dictionaryInfo, filters)) {
552 result.add(dictionaryInfo);
555 Collections.sort(result, dictionaryInfoComparator);
559 public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
560 return dictionaryConfig.uncompressedFilenameToDictionaryInfo.get(uncompressedFilename) != null;
563 public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
564 final DictionaryInfo downloadable =
565 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
566 dictionaryInfo.uncompressedFilename);
567 return downloadable != null &&
568 downloadable.creationMillis > dictionaryInfo.creationMillis;
571 public DictionaryInfo getDownloadable(final String uncompressedFilename) {
572 final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
573 .get(uncompressedFilename);