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