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