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