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