]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryApplication.java
c17c7ef82975e407f707d4da0cf8e67963edb2da
[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.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.CollatorWrapper;
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     static public final boolean USE_COLLATOR = true;
68
69     static public 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     static public 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 {
318             return Theme.DEFAULT;
319         }
320     }
321
322     public File getPath(String uncompressedFilename) {
323         return new File(getDictDir(), uncompressedFilename);
324     }
325
326     String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
327     String defaultLangName = null;
328     final Map<String, String> fileToNameCache = new HashMap<>();
329
330     public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
331         // Hack to put the default locale first in the name.
332         if (indexInfos.size() > 1 &&
333                 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
334             List<IndexInfo> result = new ArrayList<>(indexInfos);
335             ListUtil.swap(result, 0, 1);
336             return result;
337         }
338         return indexInfos;
339     }
340
341     public synchronized String getDictionaryName(final String uncompressedFilename) {
342         final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
343         if (!currentLocale.equals(defaultLangISO2)) {
344             defaultLangISO2 = currentLocale;
345             fileToNameCache.clear();
346             defaultLangName = null;
347         }
348         if (defaultLangName == null) {
349             defaultLangName = IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, defaultLangISO2);
350         }
351
352         String name = fileToNameCache.get(uncompressedFilename);
353         if (name != null) {
354             return name;
355         }
356
357         final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
358                                               .get(uncompressedFilename);
359         if (dictionaryInfo != null) {
360             final StringBuilder nameBuilder = new StringBuilder();
361
362             List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
363             for (int i = 0; i < sortedIndexInfos.size(); ++i) {
364                 if (i > 0) {
365                     nameBuilder.append("-");
366                 }
367                 nameBuilder
368                 .append(IsoUtils.INSTANCE.isoCodeToLocalizedLanguageName(appContext, sortedIndexInfos.get(i).shortName));
369             }
370             name = nameBuilder.toString();
371         } else {
372             name = uncompressedFilename.replace(".quickdic", "");
373         }
374         fileToNameCache.put(uncompressedFilename, name);
375         return name;
376     }
377
378     public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
379         dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
380         dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
381         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
382     }
383
384     public synchronized void sortDictionaries() {
385         Collections.sort(dictionaryConfig.dictionaryFilesOrdered, uncompressedFilenameComparator);
386         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
387     }
388
389     public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
390         while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
391         }
392         dictionaryConfig.uncompressedFilenameToDictionaryInfo
393         .remove(dictionaryInfo.uncompressedFilename);
394         getPath(dictionaryInfo.uncompressedFilename).delete();
395         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
396     }
397
398     final Comparator<Object> collator = USE_COLLATOR ? CollatorWrapper.getInstance() : null;
399     final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
400         @Override
401         public int compare(String uncompressedFilename1, String uncompressedFilename2) {
402             final String name1 = getDictionaryName(uncompressedFilename1);
403             final String name2 = getDictionaryName(uncompressedFilename2);
404             if (defaultLangName.length() > 0) {
405                 if (name1.startsWith(defaultLangName + "-")
406                         && !name2.startsWith(defaultLangName + "-")) {
407                     return -1;
408                 } else if (name2.startsWith(defaultLangName + "-")
409                            && !name1.startsWith(defaultLangName + "-")) {
410                     return 1;
411                 }
412             }
413             return collator != null ? collator.compare(name1, name2) : name1.compareToIgnoreCase(name2);
414         }
415     };
416     final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
417         @Override
418         public int compare(DictionaryInfo d1, DictionaryInfo d2) {
419             // Single-index dictionaries first.
420             if (d1.indexInfos.size() != d2.indexInfos.size()) {
421                 return d1.indexInfos.size() - d2.indexInfos.size();
422             }
423             return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
424                     d2.uncompressedFilename);
425         }
426     };
427
428     public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
429         new Thread(new Runnable() {
430             @Override
431             public void run() {
432                 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
433                 synchronized (DictionaryApplication.this) {
434                     oldDictionaryConfig.dictionaryFilesOrdered
435                     .addAll(dictionaryConfig.dictionaryFilesOrdered);
436                 }
437                 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
438                 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
439                     final File dictFile = getPath(uncompressedFilename);
440                     final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
441                     if (dictionaryInfo.isValid() || dictFile.exists()) {
442                         newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
443                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
444                             uncompressedFilename, dictionaryInfo);
445                     }
446                 }
447
448                 // Are there dictionaries on the device that we didn't know
449                 // about already?
450                 // Pick them up and put them at the end of the list.
451                 final List<String> toAddSorted = new ArrayList<>();
452                 final File[] dictDirFiles = getDictDir().listFiles();
453                 if (dictDirFiles != null) {
454                     for (final File file : dictDirFiles) {
455                         if (file.getName().endsWith(".zip")) {
456                             if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
457                                     .containsKey(file.getName().replace(".zip", ""))) {
458                                 file.delete();
459                             }
460                         }
461                         if (!file.getName().endsWith(".quickdic")) {
462                             continue;
463                         }
464                         if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
465                                 .containsKey(file.getName())) {
466                             // We have it in our list already.
467                             continue;
468                         }
469                         final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
470                         if (!dictionaryInfo.isValid()) {
471                             Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
472                         }
473
474                         toAddSorted.add(file.getName());
475                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
476                             file.getName(), dictionaryInfo);
477                     }
478                 } else {
479                     Log.w(LOG, "dictDir is not a directory: " + getDictDir().getPath());
480                 }
481                 if (!toAddSorted.isEmpty()) {
482                     Collections.sort(toAddSorted, uncompressedFilenameComparator);
483                     newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
484                 }
485
486                 try {
487                     PersistentObjectCache.getInstance()
488                     .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
489                 } catch (Exception e) {
490                     Log.e(LOG, "Failed persisting dictionary configs", e);
491                 }
492
493                 synchronized (DictionaryApplication.this) {
494                     dictionaryConfig = newDictionaryConfig;
495                 }
496
497                 try {
498                     onUpdateFinished.run();
499                 } catch (Exception e) {
500                     Log.e(LOG, "Exception running callback.", e);
501                 }
502             }
503         }).start();
504     }
505
506     private boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
507         if (filters == null) {
508             return true;
509         }
510         for (final String filter : filters) {
511             if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
512                         filter)) {
513                 return false;
514             }
515         }
516         return true;
517     }
518
519     public synchronized List<DictionaryInfo> getDictionariesOnDevice(String[] filters) {
520         final List<DictionaryInfo> result = new ArrayList<>(
521                 dictionaryConfig.dictionaryFilesOrdered.size());
522         for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
523             final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo
524                                                   .get(uncompressedFilename);
525             if (dictionaryInfo != null && matchesFilters(dictionaryInfo, filters)) {
526                 result.add(dictionaryInfo);
527             }
528         }
529         return result;
530     }
531
532     public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
533         final List<DictionaryInfo> result = new ArrayList<>(
534                 dictionaryConfig.dictionaryFilesOrdered.size());
535
536         final Map<String, DictionaryInfo> remaining = new HashMap<>(
537                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
538         remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
539         for (final DictionaryInfo dictionaryInfo : remaining.values()) {
540             if (matchesFilters(dictionaryInfo, filters)) {
541                 result.add(dictionaryInfo);
542             }
543         }
544         Collections.sort(result, dictionaryInfoComparator);
545         return result;
546     }
547
548     public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
549         final DictionaryInfo downloadable =
550             DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
551                 dictionaryInfo.uncompressedFilename);
552         return downloadable != null &&
553                downloadable.creationMillis > dictionaryInfo.creationMillis;
554     }
555
556     public DictionaryInfo getDownloadable(final String uncompressedFilename) {
557         return DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);
558     }
559
560 }