]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryApplication.java
Replace issue reporting URL and email address.
[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(getApplicationContext(), AboutActivity.class);
354                 context.startActivity(intent);
355                 return false;
356             }
357         });
358
359         final MenuItem help = menu.add(getString(R.string.help));
360         MenuItemCompat.setShowAsAction(help, MenuItem.SHOW_AS_ACTION_NEVER);
361         help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
362             public boolean onMenuItemClick(final MenuItem menuItem) {
363                 context.startActivity(HtmlDisplayActivity.getHelpLaunchIntent(getApplicationContext()));
364                 return false;
365             }
366         });
367
368         final MenuItem preferences = menu.add(getString(R.string.settings));
369         MenuItemCompat.setShowAsAction(preferences, MenuItem.SHOW_AS_ACTION_NEVER);
370         preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
371             public boolean onMenuItemClick(final MenuItem menuItem) {
372                 PreferenceActivity.prefsMightHaveChanged = true;
373                 final Intent intent = new Intent(getApplicationContext(), PreferenceActivity.class);
374                 context.startActivity(intent);
375                 return false;
376             }
377         });
378
379         final MenuItem reportIssue = menu.add(getString(R.string.reportIssue));
380         MenuItemCompat.setShowAsAction(reportIssue, MenuItem.SHOW_AS_ACTION_NEVER);
381         reportIssue.setOnMenuItemClickListener(new OnMenuItemClickListener() {
382             public boolean onMenuItemClick(final MenuItem menuItem) {
383                 final Intent intent = new Intent(Intent.ACTION_VIEW);
384                 intent.setData(Uri
385                         .parse("http://github.com/rdoeffinger/Dictionary/issues"));
386                 context.startActivity(intent);
387                 return false;
388             }
389         });
390     }
391
392     public synchronized File getDictDir() {
393         // This metaphor doesn't work, because we've already reset
394         // prefsMightHaveChanged.
395         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
396         String dir = prefs.getString(getString(R.string.quickdicDirectoryKey), "");
397         if (dir.isEmpty()) {
398             final File defaultDictDir = new File(Environment.getExternalStorageDirectory(), "quickDic");
399             dir = defaultDictDir.getAbsolutePath();
400         }
401         dictDir = new File(dir);
402         dictDir.mkdirs();
403         return dictDir;
404     }
405
406     public File getWordListFile() {
407         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
408         String file = prefs.getString(getString(R.string.wordListFileKey), "");
409         if (file.isEmpty()) {
410             return new File(getDictDir(), "wordList.txt");
411         }
412         return new File(file);
413     }
414
415     public Theme getSelectedTheme() {
416         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
417         final String theme = prefs.getString(getString(R.string.themeKey), "themeLight");
418         if (theme.equals("themeLight")) {
419             return Theme.LIGHT;
420         } else {
421             return Theme.DEFAULT;
422         }
423     }
424
425     public File getPath(String uncompressedFilename) {
426         return new File(getDictDir(), uncompressedFilename);
427     }
428
429     String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
430     String defaultLangName = null;
431     final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
432
433     public String isoCodeToLocalizedLanguageName(final String isoCode) {
434         final Language.LanguageResources languageResources = isoCodeToResources
435                 .get(isoCode);
436         final String lang = languageResources != null ? getApplicationContext().getString(
437                 languageResources.nameId) : isoCode;
438         return lang;
439     }
440
441     public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
442         // Hack to put the default locale first in the name.
443         if (indexInfos.size() > 1 &&
444                 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
445             List<IndexInfo> result = new ArrayList<DictionaryInfo.IndexInfo>(indexInfos);
446             ListUtil.swap(result, 0, 1);
447             return result;
448         }
449         return indexInfos;
450     }
451
452     public synchronized String getDictionaryName(final String uncompressedFilename) {
453         final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
454         if (!currentLocale.equals(defaultLangISO2)) {
455             defaultLangISO2 = currentLocale;
456             fileToNameCache.clear();
457             defaultLangName = null;
458         }
459         if (defaultLangName == null) {
460             defaultLangName = isoCodeToLocalizedLanguageName(defaultLangISO2);
461         }
462
463         String name = fileToNameCache.get(uncompressedFilename);
464         if (name != null) {
465             return name;
466         }
467
468         final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
469                 .get(uncompressedFilename);
470         if (dictionaryInfo != null) {
471             final StringBuilder nameBuilder = new StringBuilder();
472
473             List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
474             for (int i = 0; i < sortedIndexInfos.size(); ++i) {
475                 if (i > 0) {
476                     nameBuilder.append("-");
477                 }
478                 nameBuilder
479                         .append(isoCodeToLocalizedLanguageName(sortedIndexInfos.get(i).shortName));
480             }
481             name = nameBuilder.toString();
482         } else {
483             name = uncompressedFilename.replace(".quickdic", "");
484         }
485         fileToNameCache.put(uncompressedFilename, name);
486         return name;
487     }
488
489     public View createButton(final Context context, final DictionaryInfo dictionaryInfo,
490             final IndexInfo indexInfo) {
491         LanguageResources languageResources = isoCodeToResources.get(indexInfo.shortName);
492         View result;
493
494         if (languageResources == null || languageResources.flagId <= 0) {
495             Button button = new Button(context);
496             button.setText(indexInfo.shortName);
497             result = button;
498         } else {
499             ImageButton button = new ImageButton(context);
500             button.setImageResource(languageResources.flagId);
501             button.setScaleType(ScaleType.FIT_CENTER);
502             result = button;
503         }
504         result.setMinimumWidth(languageButtonPixels);
505         result.setMinimumHeight(languageButtonPixels * 2 / 3);
506         // result.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
507         // LayoutParams.WRAP_CONTENT));
508         return result;
509     }
510
511     public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
512         dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
513         dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
514         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
515     }
516
517     public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
518         while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
519         }
520         dictionaryConfig.uncompressedFilenameToDictionaryInfo
521                 .remove(dictionaryInfo.uncompressedFilename);
522         getPath(dictionaryInfo.uncompressedFilename).delete();
523         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
524     }
525
526     final Collator collator = Collator.getInstance();
527     final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
528         @Override
529         public int compare(String uncompressedFilename1, String uncompressedFilename2) {
530             final String name1 = getDictionaryName(uncompressedFilename1);
531             final String name2 = getDictionaryName(uncompressedFilename2);
532             if (defaultLangName.length() > 0) {
533                 if (name1.startsWith(defaultLangName + "-")
534                         && !name2.startsWith(defaultLangName + "-")) {
535                     return -1;
536                 } else if (name2.startsWith(defaultLangName + "-")
537                         && !name1.startsWith(defaultLangName + "-")) {
538                     return 1;
539                 }
540             }
541             return collator.compare(name1, name2);
542         }
543     };
544     final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
545         @Override
546         public int compare(DictionaryInfo d1, DictionaryInfo d2) {
547             // Single-index dictionaries first.
548             if (d1.indexInfos.size() != d2.indexInfos.size()) {
549                 return d1.indexInfos.size() - d2.indexInfos.size();
550             }
551             return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
552                     d2.uncompressedFilename);
553         }
554     };
555
556     public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
557         new Thread(new Runnable() {
558             @Override
559             public void run() {
560                 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
561                 synchronized (this) {
562                     oldDictionaryConfig.dictionaryFilesOrdered
563                             .addAll(dictionaryConfig.dictionaryFilesOrdered);
564                 }
565                 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
566                 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
567                     final File dictFile = getPath(uncompressedFilename);
568                     final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
569                     if (dictionaryInfo != null) {
570                         newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
571                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
572                                 uncompressedFilename, dictionaryInfo);
573                     }
574                 }
575
576                 // Are there dictionaries on the device that we didn't know
577                 // about already?
578                 // Pick them up and put them at the end of the list.
579                 final List<String> toAddSorted = new ArrayList<String>();
580                 final File[] dictDirFiles = getDictDir().listFiles();
581                 if (dictDirFiles != null) {
582                     for (final File file : dictDirFiles) {
583                         if (file.getName().endsWith(".zip")) {
584                             if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
585                                     .containsKey(file.getName().replace(".zip", ""))) {
586                                 file.delete();
587                             }
588                         }
589                         if (!file.getName().endsWith(".quickdic")) {
590                             continue;
591                         }
592                         if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
593                                 .containsKey(file.getName())) {
594                             // We have it in our list already.
595                             continue;
596                         }
597                         final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
598                         if (dictionaryInfo == null) {
599                             Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
600                             continue;
601                         }
602
603                         toAddSorted.add(file.getName());
604                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
605                                 file.getName(), dictionaryInfo);
606                     }
607                 } else {
608                     Log.w(LOG, "dictDir is not a diretory: " + getDictDir().getPath());
609                 }
610                 if (!toAddSorted.isEmpty()) {
611                     Collections.sort(toAddSorted, uncompressedFilenameComparator);
612                     newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
613                 }
614
615                 PersistentObjectCache.getInstance()
616                         .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
617                 synchronized (this) {
618                     dictionaryConfig = newDictionaryConfig;
619                 }
620
621                 try {
622                     onUpdateFinished.run();
623                 } catch (Exception e) {
624                     Log.e(LOG, "Exception running callback.", e);
625                 }
626             }
627         }).start();
628     }
629
630     public boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
631         if (filters == null) {
632             return true;
633         }
634         for (final String filter : filters) {
635             if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
636                     filter)) {
637                 return false;
638             }
639         }
640         return true;
641     }
642
643     public synchronized List<DictionaryInfo> getDictionariesOnDevice(String[] filters) {
644         final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
645                 dictionaryConfig.dictionaryFilesOrdered.size());
646         for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
647             final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo
648                     .get(uncompressedFilename);
649             if (dictionaryInfo != null && matchesFilters(dictionaryInfo, filters)) {
650                 result.add(dictionaryInfo);
651             }
652         }
653         return result;
654     }
655
656     public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
657         final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
658                 dictionaryConfig.dictionaryFilesOrdered.size());
659
660         final Map<String, DictionaryInfo> remaining = new LinkedHashMap<String, DictionaryInfo>(
661                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
662         remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
663         for (final DictionaryInfo dictionaryInfo : remaining.values()) {
664             if (matchesFilters(dictionaryInfo, filters)) {
665                 result.add(dictionaryInfo);
666             }
667         }
668         Collections.sort(result, dictionaryInfoComparator);
669         return result;
670     }
671
672     public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
673         return dictionaryConfig.uncompressedFilenameToDictionaryInfo.get(uncompressedFilename) != null;
674     }
675
676     public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
677         final DictionaryInfo downloadable =
678                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
679                         dictionaryInfo.uncompressedFilename);
680         return downloadable != null &&
681                 downloadable.creationMillis > dictionaryInfo.creationMillis;
682     }
683
684     public DictionaryInfo getDownloadable(final String uncompressedFilename) {
685         final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
686                 .get(uncompressedFilename);
687         return downloadable;
688     }
689
690 }