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