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