1 // Copyright 2011 Google Inc. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 package com.hughes.android.dictionary;
17 import java.io.BufferedReader;
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;
29 import android.app.Application;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.SharedPreferences;
33 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
34 import android.preference.PreferenceManager;
35 import android.util.Log;
36 import android.view.Menu;
37 import android.view.MenuItem;
38 import android.view.MenuItem.OnMenuItemClickListener;
40 import com.hughes.android.dictionary.engine.Dictionary;
41 import com.hughes.android.dictionary.engine.Language;
42 import com.hughes.android.dictionary.engine.TransliteratorManager;
43 import com.hughes.android.util.PersistentObjectCache;
44 import com.ibm.icu.text.Collator;
46 public class DictionaryApplication extends Application {
48 static final String LOG = "QuickDicApp";
50 // Static, determined by resources (and locale).
52 static Map<String,DictionaryInfo> DOWNLOADABLE_NAME_TO_INFO = null;
54 static final class DictionaryConfig implements Serializable {
55 private static final long serialVersionUID = -1444177164708201263L;
56 // User-ordered list, persisted, just the ones that are/have been present.
57 final List<String> dictionaryFilesOrdered = new ArrayList<String>();
58 final Map<String, DictionaryInfo> dictionaryInfoCache = new LinkedHashMap<String, DictionaryInfo>();
60 DictionaryConfig dictionaryConfig = null;
62 static final class DictionaryHistory implements Serializable {
63 private static final long serialVersionUID = -4842995032541390284L;
64 // User-ordered list, persisted, just the ones that are/have been present.
65 final List<DictionaryLink> dictionaryLinks = new ArrayList<DictionaryLink>();
67 DictionaryHistory dictionaryHistory = null;
71 static synchronized void staticInit(final Context context) {
72 if (DOWNLOADABLE_NAME_TO_INFO != null) {
75 DOWNLOADABLE_NAME_TO_INFO = new LinkedHashMap<String,DictionaryInfo>();
76 final BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
79 while ((line = reader.readLine()) != null) {
80 if (line.startsWith("#") || line.length() == 0) {
83 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
84 DOWNLOADABLE_NAME_TO_INFO.put(dictionaryInfo.uncompressedFilename, dictionaryInfo);
87 } catch (IOException e) {
88 Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
94 public void onCreate() {
96 Log.d("QuickDic", "Application: onCreate");
97 TransliteratorManager.init(null);
98 staticInit(getApplicationContext());
100 // Load the dictionaries we know about.
101 dictionaryConfig = PersistentObjectCache.init(getApplicationContext()).read(C.DICTIONARY_CONFIGS, DictionaryConfig.class);
102 if (dictionaryConfig == null) {
103 dictionaryConfig = new DictionaryConfig();
107 setTheme(getSelectedTheme().themeId);
108 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
109 prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
111 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
113 Log.d("THAD", "prefs changed: " + key);
114 if (key.equals(getString(R.string.themeKey))) {
115 setTheme(getSelectedTheme().themeId);
121 public void onCreateGlobalOptionsMenu(
122 final Context context, final Menu menu) {
123 final MenuItem about = menu.add(getString(R.string.about));
124 about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
125 public boolean onMenuItemClick(final MenuItem menuItem) {
126 final Intent intent = new Intent().setClassName(AboutActivity.class
127 .getPackage().getName(), AboutActivity.class.getCanonicalName());
128 context.startActivity(intent);
133 final MenuItem help = menu.add(getString(R.string.help));
134 help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
135 public boolean onMenuItemClick(final MenuItem menuItem) {
136 context.startActivity(HelpActivity.getLaunchIntent());
141 final MenuItem preferences = menu.add(getString(R.string.preferences));
142 preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
143 public boolean onMenuItemClick(final MenuItem menuItem) {
144 PreferenceActivity.prefsMightHaveChanged = true;
145 final Intent intent = new Intent().setClassName(PreferenceActivity.class
146 .getPackage().getName(), PreferenceActivity.class.getCanonicalName());
147 context.startActivity(intent);
153 public synchronized File getDictDir() {
154 // This metaphore doesn't work, because we've already reset prefsMightHaveChanged.
155 // if (dictDir == null || PreferenceActivity.prefsMightHaveChanged) {
156 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
157 final String dir = prefs.getString(getString(R.string.quickdicDirectoryKey), getString(R.string.quickdicDirectoryDefault));
158 dictDir = new File(dir);
164 public C.Theme getSelectedTheme() {
165 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
166 final String theme = prefs.getString(getString(R.string.themeKey), "themeLight");
167 if (theme.equals("themeLight")) {
168 return C.Theme.LIGHT;
170 return C.Theme.DEFAULT;
174 public File getPath(String uncompressedFilename) {
175 return new File(getDictDir(), uncompressedFilename);
179 final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
181 public String getLanguageName(final String isoCode) {
182 final Language.LanguageResources languageResources = Language.isoCodeToResources.get(isoCode);
183 final String lang = languageResources != null ? getApplicationContext().getString(languageResources.nameId) : isoCode;
187 public synchronized String getDictionaryName(final String uncompressedFilename) {
188 String name = fileToNameCache.get(uncompressedFilename);
193 final DictionaryInfo dictionaryInfo = DOWNLOADABLE_NAME_TO_INFO.get(uncompressedFilename);
194 if (dictionaryInfo != null) {
195 final StringBuilder nameBuilder = new StringBuilder();
196 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
198 nameBuilder.append("-");
200 nameBuilder.append(getLanguageName(dictionaryInfo.indexInfos.get(i).shortName));
202 name = nameBuilder.toString();
204 name = uncompressedFilename.replace(".quickdic", "");
206 fileToNameCache.put(uncompressedFilename, name);
210 public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
211 dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
212 dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
213 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
216 public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
217 while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {};
218 dictionaryConfig.dictionaryInfoCache.remove(dictionaryInfo.uncompressedFilename);
219 getPath(dictionaryInfo.uncompressedFilename).delete();
220 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
223 final Collator collator = Collator.getInstance();
224 final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
226 public int compare(String uncompressedFilename1, String uncompressedFilename2) {
227 return collator.compare(getDictionaryName(uncompressedFilename1), getDictionaryName(uncompressedFilename2));
230 final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
232 public int compare(DictionaryInfo d1, DictionaryInfo d2) {
233 return uncompressedFilenameComparator.compare(d1.uncompressedFilename, d2.uncompressedFilename);
237 public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
238 new Thread(new Runnable() {
241 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
243 oldDictionaryConfig.dictionaryFilesOrdered.addAll(dictionaryConfig.dictionaryFilesOrdered);
245 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
246 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
247 final File dictFile = getPath(uncompressedFilename);
248 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
249 if (dictionaryInfo != null) {
250 newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
251 newDictionaryConfig.dictionaryInfoCache.put(uncompressedFilename, dictionaryInfo);
255 // Are there dictionaries on the device that we didn't know about already?
256 // Pick them up and put them at the end of the list.
257 final List<String> toAddSorted = new ArrayList<String>();
258 final File[] dictDirFiles = getDictDir().listFiles();
259 if (dictDirFiles != null) {
260 for (final File file : dictDirFiles) {
261 if (file.getName().endsWith(".zip")) {
262 if (DOWNLOADABLE_NAME_TO_INFO.containsKey(file.getName().replace(".zip", ""))) {
266 if (!file.getName().endsWith(".quickdic")) {
269 if (newDictionaryConfig.dictionaryInfoCache.containsKey(file.getName())) {
270 // We have it in our list already.
273 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
274 if (dictionaryInfo == null) {
275 Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
279 toAddSorted.add(file.getName());
280 newDictionaryConfig.dictionaryInfoCache.put(file.getName(), dictionaryInfo);
283 Log.w(LOG, "dictDir is not a diretory: " + getDictDir().getPath());
285 if (!toAddSorted.isEmpty()) {
286 Collections.sort(toAddSorted, uncompressedFilenameComparator);
287 newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
290 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
291 synchronized (this) {
292 dictionaryConfig = newDictionaryConfig;
296 onUpdateFinished.run();
297 } catch (Exception e) {
298 Log.e(LOG, "Exception running callback.", e);
303 public synchronized List<DictionaryInfo> getUsableDicts() {
304 final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(dictionaryConfig.dictionaryFilesOrdered.size());
305 for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
306 final DictionaryInfo dictionaryInfo = dictionaryConfig.dictionaryInfoCache.get(uncompressedFilename);
307 if (dictionaryInfo != null) {
308 result.add(dictionaryInfo);
314 public synchronized List<DictionaryInfo> getAllDictionaries() {
315 final List<DictionaryInfo> result = getUsableDicts();
317 // The downloadable ones.
318 final Map<String,DictionaryInfo> remaining = new LinkedHashMap<String, DictionaryInfo>(DOWNLOADABLE_NAME_TO_INFO);
319 remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
320 final List<DictionaryInfo> toAddSorted = new ArrayList<DictionaryInfo>(remaining.values());
321 Collections.sort(toAddSorted, dictionaryInfoComparator);
322 result.addAll(toAddSorted);
327 public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
328 return dictionaryConfig.dictionaryInfoCache.get(uncompressedFilename) != null;
331 public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
332 final DictionaryInfo downloadable = DOWNLOADABLE_NAME_TO_INFO.get(dictionaryInfo.uncompressedFilename);
333 return downloadable != null && downloadable.creationMillis > dictionaryInfo.creationMillis;
336 public DictionaryInfo getDownloadable(final String uncompressedFilename) {
337 final DictionaryInfo downloadable = DOWNLOADABLE_NAME_TO_INFO.get(uncompressedFilename);