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;
27 import java.util.Locale;
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;
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;
50 public class DictionaryApplication extends Application {
52 static final String LOG = "QuickDicApp";
54 // Static, determined by resources (and locale).
56 static Map<String,DictionaryInfo> DOWNLOADABLE_NAME_TO_INFO = null;
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>();
64 DictionaryConfig dictionaryConfig = null;
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>();
71 DictionaryHistory dictionaryHistory = null;
75 static synchronized void staticInit(final Context context) {
76 if (DOWNLOADABLE_NAME_TO_INFO != null) {
79 DOWNLOADABLE_NAME_TO_INFO = new LinkedHashMap<String,DictionaryInfo>();
80 final BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
83 while ((line = reader.readLine()) != null) {
84 if (line.startsWith("#") || line.length() == 0) {
87 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
88 DOWNLOADABLE_NAME_TO_INFO.put(dictionaryInfo.uncompressedFilename, dictionaryInfo);
91 } catch (IOException e) {
92 Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
98 public void onCreate() {
100 Log.d("QuickDic", "Application: onCreate");
101 TransliteratorManager.init(null);
102 staticInit(getApplicationContext());
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();
111 setTheme(getSelectedTheme().themeId);
112 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
113 prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
115 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
117 Log.d("QuickDic", "prefs changed: " + key);
118 if (key.equals(getString(R.string.themeKey))) {
119 setTheme(getSelectedTheme().themeId);
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);
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());
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);
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);
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);
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;
185 return C.Theme.DEFAULT;
189 public File getPath(String uncompressedFilename) {
190 return new File(getDictDir(), uncompressedFilename);
195 String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
196 final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
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;
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();
212 String name = fileToNameCache.get(uncompressedFilename);
217 final DictionaryInfo dictionaryInfo = DOWNLOADABLE_NAME_TO_INFO.get(uncompressedFilename);
218 if (dictionaryInfo != null) {
219 final StringBuilder nameBuilder = new StringBuilder();
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);
228 for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
230 nameBuilder.append("-");
232 nameBuilder.append(getLanguageName(dictionaryInfo.indexInfos.get(i).shortName));
235 ListUtil.swap(dictionaryInfo.indexInfos, 0, 1);
237 name = nameBuilder.toString();
239 name = uncompressedFilename.replace(".quickdic", "");
241 fileToNameCache.put(uncompressedFilename, name);
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);
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);
258 final Collator collator = Collator.getInstance();
259 final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
261 public int compare(String uncompressedFilename1, String uncompressedFilename2) {
262 return collator.compare(getDictionaryName(uncompressedFilename1), getDictionaryName(uncompressedFilename2));
265 final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
267 public int compare(DictionaryInfo d1, DictionaryInfo d2) {
268 return uncompressedFilenameComparator.compare(d1.uncompressedFilename, d2.uncompressedFilename);
272 public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
273 new Thread(new Runnable() {
276 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
278 oldDictionaryConfig.dictionaryFilesOrdered.addAll(dictionaryConfig.dictionaryFilesOrdered);
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);
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", ""))) {
301 if (!file.getName().endsWith(".quickdic")) {
304 if (newDictionaryConfig.dictionaryInfoCache.containsKey(file.getName())) {
305 // We have it in our list already.
308 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
309 if (dictionaryInfo == null) {
310 Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
314 toAddSorted.add(file.getName());
315 newDictionaryConfig.dictionaryInfoCache.put(file.getName(), dictionaryInfo);
318 Log.w(LOG, "dictDir is not a diretory: " + getDictDir().getPath());
320 if (!toAddSorted.isEmpty()) {
321 Collections.sort(toAddSorted, uncompressedFilenameComparator);
322 newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
325 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
326 synchronized (this) {
327 dictionaryConfig = newDictionaryConfig;
331 onUpdateFinished.run();
332 } catch (Exception e) {
333 Log.e(LOG, "Exception running callback.", e);
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);
349 public synchronized List<DictionaryInfo> getAllDictionaries() {
350 final List<DictionaryInfo> result = getUsableDicts();
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);
362 public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
363 return dictionaryConfig.dictionaryInfoCache.get(uncompressedFilename) != null;
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;
371 public DictionaryInfo getDownloadable(final String uncompressedFilename) {
372 final DictionaryInfo downloadable = DOWNLOADABLE_NAME_TO_INFO.get(uncompressedFilename);