]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryApplication.java
Long-press on lang button shows list.
[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.LinkedHashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30
31 import android.app.Application;
32 import android.content.Context;
33 import android.content.SharedPreferences;
34 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
35 import android.os.Environment;
36 import android.preference.PreferenceManager;
37 import android.util.Log;
38
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.util.PersistentObjectCache;
43 import com.ibm.icu.text.Collator;
44
45 public class DictionaryApplication extends Application {
46   
47   static final String LOG = "QuickDicApp";
48   
49   private static final File DICT_DIR = new File(Environment.getExternalStorageDirectory().getName(), "quickdic");
50
51   // Static, determined by resources (and locale).
52   // Unordered.
53   static Map<String,DictionaryInfo> DOWNLOADABLE_NAME_TO_INFO = null;
54   
55   static final class DictionaryConfig implements Serializable {
56     private static final long serialVersionUID = -1444177164708201262L;
57     // User-ordered list, persisted, just the ones that are/have been present.
58     final List<DictionaryInfo> dictionaryFilesOrdered = new ArrayList<DictionaryInfo>();
59     final Set<String> invalidatedFilenames = new LinkedHashSet<String>();
60   }
61   DictionaryConfig dictionaryConfig = null;
62
63   static final class DictionaryHistory implements Serializable {
64     private static final long serialVersionUID = -4842995032541390284L;
65     // User-ordered list, persisted, just the ones that are/have been present.
66     final List<DictionaryLink> dictionaryLinks = new ArrayList<DictionaryLink>();
67   }
68   DictionaryHistory dictionaryHistory = null;
69
70   
71   @Override
72   public void onCreate() {
73     super.onCreate();
74     Log.d("QuickDic", "Application: onCreate");
75     TransliteratorManager.init(null);
76     staticInit(getApplicationContext());
77     
78     // Load the dictionaries we know about.
79     dictionaryConfig = PersistentObjectCache.init(getApplicationContext()).read(C.DICTIONARY_CONFIGS, DictionaryConfig.class);
80     if (dictionaryConfig == null) {
81       dictionaryConfig = new DictionaryConfig();
82     }
83     
84
85     // Theme stuff.
86     setTheme(getSelectedTheme().themeId);
87     final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
88     prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
89       @Override
90       public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
91           String key) {
92         Log.d("THAD", "prefs changed: " + key);
93         if (key.equals(getString(R.string.themeKey))) {
94           setTheme(getSelectedTheme().themeId);
95         }
96       }
97     });
98   }
99   
100   public C.Theme getSelectedTheme() {
101     final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
102     final String theme = prefs.getString(getString(R.string.themeKey), "themeLight");
103     if (theme.equals("themeLight")) {
104       return C.Theme.LIGHT;
105     } else {
106       return C.Theme.DEFAULT;
107     }
108   }
109     
110   static synchronized void staticInit(final Context context) {
111     if (DOWNLOADABLE_NAME_TO_INFO != null) {
112       return;
113     }
114     DOWNLOADABLE_NAME_TO_INFO = new LinkedHashMap<String,DictionaryInfo>();
115     final BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
116     try {
117       String line;
118       while ((line = reader.readLine()) != null) {
119         if (line.startsWith("#") || line.length() == 0) {
120           continue;
121         }
122         final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
123         DOWNLOADABLE_NAME_TO_INFO.put(dictionaryInfo.uncompressedFilename, dictionaryInfo);
124       }
125       reader.close();
126     } catch (IOException e) {
127       Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
128     }
129   }
130
131   public File getPath(String uncompressedFilename) {
132     return new File(DICT_DIR, uncompressedFilename);
133   }
134
135
136   public List<DictionaryInfo> getUsableDicts() {
137     final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(dictionaryConfig.dictionaryFilesOrdered.size());
138     for (int i = 0; i < dictionaryConfig.dictionaryFilesOrdered.size(); ++i) {
139       DictionaryInfo dictionaryInfo = dictionaryConfig.dictionaryFilesOrdered.get(i);
140       if (dictionaryConfig.invalidatedFilenames.contains(dictionaryInfo.uncompressedFilename)) {
141         dictionaryInfo = Dictionary.getDictionaryInfo(getPath(dictionaryInfo.uncompressedFilename));
142         if (dictionaryInfo != null) {
143           dictionaryConfig.dictionaryFilesOrdered.set(i, dictionaryInfo);
144         }
145       }
146       if (dictionaryInfo != null) {
147         result.add(dictionaryInfo);
148       }
149     }
150     if (!dictionaryConfig.invalidatedFilenames.isEmpty()) {
151       dictionaryConfig.invalidatedFilenames.clear();
152       PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
153     }
154     return result;
155   }
156   
157   public String getLanguageName(final String isoCode) {
158     final Integer langCode = Language.isoCodeToResourceId.get(isoCode);
159     final String lang = langCode != null ? getApplicationContext().getString(langCode) : isoCode;
160     return lang;
161   }
162
163   final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
164   public synchronized String getDictionaryName(final String uncompressedFilename) {
165     String name = fileToNameCache.get(uncompressedFilename);
166     if (name != null) {
167       return name;
168     }
169     
170     final DictionaryInfo dictionaryInfo = DOWNLOADABLE_NAME_TO_INFO.get(uncompressedFilename);
171     if (dictionaryInfo != null) {
172       final StringBuilder nameBuilder = new StringBuilder();
173       for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
174         if (i > 0) {
175           nameBuilder.append("-");
176         }
177         nameBuilder.append(getLanguageName(dictionaryInfo.indexInfos.get(i).shortName));
178       }
179       name = nameBuilder.toString();
180     } else {
181       name = uncompressedFilename.replace(".quickdic", "");
182     }
183     fileToNameCache.put(uncompressedFilename, name);
184     return name;
185   }
186
187   public void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
188     dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo);
189     dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo);
190     PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
191   }
192
193   public void deleteDictionary(final DictionaryInfo dictionaryInfo) {
194     while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo)) {};
195     getPath(dictionaryInfo.uncompressedFilename).delete();
196     PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
197   }
198
199   final Collator collator = Collator.getInstance();
200   final Comparator<DictionaryInfo> comparator = new Comparator<DictionaryInfo>() {
201     @Override
202     public int compare(DictionaryInfo object1, DictionaryInfo object2) {
203       return collator.compare(getDictionaryName(object1.uncompressedFilename), getDictionaryName(object2.uncompressedFilename));
204     }
205   };
206
207   public List<DictionaryInfo> getAllDictionaries() {
208     final List<DictionaryInfo> result = getUsableDicts();
209     
210     // The ones we knew about...
211     final Set<String> known = new LinkedHashSet<String>();
212     for (final DictionaryInfo usable : result) {
213       known.add(usable.uncompressedFilename);
214     }
215     if (!dictionaryConfig.invalidatedFilenames.isEmpty()) {
216       dictionaryConfig.invalidatedFilenames.clear();
217     }
218     
219     // Are there dictionaries on the device that we didn't know about already?
220     // Pick them up and put them at the end of the list.
221     final List<DictionaryInfo> toAddSorted = new ArrayList<DictionaryInfo>();
222     final File[] dictDirFiles = DICT_DIR.listFiles();
223     for (final File file : dictDirFiles) {
224       if (!file.getName().endsWith(".quickdic")) {
225         continue;
226       }
227       if (known.contains(file.getName())) {
228         // We have it in our list already.
229         continue;
230       }
231       final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
232       if (dictionaryInfo == null) {
233         Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
234         continue;
235       }
236       known.add(file.getName());
237       toAddSorted.add(dictionaryInfo);
238     }
239     if (!toAddSorted.isEmpty()) {
240       Collections.sort(toAddSorted, comparator);
241       result.addAll(toAddSorted);
242 //      for (final DictionaryInfo dictionaryInfo : toAddSorted) {
243 //        dictionaryConfig.dictionaryFilesOrdered.add(dictionaryInfo.uncompressedFilename);
244 //      }
245       dictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
246       PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
247     }
248
249     // The downloadable ones.
250     final Map<String,DictionaryInfo> remaining = new LinkedHashMap<String, DictionaryInfo>(DOWNLOADABLE_NAME_TO_INFO);
251     remaining.keySet().removeAll(known);
252     toAddSorted.clear();
253     toAddSorted.addAll(remaining.values());
254     Collections.sort(toAddSorted, comparator);
255     result.addAll(toAddSorted);
256     return result;
257   }
258
259   public boolean isDictionaryOnDevice(String uncompressedFilename) {
260     return getPath(uncompressedFilename).canRead();
261   }
262
263   public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
264     final DictionaryInfo downloadable = DOWNLOADABLE_NAME_TO_INFO.get(dictionaryInfo.uncompressedFilename);
265     return downloadable != null && downloadable.creationMillis > dictionaryInfo.creationMillis;
266   }
267
268   public DictionaryInfo getDownloadable(final String uncompressedFilename) {
269     final DictionaryInfo downloadable = DOWNLOADABLE_NAME_TO_INFO.get(uncompressedFilename);
270     return downloadable;
271   }
272
273   public void invalidateDictionaryInfo(final String uncompressedFilename) {
274     dictionaryConfig.invalidatedFilenames.add(uncompressedFilename);
275     PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
276   }
277   
278 }