]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryApplication.java
Picking back up in the middle of a major refactoring of the UI, tyring
[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
26 import com.actionbarsherlock.view.Menu;
27 import com.actionbarsherlock.view.MenuItem;
28 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
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.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
128     about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
129       public boolean onMenuItemClick(final MenuItem menuItem) {
130         final Intent intent = new Intent().setClassName(AboutActivity.class
131             .getPackage().getName(), AboutActivity.class.getCanonicalName());
132         context.startActivity(intent);
133         return false;
134       }
135     });
136
137     final MenuItem help = menu.add(getString(R.string.help));
138     help.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
139     help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
140       public boolean onMenuItemClick(final MenuItem menuItem) {
141         context.startActivity(HtmlDisplayActivity.getHelpLaunchIntent());
142         return false;
143       }
144     });
145
146     final MenuItem preferences = menu.add(getString(R.string.settings));
147     preferences.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
148     preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
149       public boolean onMenuItemClick(final MenuItem menuItem) {
150         SettingsActivity.settingsMightHaveChanged = true;
151         final Intent intent = new Intent().setClassName(SettingsActivity.class
152             .getPackage().getName(), SettingsActivity.class.getCanonicalName());
153         context.startActivity(intent);
154         return false;
155       }
156     });
157     
158     
159     final MenuItem reportIssue = menu.add(getString(R.string.reportIssue));
160     reportIssue.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
161     reportIssue.setOnMenuItemClickListener(new OnMenuItemClickListener() {
162       public boolean onMenuItemClick(final MenuItem menuItem) {
163         final Intent intent = new Intent(Intent.ACTION_VIEW);
164         intent.setData(Uri.parse("http://code.google.com/p/quickdic-dictionary/issues/entry"));
165         context.startActivity(intent);
166         return false;
167       }
168     });
169   }
170   
171   public synchronized File getDictDir() {
172     // This metaphore doesn't work, because we've already reset prefsMightHaveChanged.
173 //    if (dictDir == null || PreferenceActivity.prefsMightHaveChanged) {
174       final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
175       final String dir = prefs.getString(getString(R.string.quickdicDirectoryKey), getString(R.string.quickdicDirectoryDefault));
176       dictDir = new File(dir);
177       dictDir.mkdirs();
178 //    }
179     return dictDir;
180   }
181   
182   public C.Theme getSelectedTheme() {
183     final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
184     final String theme = prefs.getString(getString(R.string.themeKey), "themeLight");
185     if (theme.equals("themeLight")) {
186       return C.Theme.LIGHT;
187     } else {
188       return C.Theme.DEFAULT;
189     }
190   }
191     
192   public File getPath(String uncompressedFilename) {
193     return new File(getDictDir(), uncompressedFilename);
194   }
195   
196
197   String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
198   String defaultLangName = null;
199   final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
200
201   public String getLanguageName(final String isoCode) {
202     final Language.LanguageResources languageResources = Language.isoCodeToResources.get(isoCode); 
203     final String lang = languageResources != null ? getApplicationContext().getString(languageResources.nameId) : isoCode;
204     return lang;
205   }
206   
207
208   public synchronized String getDictionaryName(final String uncompressedFilename) {
209     final String currentLocale = Locale.getDefault().getLanguage().toLowerCase(); 
210     if (!currentLocale.equals(defaultLangISO2)) {
211       defaultLangISO2 = currentLocale;
212       fileToNameCache.clear();
213       defaultLangName = null;
214     }
215     if (defaultLangName == null) {
216       defaultLangName = getLanguageName(defaultLangISO2);
217     }
218     
219     String name = fileToNameCache.get(uncompressedFilename);
220     if (name != null) {
221       return name;
222     }
223     
224     final DictionaryInfo dictionaryInfo = DOWNLOADABLE_NAME_TO_INFO.get(uncompressedFilename);
225     if (dictionaryInfo != null) {
226       final StringBuilder nameBuilder = new StringBuilder();
227
228       // Hack to put the default locale first in the name.
229       boolean swapped = false;
230       if (dictionaryInfo.indexInfos.size() > 1 && 
231           dictionaryInfo.indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
232         ListUtil.swap(dictionaryInfo.indexInfos, 0, 1);
233         swapped = true;
234       }
235       for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
236         if (i > 0) {
237           nameBuilder.append("-");
238         }
239         nameBuilder.append(getLanguageName(dictionaryInfo.indexInfos.get(i).shortName));
240       }
241       if (swapped) {
242         ListUtil.swap(dictionaryInfo.indexInfos, 0, 1);
243       }
244       name = nameBuilder.toString();
245     } else {
246       name = uncompressedFilename.replace(".quickdic", "");
247     }
248     fileToNameCache.put(uncompressedFilename, name);
249     return name;
250   }
251
252   public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
253     dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
254     dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
255     PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
256   }
257
258   public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
259     while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {};
260     dictionaryConfig.dictionaryInfoCache.remove(dictionaryInfo.uncompressedFilename);
261     getPath(dictionaryInfo.uncompressedFilename).delete();
262     PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
263   }
264
265   final Collator collator = Collator.getInstance();
266   final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
267     @Override
268     public int compare(String uncompressedFilename1, String uncompressedFilename2) {
269       final String name1 = getDictionaryName(uncompressedFilename1);
270       final String name2 = getDictionaryName(uncompressedFilename2);
271       if (defaultLangName.length() > 0) {
272         if (name1.startsWith(defaultLangName) && !name2.startsWith(defaultLangName)) {
273           return -1;
274         } else if (name2.startsWith(defaultLangName) && !name1.startsWith(defaultLangName)) {
275           return 1;
276         }
277       }
278       return collator.compare(name1, name2);
279     }
280   };
281   final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
282     @Override
283     public int compare(DictionaryInfo d1, DictionaryInfo d2) {
284       // Single-index dictionaries first.
285       if (d1.indexInfos.size() != d2.indexInfos.size()) {
286           return d1.indexInfos.size() - d2.indexInfos.size();
287       }
288       return uncompressedFilenameComparator.compare(d1.uncompressedFilename, d2.uncompressedFilename);
289     }
290   };
291   
292   public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
293     new Thread(new Runnable() {
294       @Override
295       public void run() {
296         final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
297         synchronized(this) {
298           oldDictionaryConfig.dictionaryFilesOrdered.addAll(dictionaryConfig.dictionaryFilesOrdered);
299         }
300         final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
301         for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
302           final File dictFile = getPath(uncompressedFilename);
303           final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
304           if (dictionaryInfo != null) {
305             newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
306             newDictionaryConfig.dictionaryInfoCache.put(uncompressedFilename, dictionaryInfo);
307           }
308         }
309         
310         // Are there dictionaries on the device that we didn't know about already?
311         // Pick them up and put them at the end of the list.
312         final List<String> toAddSorted = new ArrayList<String>();
313         final File[] dictDirFiles = getDictDir().listFiles();
314         if (dictDirFiles != null) {
315           for (final File file : dictDirFiles) {
316             if (file.getName().endsWith(".zip")) {
317               if (DOWNLOADABLE_NAME_TO_INFO.containsKey(file.getName().replace(".zip", ""))) {
318                 file.delete();
319               }
320             }
321             if (!file.getName().endsWith(".quickdic")) {
322               continue;
323             }
324             if (newDictionaryConfig.dictionaryInfoCache.containsKey(file.getName())) {
325               // We have it in our list already.
326               continue;
327             }
328             final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
329             if (dictionaryInfo == null) {
330               Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
331               continue;
332             }
333             
334             toAddSorted.add(file.getName());
335             newDictionaryConfig.dictionaryInfoCache.put(file.getName(), dictionaryInfo);
336           }
337         } else {
338           Log.w(LOG, "dictDir is not a diretory: " + getDictDir().getPath());
339         }
340         if (!toAddSorted.isEmpty()) {
341           Collections.sort(toAddSorted, uncompressedFilenameComparator);
342           newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
343         }
344
345         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
346         synchronized (this) {
347           dictionaryConfig = newDictionaryConfig;
348         }
349         
350         try {
351           onUpdateFinished.run();
352         } catch (Exception e) {
353           Log.e(LOG, "Exception running callback.", e);
354         }
355       }}).start();
356   }
357
358   public synchronized List<DictionaryInfo> getUsableDicts() {
359     final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(dictionaryConfig.dictionaryFilesOrdered.size());
360     for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
361       final DictionaryInfo dictionaryInfo = dictionaryConfig.dictionaryInfoCache.get(uncompressedFilename);
362       if (dictionaryInfo != null) {
363         result.add(dictionaryInfo);
364       }
365     }
366     return result;
367   }
368
369   public synchronized List<DictionaryInfo> getAllDictionaries() {
370     final List<DictionaryInfo> result = getUsableDicts();
371     
372     // The downloadable ones.
373     final Map<String,DictionaryInfo> remaining = new LinkedHashMap<String, DictionaryInfo>(DOWNLOADABLE_NAME_TO_INFO);
374     remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
375     final List<DictionaryInfo> toAddSorted = new ArrayList<DictionaryInfo>(remaining.values());
376     Collections.sort(toAddSorted, dictionaryInfoComparator);
377     result.addAll(toAddSorted);
378     
379     return result;
380   }
381
382   public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
383     return dictionaryConfig.dictionaryInfoCache.get(uncompressedFilename) != null;
384   }
385
386   public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
387     final DictionaryInfo downloadable = DOWNLOADABLE_NAME_TO_INFO.get(dictionaryInfo.uncompressedFilename);
388     return downloadable != null && downloadable.creationMillis > dictionaryInfo.creationMillis;
389   }
390
391   public DictionaryInfo getDownloadable(final String uncompressedFilename) {
392     final DictionaryInfo downloadable = DOWNLOADABLE_NAME_TO_INFO.get(uncompressedFilename);
393     return downloadable;
394   }
395
396 }