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