]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryApplication.java
New images.
[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.view.View.OnClickListener;
29 import android.view.ViewGroup.LayoutParams;
30 import android.widget.Button;
31 import android.widget.ImageButton;
32 import android.widget.ImageView.ScaleType;
33 import android.widget.LinearLayout;
34
35 import com.actionbarsherlock.view.Menu;
36 import com.actionbarsherlock.view.MenuItem;
37 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
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.TransliteratorManager;
42 import com.hughes.android.dictionary.engine.Language.LanguageResources;
43 import com.hughes.android.util.IntentLauncher;
44 import com.hughes.android.util.PersistentObjectCache;
45 import com.hughes.util.ListUtil;
46 import com.ibm.icu.text.Collator;
47
48 import java.io.BufferedReader;
49 import java.io.File;
50 import java.io.IOException;
51 import java.io.InputStreamReader;
52 import java.io.Serializable;
53 import java.util.ArrayList;
54 import java.util.Collections;
55 import java.util.Comparator;
56 import java.util.LinkedHashMap;
57 import java.util.List;
58 import java.util.Locale;
59 import java.util.Map;
60
61 public class DictionaryApplication extends Application {
62
63     static final String LOG = "QuickDicApp";
64
65     // Static, determined by resources (and locale).
66     // Unordered.
67     static Map<String, DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
68
69     static final class DictionaryConfig implements Serializable {
70         private static final long serialVersionUID = -1444177164708201263L;
71         // User-ordered list, persisted, just the ones that are/have been
72         // present.
73         final List<String> dictionaryFilesOrdered = new ArrayList<String>();
74
75         final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new LinkedHashMap<String, DictionaryInfo>();
76     }
77
78     DictionaryConfig dictionaryConfig = null;
79
80     int languageButtonPixels = -1;
81
82     // static final class DictionaryHistory implements Serializable {
83     // private static final long serialVersionUID = -4842995032541390284L;
84     // // User-ordered list, persisted, just the ones that are/have been
85     // present.
86     // final List<DictionaryLink> dictionaryLinks = new
87     // ArrayList<DictionaryLink>();
88     // }
89     // DictionaryHistory dictionaryHistory = null;
90
91     static synchronized void staticInit(final Context context) {
92         if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
93             return;
94         }
95         DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new LinkedHashMap<String, DictionaryInfo>();
96         final BufferedReader reader = new BufferedReader(
97                 new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
98         try {
99             String line;
100             while ((line = reader.readLine()) != null) {
101                 if (line.startsWith("#") || line.length() == 0) {
102                     continue;
103                 }
104                 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
105                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
106                         dictionaryInfo.uncompressedFilename, dictionaryInfo);
107             }
108             reader.close();
109         } catch (IOException e) {
110             Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
111         }
112     }
113
114     private File dictDir;
115
116     @Override
117     public void onCreate() {
118         super.onCreate();
119         Log.d("QuickDic", "Application: onCreate");
120         TransliteratorManager.init(null);
121         staticInit(getApplicationContext());
122
123         languageButtonPixels = (int) TypedValue.applyDimension(
124                 TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics());
125
126         // Load the dictionaries we know about.
127         dictionaryConfig = PersistentObjectCache.init(getApplicationContext()).read(
128                 C.DICTIONARY_CONFIGS, DictionaryConfig.class);
129         if (dictionaryConfig == null) {
130             dictionaryConfig = new DictionaryConfig();
131         }
132
133         // Theme stuff.
134         setTheme(getSelectedTheme().themeId);
135         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
136         prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
137             @Override
138             public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
139                     String key) {
140                 Log.d("QuickDic", "prefs changed: " + key);
141                 if (key.equals(getString(R.string.themeKey))) {
142                     setTheme(getSelectedTheme().themeId);
143                 }
144             }
145         });
146     }
147
148     public void onCreateGlobalOptionsMenu(
149             final Context context, final Menu menu) {
150         final MenuItem about = menu.add(getString(R.string.about));
151         about.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
152         about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
153             public boolean onMenuItemClick(final MenuItem menuItem) {
154                 final Intent intent = new Intent().setClassName(AboutActivity.class
155                         .getPackage().getName(), AboutActivity.class.getCanonicalName());
156                 context.startActivity(intent);
157                 return false;
158             }
159         });
160
161         final MenuItem help = menu.add(getString(R.string.help));
162         help.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
163         help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
164             public boolean onMenuItemClick(final MenuItem menuItem) {
165                 context.startActivity(HtmlDisplayActivity.getHelpLaunchIntent());
166                 return false;
167             }
168         });
169
170         final MenuItem preferences = menu.add(getString(R.string.settings));
171         preferences.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
172         preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
173             public boolean onMenuItemClick(final MenuItem menuItem) {
174                 PreferenceActivity.prefsMightHaveChanged = true;
175                 final Intent intent = new Intent().setClassName(PreferenceActivity.class
176                         .getPackage().getName(), PreferenceActivity.class.getCanonicalName());
177                 context.startActivity(intent);
178                 return false;
179             }
180         });
181
182         final MenuItem reportIssue = menu.add(getString(R.string.reportIssue));
183         reportIssue.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
184         reportIssue.setOnMenuItemClickListener(new OnMenuItemClickListener() {
185             public boolean onMenuItemClick(final MenuItem menuItem) {
186                 final Intent intent = new Intent(Intent.ACTION_VIEW);
187                 intent.setData(Uri
188                         .parse("http://code.google.com/p/quickdic-dictionary/issues/entry"));
189                 context.startActivity(intent);
190                 return false;
191             }
192         });
193     }
194
195     public synchronized File getDictDir() {
196         // This metaphor doesn't work, because we've already reset
197         // prefsMightHaveChanged.
198         // if (dictDir == null || PreferenceActivity.prefsMightHaveChanged) {
199         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
200         final File defaultDictDir = new File(Environment.getExternalStorageDirectory(), "quickDic");
201         String dir = prefs.getString(getString(R.string.quickdicDirectoryKey),
202                 defaultDictDir.getAbsolutePath());
203         if (dir.isEmpty()) {
204             dir = defaultDictDir.getAbsolutePath();
205         }
206         dictDir = new File(dir);
207         dictDir.mkdirs();
208         return dictDir;
209     }
210
211     public C.Theme getSelectedTheme() {
212         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
213         final String theme = prefs.getString(getString(R.string.themeKey), "themeLight");
214         if (theme.equals("themeLight")) {
215             return C.Theme.LIGHT;
216         } else {
217             return C.Theme.DEFAULT;
218         }
219     }
220
221     public File getPath(String uncompressedFilename) {
222         return new File(getDictDir(), uncompressedFilename);
223     }
224
225     String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
226     String defaultLangName = null;
227     final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
228
229     public String isoCodeToLocalizedLanguageName(final String isoCode) {
230         final Language.LanguageResources languageResources = Language.isoCodeToResources
231                 .get(isoCode);
232         final String lang = languageResources != null ? getApplicationContext().getString(
233                 languageResources.nameId) : isoCode;
234         return lang;
235     }
236
237     public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
238         // Hack to put the default locale first in the name.
239         if (indexInfos.size() > 1 &&
240                 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
241             List<IndexInfo> result = new ArrayList<DictionaryInfo.IndexInfo>(indexInfos);
242             ListUtil.swap(result, 0, 1);
243             return result;
244         }
245         return indexInfos;
246     }
247
248     public synchronized String getDictionaryName(final String uncompressedFilename) {
249         final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
250         if (!currentLocale.equals(defaultLangISO2)) {
251             defaultLangISO2 = currentLocale;
252             fileToNameCache.clear();
253             defaultLangName = null;
254         }
255         if (defaultLangName == null) {
256             defaultLangName = isoCodeToLocalizedLanguageName(defaultLangISO2);
257         }
258
259         String name = fileToNameCache.get(uncompressedFilename);
260         if (name != null) {
261             return name;
262         }
263
264         final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
265                 .get(uncompressedFilename);
266         if (dictionaryInfo != null) {
267             final StringBuilder nameBuilder = new StringBuilder();
268
269             List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
270             for (int i = 0; i < sortedIndexInfos.size(); ++i) {
271                 if (i > 0) {
272                     nameBuilder.append("-");
273                 }
274                 nameBuilder
275                         .append(isoCodeToLocalizedLanguageName(sortedIndexInfos.get(i).shortName));
276             }
277             name = nameBuilder.toString();
278         } else {
279             name = uncompressedFilename.replace(".quickdic", "");
280         }
281         fileToNameCache.put(uncompressedFilename, name);
282         return name;
283     }
284
285     public View createButton(final Context context, final DictionaryInfo dictionaryInfo,
286             final IndexInfo indexInfo) {
287         LanguageResources languageResources = Language.isoCodeToResources.get(indexInfo.shortName);
288         View result;
289
290         if (languageResources == null || languageResources.flagId <= 0) {
291             Button button = new Button(context);
292             button.setText(indexInfo.shortName);
293             result = button;
294         } else {
295             ImageButton button = new ImageButton(context);
296             button.setImageResource(languageResources.flagId);
297             button.setScaleType(ScaleType.FIT_CENTER);
298             result = button;
299         }
300         result.setMinimumWidth(languageButtonPixels);
301         result.setMinimumHeight(languageButtonPixels * 2 / 3);
302         // result.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
303         // LayoutParams.WRAP_CONTENT));
304         return result;
305     }
306
307     public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
308         dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
309         dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
310         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
311     }
312
313     public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
314         while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
315         }
316         ;
317         dictionaryConfig.uncompressedFilenameToDictionaryInfo
318                 .remove(dictionaryInfo.uncompressedFilename);
319         getPath(dictionaryInfo.uncompressedFilename).delete();
320         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
321     }
322
323     final Collator collator = Collator.getInstance();
324     final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
325         @Override
326         public int compare(String uncompressedFilename1, String uncompressedFilename2) {
327             final String name1 = getDictionaryName(uncompressedFilename1);
328             final String name2 = getDictionaryName(uncompressedFilename2);
329             if (defaultLangName.length() > 0) {
330                 if (name1.startsWith(defaultLangName + "-")
331                         && !name2.startsWith(defaultLangName + "-")) {
332                     return -1;
333                 } else if (name2.startsWith(defaultLangName + "-")
334                         && !name1.startsWith(defaultLangName + "-")) {
335                     return 1;
336                 }
337             }
338             return collator.compare(name1, name2);
339         }
340     };
341     final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
342         @Override
343         public int compare(DictionaryInfo d1, DictionaryInfo d2) {
344             // Single-index dictionaries first.
345             if (d1.indexInfos.size() != d2.indexInfos.size()) {
346                 return d1.indexInfos.size() - d2.indexInfos.size();
347             }
348             return uncompressedFilenameComparator.compare(d1.uncompressedFilename,
349                     d2.uncompressedFilename);
350         }
351     };
352
353     public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
354         new Thread(new Runnable() {
355             @Override
356             public void run() {
357                 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
358                 synchronized (this) {
359                     oldDictionaryConfig.dictionaryFilesOrdered
360                             .addAll(dictionaryConfig.dictionaryFilesOrdered);
361                 }
362                 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
363                 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
364                     final File dictFile = getPath(uncompressedFilename);
365                     final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
366                     if (dictionaryInfo != null) {
367                         newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
368                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
369                                 uncompressedFilename, dictionaryInfo);
370                     }
371                 }
372
373                 // Are there dictionaries on the device that we didn't know
374                 // about already?
375                 // Pick them up and put them at the end of the list.
376                 final List<String> toAddSorted = new ArrayList<String>();
377                 final File[] dictDirFiles = getDictDir().listFiles();
378                 if (dictDirFiles != null) {
379                     for (final File file : dictDirFiles) {
380                         if (file.getName().endsWith(".zip")) {
381                             if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
382                                     .containsKey(file.getName().replace(".zip", ""))) {
383                                 file.delete();
384                             }
385                         }
386                         if (!file.getName().endsWith(".quickdic")) {
387                             continue;
388                         }
389                         if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo
390                                 .containsKey(file.getName())) {
391                             // We have it in our list already.
392                             continue;
393                         }
394                         final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
395                         if (dictionaryInfo == null) {
396                             Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
397                             continue;
398                         }
399
400                         toAddSorted.add(file.getName());
401                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
402                                 file.getName(), dictionaryInfo);
403                     }
404                 } else {
405                     Log.w(LOG, "dictDir is not a diretory: " + getDictDir().getPath());
406                 }
407                 if (!toAddSorted.isEmpty()) {
408                     Collections.sort(toAddSorted, uncompressedFilenameComparator);
409                     newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
410                 }
411
412                 PersistentObjectCache.getInstance()
413                         .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
414                 synchronized (this) {
415                     dictionaryConfig = newDictionaryConfig;
416                 }
417
418                 try {
419                     onUpdateFinished.run();
420                 } catch (Exception e) {
421                     Log.e(LOG, "Exception running callback.", e);
422                 }
423             }
424         }).start();
425     }
426
427     public boolean matchesFilters(final DictionaryInfo dictionaryInfo, final String[] filters) {
428         if (filters == null) {
429             return true;
430         }
431         for (final String filter : filters) {
432             if (!getDictionaryName(dictionaryInfo.uncompressedFilename).toLowerCase().contains(
433                     filter)) {
434                 return false;
435             }
436         }
437         return true;
438     }
439
440     public synchronized List<DictionaryInfo> getDictionariesOnDevice(String[] filters) {
441         final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
442                 dictionaryConfig.dictionaryFilesOrdered.size());
443         for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
444             final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo
445                     .get(uncompressedFilename);
446             if (dictionaryInfo != null && matchesFilters(dictionaryInfo, filters)) {
447                 result.add(dictionaryInfo);
448             }
449         }
450         return result;
451     }
452
453     public List<DictionaryInfo> getDownloadableDictionaries(String[] filters) {
454         final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
455                 dictionaryConfig.dictionaryFilesOrdered.size());
456
457         final Map<String, DictionaryInfo> remaining = new LinkedHashMap<String, DictionaryInfo>(
458                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
459         remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
460         for (final DictionaryInfo dictionaryInfo : remaining.values()) {
461             if (matchesFilters(dictionaryInfo, filters)) {
462                 result.add(dictionaryInfo);
463             }
464         }
465         Collections.sort(result, dictionaryInfoComparator);
466         return result;
467     }
468
469     public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
470         return dictionaryConfig.uncompressedFilenameToDictionaryInfo.get(uncompressedFilename) != null;
471     }
472
473     public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
474         final DictionaryInfo downloadable =
475                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(
476                         dictionaryInfo.uncompressedFilename);
477         return downloadable != null &&
478                 downloadable.creationMillis > dictionaryInfo.creationMillis;
479     }
480
481     public DictionaryInfo getDownloadable(final String uncompressedFilename) {
482         final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO
483                 .get(uncompressedFilename);
484         return downloadable;
485     }
486
487 }