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