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