]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryApplication.java
Make thread priority setting actually work.
[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.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;
38
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;
47
48 import java.io.BufferedReader;
49 import java.io.File;
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;
59 import java.util.Map;
60
61 public class DictionaryApplication extends Application {
62
63     static final String LOG = "QuickDicApp";
64
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)
69     // when using ICU4J.
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;
74
75     static public final TransliteratorManager.ThreadSetup threadBackground = new TransliteratorManager.ThreadSetup() {
76         @Override
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);
81         }
82     };
83
84     // Static, determined by resources (and locale).
85     // Unordered.
86     static Map<String, DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
87
88     enum Theme {
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),
95
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);
102
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;
113         }
114
115         final int themeId;
116         final int tokenRowFg;
117         final int tokenRowFgColor;
118         final int tokenRowMainBg;
119         final int tokenRowOtherBg;
120         final int normalRowBg;
121     }
122
123     // Useful:
124     // http://www.loc.gov/standards/iso639-2/php/code_list.php
125     public static final Map<String, LanguageResources> isoCodeToResources = new HashMap<String, LanguageResources>();
126     static {
127         isoCodeToResources.put("AF", new LanguageResources("Afrikaans", R.string.AF,
128                                R.drawable.flag_of_south_africa));
129         isoCodeToResources.put("SQ", new LanguageResources("Albanian", R.string.SQ,
130                                R.drawable.flag_of_albania));
131         isoCodeToResources.put("AR",
132                                new LanguageResources("Arabic", R.string.AR, R.drawable.arabic));
133         isoCodeToResources.put("HY", new LanguageResources("Armenian", R.string.HY,
134                                R.drawable.flag_of_armenia));
135         isoCodeToResources.put("BE", new LanguageResources("Belarusian", R.string.BE,
136                                R.drawable.flag_of_belarus));
137         isoCodeToResources.put("BN", new LanguageResources("Bengali", R.string.BN));
138         isoCodeToResources.put("BS", new LanguageResources("Bosnian", R.string.BS,
139                                R.drawable.flag_of_bosnia_and_herzegovina));
140         isoCodeToResources.put("BG", new LanguageResources("Bulgarian", R.string.BG,
141                                R.drawable.flag_of_bulgaria));
142         isoCodeToResources.put("MY", new LanguageResources("Burmese", R.string.MY,
143                                R.drawable.flag_of_myanmar));
144         isoCodeToResources.put("ZH", new LanguageResources("Chinese", R.string.ZH,
145                                R.drawable.flag_of_the_peoples_republic_of_china));
146         isoCodeToResources.put("cmn", new LanguageResources("Mandarin", R.string.cmn,
147                                R.drawable.flag_of_the_peoples_republic_of_china));
148         isoCodeToResources.put("yue", new LanguageResources("Cantonese", R.string.yue,
149                                R.drawable.flag_of_hong_kong));
150         isoCodeToResources.put("CA", new LanguageResources("Catalan", R.string.CA));
151         isoCodeToResources.put("HR", new LanguageResources("Croatian", R.string.HR,
152                                R.drawable.flag_of_croatia));
153         isoCodeToResources.put("CS", new LanguageResources("Czech", R.string.CS,
154                                R.drawable.flag_of_the_czech_republic));
155         isoCodeToResources.put("DA", new LanguageResources("Danish", R.string.DA,
156                                R.drawable.flag_of_denmark));
157         isoCodeToResources.put("NL", new LanguageResources("Dutch", R.string.NL,
158                                R.drawable.flag_of_the_netherlands));
159         isoCodeToResources.put("EN", new LanguageResources("English", R.string.EN,
160                                R.drawable.flag_of_the_united_kingdom));
161         isoCodeToResources.put("EO", new LanguageResources("Esperanto", R.string.EO,
162                                R.drawable.flag_of_esperanto));
163         isoCodeToResources.put("ET", new LanguageResources("Estonian", R.string.ET,
164                                R.drawable.flag_of_estonia));
165         isoCodeToResources.put("FI", new LanguageResources("Finnish", R.string.FI,
166                                R.drawable.flag_of_finland));
167         isoCodeToResources.put("FR", new LanguageResources("French", R.string.FR,
168                                R.drawable.flag_of_france));
169         isoCodeToResources.put("DE", new LanguageResources("German", R.string.DE,
170                                R.drawable.flag_of_germany));
171         isoCodeToResources.put("EL", new LanguageResources("Greek", R.string.EL,
172                                R.drawable.flag_of_greece));
173         isoCodeToResources.put("grc", new LanguageResources("Ancient Greek", R.string.grc));
174         isoCodeToResources.put("haw", new LanguageResources("Hawaiian", R.string.haw,
175                                R.drawable.flag_of_hawaii));
176         isoCodeToResources.put("HE", new LanguageResources("Hebrew", R.string.HE,
177                                R.drawable.flag_of_israel));
178         isoCodeToResources.put("HI", new LanguageResources("Hindi", R.string.HI, R.drawable.hindi));
179         isoCodeToResources.put("HU", new LanguageResources("Hungarian", R.string.HU,
180                                R.drawable.flag_of_hungary));
181         isoCodeToResources.put("IS", new LanguageResources("Icelandic", R.string.IS,
182                                R.drawable.flag_of_iceland));
183         isoCodeToResources.put("ID", new LanguageResources("Indonesian", R.string.ID,
184                                R.drawable.flag_of_indonesia));
185         isoCodeToResources.put("GA", new LanguageResources("Irish", R.string.GA,
186                                R.drawable.flag_of_ireland));
187         isoCodeToResources.put("GD", new LanguageResources("Scottish Gaelic", R.string.GD,
188                                R.drawable.flag_of_scotland));
189         isoCodeToResources.put("GV", new LanguageResources("Manx", R.string.GV,
190                                R.drawable.flag_of_the_isle_of_man));
191         isoCodeToResources.put("IT", new LanguageResources("Italian", R.string.IT,
192                                R.drawable.flag_of_italy));
193         isoCodeToResources.put("LA", new LanguageResources("Latin", R.string.LA));
194         isoCodeToResources.put("LV", new LanguageResources("Latvian", R.string.LV,
195                                R.drawable.flag_of_latvia));
196         isoCodeToResources.put("LT", new LanguageResources("Lithuanian", R.string.LT,
197                                R.drawable.flag_of_lithuania));
198         isoCodeToResources.put("JA", new LanguageResources("Japanese", R.string.JA,
199                                R.drawable.flag_of_japan));
200         isoCodeToResources.put("KO", new LanguageResources("Korean", R.string.KO,
201                                R.drawable.flag_of_south_korea));
202         isoCodeToResources.put("KU", new LanguageResources("Kurdish", R.string.KU));
203         isoCodeToResources.put("MS", new LanguageResources("Malay", R.string.MS,
204                                R.drawable.flag_of_malaysia));
205         isoCodeToResources.put("MI", new LanguageResources("Maori", R.string.MI,
206                                R.drawable.flag_of_new_zealand));
207         isoCodeToResources.put("MN", new LanguageResources("Mongolian", R.string.MN,
208                                R.drawable.flag_of_mongolia));
209         isoCodeToResources.put("NE", new LanguageResources("Nepali", R.string.NE,
210                                R.drawable.flag_of_nepal));
211         isoCodeToResources.put("NO", new LanguageResources("Norwegian", R.string.NO,
212                                R.drawable.flag_of_norway));
213         isoCodeToResources.put("FA", new LanguageResources("Persian", R.string.FA,
214                                R.drawable.flag_of_iran));
215         isoCodeToResources.put("PL", new LanguageResources("Polish", R.string.PL,
216                                R.drawable.flag_of_poland));
217         isoCodeToResources.put("PT", new LanguageResources("Portuguese", R.string.PT,
218                                R.drawable.flag_of_portugal));
219         isoCodeToResources.put("PA", new LanguageResources("Punjabi", R.string.PA));
220         isoCodeToResources.put("RO", new LanguageResources("Romanian", R.string.RO,
221                                R.drawable.flag_of_romania));
222         isoCodeToResources.put("RU", new LanguageResources("Russian", R.string.RU,
223                                R.drawable.flag_of_russia));
224         isoCodeToResources.put("SA", new LanguageResources("Sanskrit", R.string.SA));
225         isoCodeToResources.put("SR", new LanguageResources("Serbian", R.string.SR,
226                                R.drawable.flag_of_serbia));
227         isoCodeToResources.put("SK", new LanguageResources("Slovak", R.string.SK,
228                                R.drawable.flag_of_slovakia));
229         isoCodeToResources.put("SL", new LanguageResources("Slovenian", R.string.SL,
230                                R.drawable.flag_of_slovenia));
231         isoCodeToResources.put("SO", new LanguageResources("Somali", R.string.SO,
232                                R.drawable.flag_of_somalia));
233         isoCodeToResources.put("ES", new LanguageResources("Spanish", R.string.ES,
234                                R.drawable.flag_of_spain));
235         isoCodeToResources.put("SW", new LanguageResources("Swahili", R.string.SW));
236         isoCodeToResources.put("SV", new LanguageResources("Swedish", R.string.SV,
237                                R.drawable.flag_of_sweden));
238         isoCodeToResources.put("TL", new LanguageResources("Tagalog", R.string.TL));
239         isoCodeToResources.put("TG", new LanguageResources("Tajik", R.string.TG,
240                                R.drawable.flag_of_tajikistan));
241         isoCodeToResources.put("TH", new LanguageResources("Thai", R.string.TH,
242                                R.drawable.flag_of_thailand));
243         isoCodeToResources.put("BO", new LanguageResources("Tibetan", R.string.BO));
244         isoCodeToResources.put("TR", new LanguageResources("Turkish", R.string.TR,
245                                R.drawable.flag_of_turkey));
246         isoCodeToResources.put("UK", new LanguageResources("Ukrainian", R.string.UK,
247                                R.drawable.flag_of_ukraine));
248         isoCodeToResources.put("UR", new LanguageResources("Urdu", R.string.UR));
249         isoCodeToResources.put("VI", new LanguageResources("Vietnamese", R.string.VI,
250                                R.drawable.flag_of_vietnam));
251         isoCodeToResources.put("CI", new LanguageResources("Welsh", R.string.CI,
252                                R.drawable.flag_of_wales_2));
253         isoCodeToResources.put("YI", new LanguageResources("Yiddish", R.string.YI));
254         isoCodeToResources.put("ZU", new LanguageResources("Zulu", R.string.ZU));
255         isoCodeToResources.put("AZ", new LanguageResources("Azeri", R.string.AZ,
256                                R.drawable.flag_of_azerbaijan));
257         isoCodeToResources.put("EU", new LanguageResources("Basque", R.string.EU,
258                                R.drawable.flag_of_the_basque_country));
259         isoCodeToResources.put("BR", new LanguageResources("Breton", R.string.BR));
260         isoCodeToResources.put("MR", new LanguageResources("Marathi", R.string.MR));
261         isoCodeToResources.put("FO", new LanguageResources("Faroese", R.string.FO));
262         isoCodeToResources.put("GL", new LanguageResources("Galician", R.string.GL,
263                                R.drawable.flag_of_galicia));
264         isoCodeToResources.put("KA", new LanguageResources("Georgian", R.string.KA,
265                                R.drawable.flag_of_georgia));
266         isoCodeToResources.put("HT", new LanguageResources("Haitian Creole", R.string.HT,
267                                R.drawable.flag_of_haiti));
268         isoCodeToResources.put("LB", new LanguageResources("Luxembourgish", R.string.LB,
269                                R.drawable.flag_of_luxembourg));
270         isoCodeToResources.put("MK", new LanguageResources("Macedonian", R.string.MK,
271                                R.drawable.flag_of_macedonia));
272         isoCodeToResources.put("LO", new LanguageResources("Lao", R.string.LO,
273                                R.drawable.flag_of_laos));
274         isoCodeToResources.put("ML", new LanguageResources("Malayalam", R.string.ML));
275         isoCodeToResources.put("SL", new LanguageResources("Slovenian", R.string.SL,
276                                R.drawable.flag_of_slovenia));
277         isoCodeToResources.put("TA", new LanguageResources("Tamil", R.string.TA));
278         isoCodeToResources.put("SH", new LanguageResources("Serbo-Croatian", R.string.SH));
279         isoCodeToResources.put("SD", new LanguageResources("Sindhi", R.string.SD));
280
281         // Hack to allow lower-case ISO codes to work:
282         for (final String isoCode : new ArrayList<String>(isoCodeToResources.keySet())) {
283             isoCodeToResources.put(isoCode.toLowerCase(), isoCodeToResources.get(isoCode));
284         }
285
286     }
287
288     public static final class DictionaryConfig implements Serializable {
289         private static final long serialVersionUID = -1444177164708201263L;
290         // User-ordered list, persisted, just the ones that are/have been
291         // present.
292         final List<String> dictionaryFilesOrdered = new ArrayList<String>();
293
294         final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new HashMap<String, DictionaryInfo>();
295
296         /**
297          * Sometimes a deserialized version of this data structure isn't valid.
298          * @return
299          */
300         boolean isValid() {
301             return uncompressedFilenameToDictionaryInfo != null && dictionaryFilesOrdered != null;
302         }
303     }
304
305     DictionaryConfig dictionaryConfig = null;
306
307     int languageButtonPixels = -1;
308
309     static synchronized void staticInit(final Context context) {
310         if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
311             return;
312         }
313         DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new HashMap<String, DictionaryInfo>();
314         final BufferedReader reader = new BufferedReader(
315             new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
316         try {
317             String line;
318             while ((line = reader.readLine()) != null) {
319                 if (line.startsWith("#") || line.length() == 0) {
320                     continue;
321                 }
322                 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
323                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
324                     dictionaryInfo.uncompressedFilename, dictionaryInfo);
325             }
326         } catch (IOException e) {
327             Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
328         }
329         try {
330             reader.close();
331         } catch (IOException e) {}
332     }
333
334     private File dictDir;
335
336     @Override
337     public void onCreate() {
338         super.onCreate();
339         Log.d("QuickDic", "Application: onCreate");
340         TransliteratorManager.init(null, threadBackground);
341         staticInit(getApplicationContext());
342
343         languageButtonPixels = (int) TypedValue.applyDimension(
344                                    TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics());
345
346         // Load the dictionaries we know about.
347         dictionaryConfig = PersistentObjectCache.init(getApplicationContext()).read(
348                                C.DICTIONARY_CONFIGS, DictionaryConfig.class);
349         if (dictionaryConfig == null) {
350             dictionaryConfig = new DictionaryConfig();
351         }
352         if (!dictionaryConfig.isValid()) {
353             dictionaryConfig = new DictionaryConfig();
354         }
355
356         // Theme stuff.
357         setTheme(getSelectedTheme().themeId);
358         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
359         prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
360             @Override
361             public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
362                                                   String key) {
363                 Log.d("QuickDic", "prefs changed: " + key);
364                 if (key.equals(getString(R.string.themeKey))) {
365                     setTheme(getSelectedTheme().themeId);
366                 }
367             }
368         });
369     }
370
371     public void onCreateGlobalOptionsMenu(
372         final Context context, final Menu menu) {
373         final MenuItem about = menu.add(getString(R.string.about));
374         MenuItemCompat.setShowAsAction(about, MenuItem.SHOW_AS_ACTION_NEVER);
375         about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
376             public boolean onMenuItemClick(final MenuItem menuItem) {
377                 final Intent intent = new Intent(getApplicationContext(), AboutActivity.class);
378                 context.startActivity(intent);
379                 return false;
380             }
381         });
382
383         final MenuItem help = menu.add(getString(R.string.help));
384         MenuItemCompat.setShowAsAction(help, MenuItem.SHOW_AS_ACTION_NEVER);
385         help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
386             public boolean onMenuItemClick(final MenuItem menuItem) {
387                 context.startActivity(HtmlDisplayActivity.getHelpLaunchIntent(getApplicationContext()));
388                 return false;
389             }
390         });
391
392         final MenuItem preferences = menu.add(getString(R.string.settings));
393         MenuItemCompat.setShowAsAction(preferences, MenuItem.SHOW_AS_ACTION_NEVER);
394         preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
395             public boolean onMenuItemClick(final MenuItem menuItem) {
396                 PreferenceActivity.prefsMightHaveChanged = true;
397                 final Intent intent = new Intent(getApplicationContext(), PreferenceActivity.class);
398                 context.startActivity(intent);
399                 return false;
400             }
401         });
402
403         final MenuItem reportIssue = menu.add(getString(R.string.reportIssue));
404         MenuItemCompat.setShowAsAction(reportIssue, MenuItem.SHOW_AS_ACTION_NEVER);
405         reportIssue.setOnMenuItemClickListener(new OnMenuItemClickListener() {
406             public boolean onMenuItemClick(final MenuItem menuItem) {
407                 final Intent intent = new Intent(Intent.ACTION_VIEW);
408                 intent.setData(Uri
409                                .parse("http://github.com/rdoeffinger/Dictionary/issues"));
410                 context.startActivity(intent);
411                 return false;
412             }
413         });
414     }
415
416     private String selectDefaultDir() {
417         final File defaultDictDir = new File(Environment.getExternalStorageDirectory(), "quickDic");
418         String dir = defaultDictDir.getAbsolutePath();
419         File dictDir = new File(dir);
420         String[] fileList = dictDir.isDirectory() ? dictDir.list() : null;
421         if (fileList != null && fileList.length > 0) {
422             return dir;
423         }
424         File efd = null;
425         try {
426             efd = getApplicationContext().getExternalFilesDir(null);
427         } catch (Exception e) {
428         }
429         if (efd != null) {
430             efd.mkdirs();
431             if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
432                 getApplicationContext().getExternalFilesDirs(null);
433             }
434             if (efd.isDirectory() && efd.canWrite() && checkFileCreate(efd)) {
435                 return efd.getAbsolutePath();
436             }
437         }
438         if (!dictDir.isDirectory() && !dictDir.mkdirs()) {
439             return getApplicationContext().getFilesDir().getAbsolutePath();
440         }
441         return dir;
442     }
443
444     public synchronized File getDictDir() {
445         // This metaphor doesn't work, because we've already reset
446         // prefsMightHaveChanged.
447         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
448         String dir = prefs.getString(getString(R.string.quickdicDirectoryKey), "");
449         if (dir.isEmpty()) {
450             dir = selectDefaultDir();
451         }
452         dictDir = new File(dir);
453         dictDir.mkdirs();
454         if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
455             getApplicationContext().getExternalFilesDirs(null);
456         }
457         return dictDir;
458     }
459
460     static public boolean checkFileCreate(File dir) {
461         boolean res = false;
462         File testfile = new File(dir, "quickdic_writetest");
463         try {
464             testfile.delete();
465             res = testfile.createNewFile() & testfile.delete();
466         } catch (Exception e) {
467         }
468         return res;
469     }
470
471     public File getWordListFile() {
472         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
473         String file = prefs.getString(getString(R.string.wordListFileKey), "");
474         if (file.isEmpty()) {
475             return new File(getDictDir(), "wordList.txt");
476         }
477         return new File(file);
478     }
479
480     public Theme getSelectedTheme() {
481         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
482         final String theme = prefs.getString(getString(R.string.themeKey), "themeLight");
483         if (theme.equals("themeLight")) {
484             return Theme.LIGHT;
485         } else {
486             return Theme.DEFAULT;
487         }
488     }
489
490     public File getPath(String uncompressedFilename) {
491         return new File(getDictDir(), uncompressedFilename);
492     }
493
494     String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
495     String defaultLangName = null;
496     final Map<String, String> fileToNameCache = new HashMap<String, String>();
497
498     public String isoCodeToLocalizedLanguageName(final String isoCode) {
499         String lang = new Locale(isoCode).getDisplayLanguage();
500         if (!lang.equals("") && !lang.equals(isoCode))
501         {
502             return lang;
503         }
504         final Language.LanguageResources languageResources = isoCodeToResources
505                 .get(isoCode);
506         if (languageResources != null)
507         {
508             lang = getApplicationContext().getString(languageResources.nameId);
509         }
510         return lang;
511     }
512
513     public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
514         // Hack to put the default locale first in the name.
515         if (indexInfos.size() > 1 &&
516                 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
517             List<IndexInfo> result = new ArrayList<DictionaryInfo.IndexInfo>(indexInfos);
518             ListUtil.swap(result, 0, 1);
519             return result;
520         }
521         return indexInfos;
522     }
523
524     public synchronized String getDictionaryName(final String uncompressedFilename) {
525         final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
526         if (!currentLocale.equals(defaultLangISO2)) {
527             defaultLangISO2 = currentLocale;
528             fileToNameCache.clear();
529             defaultLangName = null;
530         }
531         if (defaultLangName == null) {
532             defaultLangName = isoCodeToLocalizedLanguageName(defaultLangISO2);
533         }
534
535         String name = fileToNameCache.get(uncompressedFilename);
536         if (name != null) {
537             return name;
538         }
539
540         final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
541                                               .get(uncompressedFilename);
542         if (dictionaryInfo != null) {
543             final StringBuilder nameBuilder = new StringBuilder();
544
545             List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
546             for (int i = 0; i < sortedIndexInfos.size(); ++i) {
547                 if (i > 0) {
548                     nameBuilder.append("-");
549                 }
550                 nameBuilder
551                 .append(isoCodeToLocalizedLanguageName(sortedIndexInfos.get(i).shortName));
552             }
553             name = nameBuilder.toString();
554         } else {
555             name = uncompressedFilename.replace(".quickdic", "");
556         }
557         fileToNameCache.put(uncompressedFilename, name);
558         return name;
559     }
560
561     public View createButton(final Context context, final DictionaryInfo dictionaryInfo,
562                              final IndexInfo indexInfo) {
563         LanguageResources languageResources = isoCodeToResources.get(indexInfo.shortName);
564         View result;
565
566         if (languageResources == null || languageResources.flagId <= 0) {
567             Button button = new Button(context);
568             button.setText(indexInfo.shortName);
569             result = button;
570         } else {
571             ImageButton button = new ImageButton(context);
572             button.setImageResource(languageResources.flagId);
573             button.setScaleType(ScaleType.FIT_CENTER);
574             result = button;
575         }
576         result.setLayoutParams(new LinearLayout.LayoutParams(languageButtonPixels, languageButtonPixels * 2 / 3));
577         return result;
578     }
579
580     public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
581         dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
582         dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
583         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
584     }
585
586     public synchronized void sortDictionaries() {
587         Collections.sort(dictionaryConfig.dictionaryFilesOrdered, uncompressedFilenameComparator);
588         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
589     }
590
591     public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
592         while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
593         }
594         dictionaryConfig.uncompressedFilenameToDictionaryInfo
595         .remove(dictionaryInfo.uncompressedFilename);
596         getPath(dictionaryInfo.uncompressedFilename).delete();
597         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
598     }
599
600     final Comparator collator = USE_COLLATOR ? Collator.getInstance() : String.CASE_INSENSITIVE_ORDER;
601     final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
602         @Override
603         public int compare(String uncompressedFilename1, String uncompressedFilename2) {
604             final String name1 = getDictionaryName(uncompressedFilename1);
605             final String name2 = getDictionaryName(uncompressedFilename2);
606             if (defaultLangName.length() > 0) {
607                 if (name1.startsWith(defaultLangName + "-")
608                         && !name2.startsWith(defaultLangName + "-")) {
609                     return -1;
610                 } else if (name2.startsWith(defaultLangName + "-")
611                            && !name1.startsWith(defaultLangName + "-")) {
612                     return 1;
613                 }
614             }
615             return collator.compare(name1, name2);
616         }
617     };
618     final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
619         @Override
620         public int compare(DictionaryInfo d1, DictionaryInfo d2) {
621             // Single-index dictionaries first.
622             if (d1.indexInfos.size() != d2.indexInfos.size()) {
623                 return d1.indexInfos.size() - d2.indexInfos.size();
624             }
625             return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
626                     d2.uncompressedFilename);
627         }
628     };
629
630     public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
631         new Thread(new Runnable() {
632             @Override
633             public void run() {
634                 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
635                 synchronized (DictionaryApplication.this) {
636                     oldDictionaryConfig.dictionaryFilesOrdered
637                     .addAll(dictionaryConfig.dictionaryFilesOrdered);
638                 }
639                 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
640                 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
641                     final File dictFile = getPath(uncompressedFilename);
642                     final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
643                     if (dictionaryInfo.isValid() || dictFile.exists()) {
644                         newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
645                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
646                             uncompressedFilename, dictionaryInfo);
647                     }
648                 }
649
650                 // Are there dictionaries on the device that we didn't know
651                 // about already?
652                 // Pick them up and put them at the end of the list.
653                 final List<String> toAddSorted = new ArrayList<String>();
654                 final File[] dictDirFiles = getDictDir().listFiles();
655                 if (dictDirFiles != null) {
656                     for (final File file : dictDirFiles) {
657                         if (file.getName().endsWith(".zip")) {
658                             if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
659                                     .containsKey(file.getName().replace(".zip", ""))) {
660                                 file.delete();
661                             }
662                         }
663                         if (!file.getName().endsWith(".quickdic")) {
664                             continue;
665                         }
666                         if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
667                                 .containsKey(file.getName())) {
668                             // We have it in our list already.
669                             continue;
670                         }
671                         final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
672                         if (!dictionaryInfo.isValid()) {
673                             Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
674                         }
675
676                         toAddSorted.add(file.getName());
677                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
678                             file.getName(), dictionaryInfo);
679                     }
680                 } else {
681                     Log.w(LOG, "dictDir is not a directory: " + getDictDir().getPath());
682                 }
683                 if (!toAddSorted.isEmpty()) {
684                     Collections.sort(toAddSorted, uncompressedFilenameComparator);
685                     newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
686                 }
687
688                 try {
689                     PersistentObjectCache.getInstance()
690                     .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
691                 } catch (Exception e) {
692                     Log.e(LOG, "Failed persisting dictionary configs", e);
693                 }
694
695                 synchronized (DictionaryApplication.this) {
696                     dictionaryConfig = newDictionaryConfig;
697                 }
698
699                 try {
700                     onUpdateFinished.run();
701                 } catch (Exception e) {
702                     Log.e(LOG, "Exception running callback.", e);
703                 }
704             }
705         }).start();
706     }
707
708     public boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
709         if (filters == null) {
710             return true;
711         }
712         for (final String filter : filters) {
713             if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
714                         filter)) {
715                 return false;
716             }
717         }
718         return true;
719     }
720
721     public synchronized List<DictionaryInfo> getDictionariesOnDevice(String[] filters) {
722         final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
723             dictionaryConfig.dictionaryFilesOrdered.size());
724         for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
725             final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo
726                                                   .get(uncompressedFilename);
727             if (dictionaryInfo != null && matchesFilters(dictionaryInfo, filters)) {
728                 result.add(dictionaryInfo);
729             }
730         }
731         return result;
732     }
733
734     public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
735         final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
736             dictionaryConfig.dictionaryFilesOrdered.size());
737
738         final Map<String, DictionaryInfo> remaining = new HashMap<String, DictionaryInfo>(
739             DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
740         remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
741         for (final DictionaryInfo dictionaryInfo : remaining.values()) {
742             if (matchesFilters(dictionaryInfo, filters)) {
743                 result.add(dictionaryInfo);
744             }
745         }
746         Collections.sort(result, dictionaryInfoComparator);
747         return result;
748     }
749
750     public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
751         return dictionaryConfig.uncompressedFilenameToDictionaryInfo.get(uncompressedFilename) != null;
752     }
753
754     public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
755         final DictionaryInfo downloadable =
756             DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
757                 dictionaryInfo.uncompressedFilename);
758         return downloadable != null &&
759                downloadable.creationMillis > dictionaryInfo.creationMillis;
760     }
761
762     public DictionaryInfo getDownloadable(final String uncompressedFilename) {
763         final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
764                                             .get(uncompressedFilename);
765         return downloadable;
766     }
767
768 }