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.DictionaryInfo.IndexInfo;
40 import com.hughes.android.dictionary.engine.Dictionary;
41 import com.hughes.android.dictionary.engine.Language;
42 import com.hughes.android.dictionary.engine.Language.LanguageResources;
43 import com.hughes.android.dictionary.engine.TransliteratorManager;
44 import com.hughes.android.util.PersistentObjectCache;
45 import com.hughes.util.ListUtil;
46 import java.text.Collator;
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 class DictionaryApplication extends Application {
63 static final String LOG = "QuickDicApp";
65 // If set to false, avoid use of ICU collator
66 // Works well enough for most european languages,
67 // gives faster startup and avoids crashes on some
68 // devices due to Dalvik bugs (e.g. ARMv6, S5570i, CM11)
70 // Leave it enabled by default for correctness except
71 // for my known broken development/performance test device config.
72 //static public final boolean USE_COLLATOR = !android.os.Build.FINGERPRINT.equals("Samsung/cm_tassve/tassve:4.4.4/KTU84Q/20150211:userdebug/release-keys");
73 static public final boolean USE_COLLATOR = true;
75 static public final TransliteratorManager.ThreadSetup threadBackground = new TransliteratorManager.ThreadSetup() {
77 public void onThreadStart() {
78 // THREAD_PRIORITY_BACKGROUND seemed like a good idea, but it
79 // can make Transliterator go from 20 seconds to 3 minutes (!)
80 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
84 // Static, determined by resources (and locale).
86 static Map<String, DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
89 DEFAULT(R.style.Theme_Default,
90 R.style.Theme_Default_TokenRow_Fg,
91 R.color.theme_default_token_row_fg,
92 R.drawable.theme_default_token_row_main_bg,
93 R.drawable.theme_default_token_row_other_bg,
94 R.drawable.theme_default_normal_row_bg),
96 LIGHT(R.style.Theme_Light,
97 R.style.Theme_Light_TokenRow_Fg,
98 R.color.theme_light_token_row_fg,
99 R.drawable.theme_light_token_row_main_bg,
100 R.drawable.theme_light_token_row_other_bg,
101 R.drawable.theme_light_normal_row_bg);
103 Theme(final int themeId, final int tokenRowFg,
104 final int tokenRowFgColor,
105 final int tokenRowMainBg, final int tokenRowOtherBg,
106 final int normalRowBg) {
107 this.themeId = themeId;
108 this.tokenRowFg = tokenRowFg;
109 this.tokenRowFgColor = tokenRowFgColor;
110 this.tokenRowMainBg = tokenRowMainBg;
111 this.tokenRowOtherBg = tokenRowOtherBg;
112 this.normalRowBg = normalRowBg;
116 final int tokenRowFg;
117 final int tokenRowFgColor;
118 final int tokenRowMainBg;
119 final int tokenRowOtherBg;
120 final int normalRowBg;
123 public static final class DictionaryConfig implements Serializable {
124 private static final long serialVersionUID = -1444177164708201263L;
125 // User-ordered list, persisted, just the ones that are/have been
127 final List<String> dictionaryFilesOrdered = new ArrayList<String>();
129 final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new HashMap<String, DictionaryInfo>();
132 * Sometimes a deserialized version of this data structure isn't valid.
136 return uncompressedFilenameToDictionaryInfo != null && dictionaryFilesOrdered != null;
140 DictionaryConfig dictionaryConfig = null;
142 public int languageButtonPixels = -1;
144 static synchronized void staticInit(final Context context) {
145 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
148 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new HashMap<String, DictionaryInfo>();
149 final BufferedReader reader = new BufferedReader(
150 new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
153 while ((line = reader.readLine()) != null) {
154 if (line.length() == 0 || line.charAt(0) == '#') {
157 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
158 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
159 dictionaryInfo.uncompressedFilename, dictionaryInfo);
161 } catch (IOException e) {
162 Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
166 } catch (IOException e) {}
169 private File dictDir;
172 public void onCreate() {
174 Log.d("QuickDic", "Application: onCreate");
175 TransliteratorManager.init(null, threadBackground);
176 staticInit(getApplicationContext());
178 languageButtonPixels = (int) TypedValue.applyDimension(
179 TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics());
181 // Load the dictionaries we know about.
182 dictionaryConfig = PersistentObjectCache.init(getApplicationContext()).read(
183 C.DICTIONARY_CONFIGS, DictionaryConfig.class);
184 if (dictionaryConfig == null) {
185 dictionaryConfig = new DictionaryConfig();
187 if (!dictionaryConfig.isValid()) {
188 dictionaryConfig = new DictionaryConfig();
192 setTheme(getSelectedTheme().themeId);
193 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
194 prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
196 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
198 Log.d("QuickDic", "prefs changed: " + key);
199 if (key.equals(getString(R.string.themeKey))) {
200 setTheme(getSelectedTheme().themeId);
206 public void onCreateGlobalOptionsMenu(
207 final Context context, final Menu menu) {
208 final MenuItem about = menu.add(getString(R.string.about));
209 MenuItemCompat.setShowAsAction(about, MenuItem.SHOW_AS_ACTION_NEVER);
210 about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
211 public boolean onMenuItemClick(final MenuItem menuItem) {
212 final Intent intent = new Intent(getApplicationContext(), AboutActivity.class);
213 context.startActivity(intent);
218 final MenuItem help = menu.add(getString(R.string.help));
219 MenuItemCompat.setShowAsAction(help, MenuItem.SHOW_AS_ACTION_NEVER);
220 help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
221 public boolean onMenuItemClick(final MenuItem menuItem) {
222 context.startActivity(HtmlDisplayActivity.getHelpLaunchIntent(getApplicationContext()));
227 final MenuItem preferences = menu.add(getString(R.string.settings));
228 MenuItemCompat.setShowAsAction(preferences, MenuItem.SHOW_AS_ACTION_NEVER);
229 preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
230 public boolean onMenuItemClick(final MenuItem menuItem) {
231 PreferenceActivity.prefsMightHaveChanged = true;
232 final Intent intent = new Intent(getApplicationContext(), PreferenceActivity.class);
233 context.startActivity(intent);
238 final MenuItem reportIssue = menu.add(getString(R.string.reportIssue));
239 MenuItemCompat.setShowAsAction(reportIssue, MenuItem.SHOW_AS_ACTION_NEVER);
240 reportIssue.setOnMenuItemClickListener(new OnMenuItemClickListener() {
241 public boolean onMenuItemClick(final MenuItem menuItem) {
242 final Intent intent = new Intent(Intent.ACTION_VIEW);
244 .parse("http://github.com/rdoeffinger/Dictionary/issues"));
245 context.startActivity(intent);
251 private String selectDefaultDir() {
252 final File defaultDictDir = new File(Environment.getExternalStorageDirectory(), "quickDic");
253 String dir = defaultDictDir.getAbsolutePath();
254 File dictDir = new File(dir);
255 String[] fileList = dictDir.isDirectory() ? dictDir.list() : null;
256 if (fileList != null && fileList.length > 0) {
261 efd = getApplicationContext().getExternalFilesDir(null);
262 } catch (Exception e) {
266 if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
267 getApplicationContext().getExternalFilesDirs(null);
269 if (efd.isDirectory() && efd.canWrite() && checkFileCreate(efd)) {
270 return efd.getAbsolutePath();
273 if (!dictDir.isDirectory() && !dictDir.mkdirs()) {
274 return getApplicationContext().getFilesDir().getAbsolutePath();
279 public synchronized File getDictDir() {
280 // This metaphor doesn't work, because we've already reset
281 // prefsMightHaveChanged.
282 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
283 String dir = prefs.getString(getString(R.string.quickdicDirectoryKey), "");
285 dir = selectDefaultDir();
287 dictDir = new File(dir);
289 if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
290 getApplicationContext().getExternalFilesDirs(null);
295 static public boolean checkFileCreate(File dir) {
297 File testfile = new File(dir, "quickdic_writetest");
300 res = testfile.createNewFile() & testfile.delete();
301 } catch (Exception e) {
306 public File getWordListFile() {
307 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
308 String file = prefs.getString(getString(R.string.wordListFileKey), "");
309 if (file.isEmpty()) {
310 return new File(getDictDir(), "wordList.txt");
312 return new File(file);
315 public Theme getSelectedTheme() {
316 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
317 final String theme = prefs.getString(getString(R.string.themeKey), "themeLight");
318 if (theme.equals("themeLight")) {
321 return Theme.DEFAULT;
325 public File getPath(String uncompressedFilename) {
326 return new File(getDictDir(), uncompressedFilename);
329 String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
330 String defaultLangName = null;
331 final Map<String, String> fileToNameCache = new HashMap<String, String>();
333 public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
334 // Hack to put the default locale first in the name.
335 if (indexInfos.size() > 1 &&
336 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
337 List<IndexInfo> result = new ArrayList<DictionaryInfo.IndexInfo>(indexInfos);
338 ListUtil.swap(result, 0, 1);
344 public synchronized String getDictionaryName(final String uncompressedFilename) {
345 final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
346 if (!currentLocale.equals(defaultLangISO2)) {
347 defaultLangISO2 = currentLocale;
348 fileToNameCache.clear();
349 defaultLangName = null;
351 if (defaultLangName == null) {
352 defaultLangName = IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(getApplicationContext(), defaultLangISO2);
355 String name = fileToNameCache.get(uncompressedFilename);
360 final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
361 .get(uncompressedFilename);
362 if (dictionaryInfo != null) {
363 final StringBuilder nameBuilder = new StringBuilder();
365 List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
366 for (int i = 0; i < sortedIndexInfos.size(); ++i) {
368 nameBuilder.append("-");
371 .append(IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(getApplicationContext(), sortedIndexInfos.get(i).shortName));
373 name = nameBuilder.toString();
375 name = uncompressedFilename.replace(".quickdic", "");
377 fileToNameCache.put(uncompressedFilename, name);
381 public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
382 dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
383 dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
384 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
387 public synchronized void sortDictionaries() {
388 Collections.sort(dictionaryConfig.dictionaryFilesOrdered, uncompressedFilenameComparator);
389 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
392 public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
393 while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
395 dictionaryConfig.uncompressedFilenameToDictionaryInfo
396 .remove(dictionaryInfo.uncompressedFilename);
397 getPath(dictionaryInfo.uncompressedFilename).delete();
398 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
401 final Comparator collator = USE_COLLATOR ? Collator.getInstance() : String.CASE_INSENSITIVE_ORDER;
402 final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
404 public int compare(String uncompressedFilename1, String uncompressedFilename2) {
405 final String name1 = getDictionaryName(uncompressedFilename1);
406 final String name2 = getDictionaryName(uncompressedFilename2);
407 if (defaultLangName.length() > 0) {
408 if (name1.startsWith(defaultLangName + "-")
409 && !name2.startsWith(defaultLangName + "-")) {
411 } else if (name2.startsWith(defaultLangName + "-")
412 && !name1.startsWith(defaultLangName + "-")) {
416 return collator.compare(name1, name2);
419 final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
421 public int compare(DictionaryInfo d1, DictionaryInfo d2) {
422 // Single-index dictionaries first.
423 if (d1.indexInfos.size() != d2.indexInfos.size()) {
424 return d1.indexInfos.size() - d2.indexInfos.size();
426 return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
427 d2.uncompressedFilename);
431 public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
432 new Thread(new Runnable() {
435 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
436 synchronized (DictionaryApplication.this) {
437 oldDictionaryConfig.dictionaryFilesOrdered
438 .addAll(dictionaryConfig.dictionaryFilesOrdered);
440 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
441 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
442 final File dictFile = getPath(uncompressedFilename);
443 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
444 if (dictionaryInfo.isValid() || dictFile.exists()) {
445 newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
446 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
447 uncompressedFilename, dictionaryInfo);
451 // Are there dictionaries on the device that we didn't know
453 // Pick them up and put them at the end of the list.
454 final List<String> toAddSorted = new ArrayList<String>();
455 final File[] dictDirFiles = getDictDir().listFiles();
456 if (dictDirFiles != null) {
457 for (final File file : dictDirFiles) {
458 if (file.getName().endsWith(".zip")) {
459 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
460 .containsKey(file.getName().replace(".zip", ""))) {
464 if (!file.getName().endsWith(".quickdic")) {
467 if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
468 .containsKey(file.getName())) {
469 // We have it in our list already.
472 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
473 if (!dictionaryInfo.isValid()) {
474 Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
477 toAddSorted.add(file.getName());
478 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
479 file.getName(), dictionaryInfo);
482 Log.w(LOG, "dictDir is not a directory: " + getDictDir().getPath());
484 if (!toAddSorted.isEmpty()) {
485 Collections.sort(toAddSorted, uncompressedFilenameComparator);
486 newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
490 PersistentObjectCache.getInstance()
491 .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
492 } catch (Exception e) {
493 Log.e(LOG, "Failed persisting dictionary configs", e);
496 synchronized (DictionaryApplication.this) {
497 dictionaryConfig = newDictionaryConfig;
501 onUpdateFinished.run();
502 } catch (Exception e) {
503 Log.e(LOG, "Exception running callback.", e);
509 public boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
510 if (filters == null) {
513 for (final String filter : filters) {
514 if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
522 public synchronized List<DictionaryInfo> getDictionariesOnDevice(String[] filters) {
523 final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
524 dictionaryConfig.dictionaryFilesOrdered.size());
525 for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
526 final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo
527 .get(uncompressedFilename);
528 if (dictionaryInfo != null && matchesFilters(dictionaryInfo, filters)) {
529 result.add(dictionaryInfo);
535 public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
536 final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
537 dictionaryConfig.dictionaryFilesOrdered.size());
539 final Map<String, DictionaryInfo> remaining = new HashMap<String, DictionaryInfo>(
540 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
541 remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
542 for (final DictionaryInfo dictionaryInfo : remaining.values()) {
543 if (matchesFilters(dictionaryInfo, filters)) {
544 result.add(dictionaryInfo);
547 Collections.sort(result, dictionaryInfoComparator);
551 public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
552 return dictionaryConfig.uncompressedFilenameToDictionaryInfo.get(uncompressedFilename) != null;
555 public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
556 final DictionaryInfo downloadable =
557 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
558 dictionaryInfo.uncompressedFilename);
559 return downloadable != null &&
560 downloadable.creationMillis > dictionaryInfo.creationMillis;
563 public DictionaryInfo getDownloadable(final String uncompressedFilename) {
564 final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
565 .get(uncompressedFilename);