]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryApplication.java
Add "system theme" to theme options
[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.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;
32
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;
38
39 import java.io.BufferedReader;
40 import java.io.File;
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;
50 import java.util.Map;
51
52 public enum DictionaryApplication {
53     INSTANCE;
54
55     private Context appContext;
56
57     static final String LOG = "QuickDicApp";
58
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)
63     // when using ICU4J.
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;
68
69     public static final TransliteratorManager.ThreadSetup threadBackground = new TransliteratorManager.ThreadSetup() {
70         @Override
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);
75         }
76     };
77
78     // Static, determined by resources (and locale).
79     // Unordered.
80     static Map<String, DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
81
82     enum Theme {
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),
89
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);
96
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;
107         }
108
109         final int themeId;
110         final int tokenRowFg;
111         final int tokenRowFgColor;
112         final int tokenRowMainBg;
113         final int tokenRowOtherBg;
114         final int normalRowBg;
115     }
116
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
120         // present.
121         final List<String> dictionaryFilesOrdered = new ArrayList<>();
122
123         final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new HashMap<>();
124
125         /**
126          * Sometimes a deserialized version of this data structure isn't valid.
127          */
128         @SuppressWarnings("ConstantConditions")
129         boolean isValid() {
130             return uncompressedFilenameToDictionaryInfo != null && dictionaryFilesOrdered != null;
131         }
132     }
133
134     DictionaryConfig dictionaryConfig = null;
135
136     public int languageButtonPixels = -1;
137
138     static synchronized void staticInit(final Context context) {
139         if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
140             return;
141         }
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)));
145         try {
146             String line;
147             while ((line = reader.readLine()) != null) {
148                 if (line.length() == 0 || line.charAt(0) == '#') {
149                     continue;
150                 }
151                 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
152                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
153                     dictionaryInfo.uncompressedFilename, dictionaryInfo);
154             }
155         } catch (IOException e) {
156             Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
157         }
158         try {
159             reader.close();
160         } catch (IOException ignored) {}
161     }
162
163     public synchronized void init(Context c) {
164         if (appContext != null) {
165             assert c == appContext;
166             return;
167         }
168         appContext = c;
169         Log.d("QuickDic", "Application: onCreate");
170         TransliteratorManager.init(null, threadBackground);
171         staticInit(appContext);
172
173         languageButtonPixels = (int) TypedValue.applyDimension(
174                                    TypedValue.COMPLEX_UNIT_DIP, 60, appContext.getResources().getDisplayMetrics());
175
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();
181         }
182         if (!dictionaryConfig.isValid()) {
183             dictionaryConfig = new DictionaryConfig();
184         }
185
186         // Theme stuff.
187         appContext.setTheme(getSelectedTheme().themeId);
188         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
189         prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
190             @Override
191             public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
192                                                   String key) {
193                 Log.d("QuickDic", "prefs changed: " + key);
194                 if (key.equals(appContext.getString(R.string.themeKey))) {
195                     appContext.setTheme(getSelectedTheme().themeId);
196                 }
197             }
198         });
199     }
200
201     public static void onCreateGlobalOptionsMenu(
202         final Context context, final Menu menu) {
203         final Context c = context.getApplicationContext();
204
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);
212                 return false;
213             }
214         });
215
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));
221                 return false;
222             }
223         });
224
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);
230                 intent.setData(Uri
231                                .parse("https://github.com/rdoeffinger/Dictionary/issues"));
232                 context.startActivity(intent);
233                 return false;
234             }
235         });
236
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);
243                 return false;
244             }
245         });
246     }
247
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) {
254             return dir;
255         }
256         File efd = null;
257         try {
258             efd = appContext.getExternalFilesDir(null);
259         } catch (Exception ignored) {
260         }
261         if (efd != null) {
262             efd.mkdirs();
263             if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
264                 appContext.getExternalFilesDirs(null);
265             }
266             if (efd.isDirectory() && efd.canWrite() && checkFileCreate(efd)) {
267                 return efd.getAbsolutePath();
268             }
269         }
270         if (!dictDir.isDirectory() && !dictDir.mkdirs()) {
271             return appContext.getFilesDir().getAbsolutePath();
272         }
273         return dir;
274     }
275
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), "");
281         if (dir.isEmpty()) {
282             dir = selectDefaultDir();
283         }
284         File dictDir = new File(dir);
285         dictDir.mkdirs();
286         if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
287             appContext.getExternalFilesDirs(null);
288         }
289         return dictDir;
290     }
291
292     public static boolean checkFileCreate(File dir) {
293         boolean res = false;
294         File testfile = new File(dir, "quickdic_writetest");
295         try {
296             testfile.delete();
297             res = testfile.createNewFile() & testfile.delete();
298         } catch (Exception ignored) {
299         }
300         return res;
301     }
302
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");
308         }
309         return new File(file);
310     }
311
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")) {
316             return Theme.LIGHT;
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) ?
321                     Theme.DEFAULT :
322                     Theme.LIGHT);
323         } else {
324             return Theme.DEFAULT;
325         }
326     }
327
328     public File getPath(String uncompressedFilename) {
329         return new File(getDictDir(), uncompressedFilename);
330     }
331
332     String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
333     String defaultLangName = null;
334     final Map<String, String> fileToNameCache = new HashMap<>();
335
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);
342             return result;
343         }
344         return indexInfos;
345     }
346
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;
353         }
354         if (defaultLangName == null) {
355             defaultLangName = IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, defaultLangISO2);
356         }
357
358         String name = fileToNameCache.get(uncompressedFilename);
359         if (name != null) {
360             return name;
361         }
362
363         final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
364                                               .get(uncompressedFilename);
365         if (dictionaryInfo != null) {
366             final StringBuilder nameBuilder = new StringBuilder();
367
368             List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
369             for (int i = 0; i < sortedIndexInfos.size(); ++i) {
370                 if (i > 0) {
371                     nameBuilder.append("-");
372                 }
373                 nameBuilder
374                 .append(IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, sortedIndexInfos.get(i).shortName));
375             }
376             name = nameBuilder.toString();
377         } else {
378             name = uncompressedFilename.replace(".quickdic", "");
379         }
380         fileToNameCache.put(uncompressedFilename, name);
381         return name;
382     }
383
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);
388     }
389
390     public synchronized void sortDictionaries() {
391         Collections.sort(dictionaryConfig.dictionaryFilesOrdered, uncompressedFilenameComparator);
392         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
393     }
394
395     public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
396         while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
397         }
398         dictionaryConfig.uncompressedFilenameToDictionaryInfo
399         .remove(dictionaryInfo.uncompressedFilename);
400         getPath(dictionaryInfo.uncompressedFilename).delete();
401         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
402     }
403
404     final Comparator<Object> collator = USE_COLLATOR ? CollatorWrapper.getInstance() : null;
405     final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
406         @Override
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 + "-")) {
413                     return -1;
414                 } else if (name2.startsWith(defaultLangName + "-")
415                         && !name1.startsWith(defaultLangName + "-")) {
416                     return 1;
417                 }
418             }
419             return collator != null ? collator.compare(name1, name2) : name1.compareToIgnoreCase(name2);
420         }
421     };
422     final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
423         @Override
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();
428             }
429             return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
430                     d2.uncompressedFilename);
431         }
432     };
433
434     public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
435         new Thread(new Runnable() {
436             @Override
437             public void run() {
438                 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
439                 synchronized (DictionaryApplication.this) {
440                     oldDictionaryConfig.dictionaryFilesOrdered
441                     .addAll(dictionaryConfig.dictionaryFilesOrdered);
442                 }
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);
451                     }
452                 }
453
454                 // Are there dictionaries on the device that we didn't know
455                 // about already?
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", ""))) {
464                                 file.delete();
465                             }
466                         }
467                         if (!file.getName().endsWith(".quickdic")) {
468                             continue;
469                         }
470                         if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
471                                 .containsKey(file.getName())) {
472                             // We have it in our list already.
473                             continue;
474                         }
475                         final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
476                         if (!dictionaryInfo.isValid()) {
477                             Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
478                         }
479
480                         toAddSorted.add(file.getName());
481                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
482                             file.getName(), dictionaryInfo);
483                     }
484                 } else {
485                     Log.w(LOG, "dictDir is not a directory: " + getDictDir().getPath());
486                 }
487                 if (!toAddSorted.isEmpty()) {
488                     Collections.sort(toAddSorted, uncompressedFilenameComparator);
489                     newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
490                 }
491
492                 try {
493                     PersistentObjectCache.getInstance()
494                     .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
495                 } catch (Exception e) {
496                     Log.e(LOG, "Failed persisting dictionary configs", e);
497                 }
498
499                 synchronized (DictionaryApplication.this) {
500                     dictionaryConfig = newDictionaryConfig;
501                 }
502
503                 try {
504                     onUpdateFinished.run();
505                 } catch (Exception e) {
506                     Log.e(LOG, "Exception running callback.", e);
507                 }
508             }
509         }).start();
510     }
511
512     private boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
513         if (filters == null) {
514             return true;
515         }
516         for (final String filter : filters) {
517             if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
518                         filter)) {
519                 return false;
520             }
521         }
522         return true;
523     }
524
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);
533             }
534         }
535         return result;
536     }
537
538     public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
539         final List<DictionaryInfo> result = new ArrayList<>(
540                 dictionaryConfig.dictionaryFilesOrdered.size());
541
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);
548             }
549         }
550         Collections.sort(result, dictionaryInfoComparator);
551         return result;
552     }
553
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;
560     }
561
562     public DictionaryInfo getDownloadable(final String uncompressedFilename) {
563         return DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);
564     }
565
566 }