]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryApplication.java
Switch to app compat preferences.
[Dictionary.git] / src / com / hughes / android / dictionary / DictionaryApplication.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
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
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 package com.hughes.android.dictionary;
16
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.support.v7.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;
31
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;
37
38 import java.io.BufferedReader;
39 import java.io.File;
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;
49 import java.util.Map;
50
51 public enum DictionaryApplication {
52     INSTANCE;
53
54     private Context appContext;
55
56     static final String LOG = "QuickDicApp";
57
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)
62     // when using ICU4J.
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;
67
68     public static final TransliteratorManager.ThreadSetup threadBackground = new TransliteratorManager.ThreadSetup() {
69         @Override
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);
74         }
75     };
76
77     // Static, determined by resources (and locale).
78     // Unordered.
79     static Map<String, DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
80
81     enum Theme {
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),
88
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);
95
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;
106         }
107
108         final int themeId;
109         final int tokenRowFg;
110         final int tokenRowFgColor;
111         final int tokenRowMainBg;
112         final int tokenRowOtherBg;
113         final int normalRowBg;
114     }
115
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
119         // present.
120         final List<String> dictionaryFilesOrdered = new ArrayList<>();
121
122         final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new HashMap<>();
123
124         /**
125          * Sometimes a deserialized version of this data structure isn't valid.
126          */
127         @SuppressWarnings("ConstantConditions")
128         boolean isValid() {
129             return uncompressedFilenameToDictionaryInfo != null && dictionaryFilesOrdered != null;
130         }
131     }
132
133     DictionaryConfig dictionaryConfig = null;
134
135     public int languageButtonPixels = -1;
136
137     static synchronized void staticInit(final Context context) {
138         if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
139             return;
140         }
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)));
144         try {
145             String line;
146             while ((line = reader.readLine()) != null) {
147                 if (line.length() == 0 || line.charAt(0) == '#') {
148                     continue;
149                 }
150                 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
151                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
152                     dictionaryInfo.uncompressedFilename, dictionaryInfo);
153             }
154         } catch (IOException e) {
155             Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
156         }
157         try {
158             reader.close();
159         } catch (IOException ignored) {}
160     }
161
162     public synchronized void init(Context c) {
163         if (appContext != null) {
164             assert c == appContext;
165             return;
166         }
167         appContext = c;
168         Log.d("QuickDic", "Application: onCreate");
169         TransliteratorManager.init(null, threadBackground);
170         staticInit(appContext);
171
172         languageButtonPixels = (int) TypedValue.applyDimension(
173                                    TypedValue.COMPLEX_UNIT_DIP, 60, appContext.getResources().getDisplayMetrics());
174
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();
180         }
181         if (!dictionaryConfig.isValid()) {
182             dictionaryConfig = new DictionaryConfig();
183         }
184
185         // Theme stuff.
186         appContext.setTheme(getSelectedTheme().themeId);
187         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
188         prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
189             @Override
190             public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
191                                                   String key) {
192                 Log.d("QuickDic", "prefs changed: " + key);
193                 if (key.equals(appContext.getString(R.string.themeKey))) {
194                     appContext.setTheme(getSelectedTheme().themeId);
195                 }
196             }
197         });
198     }
199
200     public static void onCreateGlobalOptionsMenu(
201         final Context context, final Menu menu) {
202         final Context c = context.getApplicationContext();
203
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);
211                 return false;
212             }
213         });
214
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));
220                 return false;
221             }
222         });
223
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);
229                 intent.setData(Uri
230                                .parse("https://github.com/rdoeffinger/Dictionary/issues"));
231                 context.startActivity(intent);
232                 return false;
233             }
234         });
235
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);
242                 return false;
243             }
244         });
245     }
246
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) {
253             return dir;
254         }
255         File efd = null;
256         try {
257             efd = appContext.getExternalFilesDir(null);
258         } catch (Exception ignored) {
259         }
260         if (efd != null) {
261             efd.mkdirs();
262             if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
263                 appContext.getExternalFilesDirs(null);
264             }
265             if (efd.isDirectory() && efd.canWrite() && checkFileCreate(efd)) {
266                 return efd.getAbsolutePath();
267             }
268         }
269         if (!dictDir.isDirectory() && !dictDir.mkdirs()) {
270             return appContext.getFilesDir().getAbsolutePath();
271         }
272         return dir;
273     }
274
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), "");
280         if (dir.isEmpty()) {
281             dir = selectDefaultDir();
282         }
283         File dictDir = new File(dir);
284         dictDir.mkdirs();
285         if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
286             appContext.getExternalFilesDirs(null);
287         }
288         return dictDir;
289     }
290
291     public static boolean checkFileCreate(File dir) {
292         boolean res = false;
293         File testfile = new File(dir, "quickdic_writetest");
294         try {
295             testfile.delete();
296             res = testfile.createNewFile() & testfile.delete();
297         } catch (Exception ignored) {
298         }
299         return res;
300     }
301
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");
307         }
308         return new File(file);
309     }
310
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")) {
315             return Theme.LIGHT;
316         } else {
317             return Theme.DEFAULT;
318         }
319     }
320
321     public File getPath(String uncompressedFilename) {
322         return new File(getDictDir(), uncompressedFilename);
323     }
324
325     String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
326     String defaultLangName = null;
327     final Map<String, String> fileToNameCache = new HashMap<>();
328
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);
335             return result;
336         }
337         return indexInfos;
338     }
339
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;
346         }
347         if (defaultLangName == null) {
348             defaultLangName = IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, defaultLangISO2);
349         }
350
351         String name = fileToNameCache.get(uncompressedFilename);
352         if (name != null) {
353             return name;
354         }
355
356         final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
357                                               .get(uncompressedFilename);
358         if (dictionaryInfo != null) {
359             final StringBuilder nameBuilder = new StringBuilder();
360
361             List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
362             for (int i = 0; i < sortedIndexInfos.size(); ++i) {
363                 if (i > 0) {
364                     nameBuilder.append("-");
365                 }
366                 nameBuilder
367                 .append(IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, sortedIndexInfos.get(i).shortName));
368             }
369             name = nameBuilder.toString();
370         } else {
371             name = uncompressedFilename.replace(".quickdic", "");
372         }
373         fileToNameCache.put(uncompressedFilename, name);
374         return name;
375     }
376
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);
381     }
382
383     public synchronized void sortDictionaries() {
384         Collections.sort(dictionaryConfig.dictionaryFilesOrdered, uncompressedFilenameComparator);
385         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
386     }
387
388     public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
389         while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
390         }
391         dictionaryConfig.uncompressedFilenameToDictionaryInfo
392         .remove(dictionaryInfo.uncompressedFilename);
393         getPath(dictionaryInfo.uncompressedFilename).delete();
394         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
395     }
396
397     final Comparator<Object> collator = USE_COLLATOR ? CollatorWrapper.getInstance() : null;
398     final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
399         @Override
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 + "-")) {
406                     return -1;
407                 } else if (name2.startsWith(defaultLangName + "-")
408                         && !name1.startsWith(defaultLangName + "-")) {
409                     return 1;
410                 }
411             }
412             return collator != null ? collator.compare(name1, name2) : name1.compareToIgnoreCase(name2);
413         }
414     };
415     final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
416         @Override
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();
421             }
422             return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
423                     d2.uncompressedFilename);
424         }
425     };
426
427     public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
428         new Thread(new Runnable() {
429             @Override
430             public void run() {
431                 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
432                 synchronized (DictionaryApplication.this) {
433                     oldDictionaryConfig.dictionaryFilesOrdered
434                     .addAll(dictionaryConfig.dictionaryFilesOrdered);
435                 }
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);
444                     }
445                 }
446
447                 // Are there dictionaries on the device that we didn't know
448                 // about already?
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", ""))) {
457                                 file.delete();
458                             }
459                         }
460                         if (!file.getName().endsWith(".quickdic")) {
461                             continue;
462                         }
463                         if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
464                                 .containsKey(file.getName())) {
465                             // We have it in our list already.
466                             continue;
467                         }
468                         final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
469                         if (!dictionaryInfo.isValid()) {
470                             Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
471                         }
472
473                         toAddSorted.add(file.getName());
474                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
475                             file.getName(), dictionaryInfo);
476                     }
477                 } else {
478                     Log.w(LOG, "dictDir is not a directory: " + getDictDir().getPath());
479                 }
480                 if (!toAddSorted.isEmpty()) {
481                     Collections.sort(toAddSorted, uncompressedFilenameComparator);
482                     newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
483                 }
484
485                 try {
486                     PersistentObjectCache.getInstance()
487                     .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
488                 } catch (Exception e) {
489                     Log.e(LOG, "Failed persisting dictionary configs", e);
490                 }
491
492                 synchronized (DictionaryApplication.this) {
493                     dictionaryConfig = newDictionaryConfig;
494                 }
495
496                 try {
497                     onUpdateFinished.run();
498                 } catch (Exception e) {
499                     Log.e(LOG, "Exception running callback.", e);
500                 }
501             }
502         }).start();
503     }
504
505     private boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
506         if (filters == null) {
507             return true;
508         }
509         for (final String filter : filters) {
510             if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
511                         filter)) {
512                 return false;
513             }
514         }
515         return true;
516     }
517
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);
526             }
527         }
528         return result;
529     }
530
531     public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
532         final List<DictionaryInfo> result = new ArrayList<>(
533                 dictionaryConfig.dictionaryFilesOrdered.size());
534
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);
541             }
542         }
543         Collections.sort(result, dictionaryInfoComparator);
544         return result;
545     }
546
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;
553     }
554
555     public DictionaryInfo getDownloadable(final String uncompressedFilename) {
556         return DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);
557     }
558
559 }