]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryApplication.java
Major refactor of down dictionary list is stored by app.
[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 = -1444177164708201260L;
57     // User-ordered list, persisted, just the ones that are/have been present.
58     final List<String> dictionaryFiles = new ArrayList<String>();
59   }
60   DictionaryConfig dictionaryConfig = null;
61     
62   @Override
63   public void onCreate() {
64     super.onCreate();
65     Log.d("QuickDic", "Application: onCreate");
66     TransliteratorManager.init(null);
67     staticInit(getApplicationContext());
68     
69     // Load the dictionaries we know about.
70     dictionaryConfig = PersistentObjectCache.init(getApplicationContext()).read(C.DICTIONARY_CONFIGS, DictionaryConfig.class);
71     if (dictionaryConfig == null) {
72       dictionaryConfig = new DictionaryConfig();
73     }
74     
75
76     // Theme stuff.
77     setTheme(getSelectedTheme().themeId);
78     final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
79     prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
80       @Override
81       public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
82           String key) {
83         Log.d("THAD", "prefs changed: " + key);
84         if (key.equals(getString(R.string.themeKey))) {
85           setTheme(getSelectedTheme().themeId);
86         }
87       }
88     });
89   }
90   
91   public C.Theme getSelectedTheme() {
92     final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
93     final String theme = prefs.getString(getString(R.string.themeKey), "themeLight");
94     if (theme.equals("themeLight")) {
95       return C.Theme.LIGHT;
96     } else {
97       return C.Theme.DEFAULT;
98     }
99   }
100     
101   static synchronized void staticInit(final Context context) {
102     if (DOWNLOADABLE_NAME_TO_INFO != null) {
103       return;
104     }
105     DOWNLOADABLE_NAME_TO_INFO = new LinkedHashMap<String,DictionaryInfo>();
106     final BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
107     try {
108       String line;
109       while ((line = reader.readLine()) != null) {
110         if (line.startsWith("#") || line.length() == 0) {
111           continue;
112         }
113         final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
114         DOWNLOADABLE_NAME_TO_INFO.put(dictionaryInfo.uncompressedFilename, dictionaryInfo);
115       }
116       reader.close();
117     } catch (IOException e) {
118       Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
119     }
120   }
121
122   private File getPath(String uncompressedFilename) {
123     return new File(DICT_DIR, uncompressedFilename);
124   }
125
126
127   public List<DictionaryInfo> getUsableDicts() {
128     final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(dictionaryConfig.dictionaryFiles.size());
129     for (final String uncompressedFilename : dictionaryConfig.dictionaryFiles) {
130       final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(getPath(uncompressedFilename));
131       if (dictionaryInfo != null) {
132         result.add(dictionaryInfo);
133       }
134     }
135     return result;
136   }
137
138   final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
139   public synchronized String getDictionaryName(final String uncompressedFilename) {
140     String name = fileToNameCache.get(uncompressedFilename);
141     if (name != null) {
142       return name;
143     }
144     
145     final DictionaryInfo dictionaryInfo = DOWNLOADABLE_NAME_TO_INFO.get(uncompressedFilename);
146     final Context context = getApplicationContext();
147     if (dictionaryInfo != null) {
148       final StringBuilder nameBuilder = new StringBuilder();
149       for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
150         final Integer langCode = Language.isoCodeToResourceId.get(dictionaryInfo.indexInfos.get(i).shortName);
151         final String lang = langCode != null ? context.getString(langCode) : dictionaryInfo.indexInfos.get(i).shortName;
152         if (i > 0) {
153           nameBuilder.append("-");
154         }
155         nameBuilder.append(lang);
156       }
157       name = nameBuilder.toString();
158     } else {
159       name = uncompressedFilename.replace(".quickdic", "");
160     }
161     fileToNameCache.put(uncompressedFilename, name);
162     return name;
163   }
164
165   public void moveDictionaryToTop(final String canonicalPath) {
166     dictionaryConfig.dictionaryFiles.remove(canonicalPath);
167     dictionaryConfig.dictionaryFiles.add(0, canonicalPath);
168     PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
169   }
170
171   public void deleteDictionary(String canonicalPath) {
172     while (dictionaryConfig.dictionaryFiles.remove(canonicalPath)) {};
173     PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
174   }
175
176   public List<DictionaryInfo> getAllDictionaries() {
177     final List<DictionaryInfo> result = getUsableDicts();
178     
179     // The ones we knew about...
180     final Set<String> known = new LinkedHashSet<String>();
181     for (final DictionaryInfo usable : result) {
182       known.add(usable.uncompressedFilename);
183     }
184     
185     // Are there dictionaries on the device that we didn't know about already?
186     // Pick them up and put them at the end of the list.
187     boolean foundNew = false;
188     final File[] dictDirFiles = DICT_DIR.listFiles();
189     for (final File file : dictDirFiles) {
190       if (!file.getName().endsWith(".quickdic")) {
191         continue;
192       }
193       if (known.contains(file.getName())) {
194         // We have it in our list already.
195         continue;
196       }
197       final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
198       if (dictionaryInfo == null) {
199         Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
200         continue;
201       }
202       known.add(file.getName());
203       foundNew = true;
204       dictionaryConfig.dictionaryFiles.add(file.getName());
205       result.add(dictionaryInfo);
206     }
207     if (foundNew) {
208       PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
209     }
210
211     // The downloadable ones.
212     final Map<String,DictionaryInfo> remaining = new LinkedHashMap<String, DictionaryInfo>(DOWNLOADABLE_NAME_TO_INFO);
213     remaining.keySet().removeAll(known);
214     final List<DictionaryInfo> remainingSorted = new ArrayList<DictionaryInfo>(remaining.values());
215     final Collator collator = Collator.getInstance();
216     Collections.sort(remainingSorted, new Comparator<DictionaryInfo>() {
217       @Override
218       public int compare(DictionaryInfo object1, DictionaryInfo object2) {
219         return collator.compare(getDictionaryName(object1.uncompressedFilename), getDictionaryName(object2.uncompressedFilename));
220       }
221     });
222
223     result.addAll(remainingSorted);
224     return result;
225   }
226
227   public boolean isDictionaryOnDevice(String uncompressedFilename) {
228     return getPath(uncompressedFilename).canRead();
229   }
230
231   
232 }