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