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