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