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 android.app.Application;
18 import android.content.Context;
19 import android.content.Intent;
20 import android.content.SharedPreferences;
21 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
22 import android.net.Uri;
23 import android.preference.PreferenceManager;
24 import android.util.Log;
25 import android.view.View;
26 import android.view.View.OnClickListener;
27 import android.widget.Button;
28 import android.widget.ImageButton;
29 import android.widget.ImageView.ScaleType;
31 import com.actionbarsherlock.view.Menu;
32 import com.actionbarsherlock.view.MenuItem;
33 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
34 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
35 import com.hughes.android.dictionary.engine.Dictionary;
36 import com.hughes.android.dictionary.engine.Language;
37 import com.hughes.android.dictionary.engine.TransliteratorManager;
38 import com.hughes.android.dictionary.engine.Language.LanguageResources;
39 import com.hughes.android.util.IntentLauncher;
40 import com.hughes.android.util.PersistentObjectCache;
41 import com.hughes.util.ListUtil;
42 import com.ibm.icu.text.Collator;
44 import java.io.BufferedReader;
46 import java.io.IOException;
47 import java.io.InputStreamReader;
48 import java.io.Serializable;
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.Comparator;
52 import java.util.LinkedHashMap;
53 import java.util.List;
54 import java.util.Locale;
57 public class DictionaryApplication extends Application {
59 static final String LOG = "QuickDicApp";
61 // Static, determined by resources (and locale).
63 static Map<String,DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
65 static final class DictionaryConfig implements Serializable {
66 private static final long serialVersionUID = -1444177164708201263L;
67 // User-ordered list, persisted, just the ones that are/have been present.
68 final List<String> dictionaryFilesOrdered = new ArrayList<String>();
70 final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new LinkedHashMap<String, DictionaryInfo>();
72 DictionaryConfig dictionaryConfig = null;
74 // static final class DictionaryHistory implements Serializable {
75 // private static final long serialVersionUID = -4842995032541390284L;
76 // // User-ordered list, persisted, just the ones that are/have been present.
77 // final List<DictionaryLink> dictionaryLinks = new ArrayList<DictionaryLink>();
79 // DictionaryHistory dictionaryHistory = null;
81 static synchronized void staticInit(final Context context) {
82 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
85 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new LinkedHashMap<String,DictionaryInfo>();
86 final BufferedReader reader = new BufferedReader(
87 new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
90 while ((line = reader.readLine()) != null) {
91 if (line.startsWith("#") || line.length() == 0) {
94 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
95 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
96 dictionaryInfo.uncompressedFilename, dictionaryInfo);
99 } catch (IOException e) {
100 Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
105 private File dictDir;
108 public void onCreate() {
110 Log.d("QuickDic", "Application: onCreate");
111 TransliteratorManager.init(null);
112 staticInit(getApplicationContext());
114 // Load the dictionaries we know about.
115 dictionaryConfig = PersistentObjectCache.init(getApplicationContext()).read(
116 C.DICTIONARY_CONFIGS, DictionaryConfig.class);
117 if (dictionaryConfig == null) {
118 dictionaryConfig = new DictionaryConfig();
122 setTheme(getSelectedTheme().themeId);
123 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
124 prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
126 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
128 Log.d("QuickDic", "prefs changed: " + key);
129 if (key.equals(getString(R.string.themeKey))) {
130 setTheme(getSelectedTheme().themeId);
136 public void onCreateGlobalOptionsMenu(
137 final Context context, final Menu menu) {
138 final MenuItem about = menu.add(getString(R.string.about));
139 about.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
140 about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
141 public boolean onMenuItemClick(final MenuItem menuItem) {
142 final Intent intent = new Intent().setClassName(AboutActivity.class
143 .getPackage().getName(), AboutActivity.class.getCanonicalName());
144 context.startActivity(intent);
149 final MenuItem help = menu.add(getString(R.string.help));
150 help.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
151 help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
152 public boolean onMenuItemClick(final MenuItem menuItem) {
153 context.startActivity(HtmlDisplayActivity.getHelpLaunchIntent());
158 final MenuItem preferences = menu.add(getString(R.string.settings));
159 preferences.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
160 preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
161 public boolean onMenuItemClick(final MenuItem menuItem) {
162 PreferenceActivity.prefsMightHaveChanged = true;
163 final Intent intent = new Intent().setClassName(PreferenceActivity.class
164 .getPackage().getName(), PreferenceActivity.class.getCanonicalName());
165 context.startActivity(intent);
171 final MenuItem reportIssue = menu.add(getString(R.string.reportIssue));
172 reportIssue.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
173 reportIssue.setOnMenuItemClickListener(new OnMenuItemClickListener() {
174 public boolean onMenuItemClick(final MenuItem menuItem) {
175 final Intent intent = new Intent(Intent.ACTION_VIEW);
176 intent.setData(Uri.parse("http://code.google.com/p/quickdic-dictionary/issues/entry"));
177 context.startActivity(intent);
183 public synchronized File getDictDir() {
184 // This metaphore doesn't work, because we've already reset prefsMightHaveChanged.
185 // if (dictDir == null || PreferenceActivity.prefsMightHaveChanged) {
186 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
187 final String dir = prefs.getString(getString(R.string.quickdicDirectoryKey), getString(R.string.quickdicDirectoryDefault));
188 dictDir = new File(dir);
194 public C.Theme getSelectedTheme() {
195 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
196 final String theme = prefs.getString(getString(R.string.themeKey), "themeLight");
197 if (theme.equals("themeLight")) {
198 return C.Theme.LIGHT;
200 return C.Theme.DEFAULT;
204 public File getPath(String uncompressedFilename) {
205 return new File(getDictDir(), uncompressedFilename);
209 String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
210 String defaultLangName = null;
211 final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
213 public String isoCodeToLocalizedLanguageName(final String isoCode) {
214 final Language.LanguageResources languageResources = Language.isoCodeToResources.get(isoCode);
215 final String lang = languageResources != null ? getApplicationContext().getString(languageResources.nameId) : isoCode;
219 public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
220 // Hack to put the default locale first in the name.
221 if (indexInfos.size() > 1 &&
222 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
223 List<IndexInfo> result = new ArrayList<DictionaryInfo.IndexInfo>(indexInfos);
224 ListUtil.swap(result, 0, 1);
231 public synchronized String getDictionaryName(final String uncompressedFilename) {
232 final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
233 if (!currentLocale.equals(defaultLangISO2)) {
234 defaultLangISO2 = currentLocale;
235 fileToNameCache.clear();
236 defaultLangName = null;
238 if (defaultLangName == null) {
239 defaultLangName = isoCodeToLocalizedLanguageName(defaultLangISO2);
242 String name = fileToNameCache.get(uncompressedFilename);
247 final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);
248 if (dictionaryInfo != null) {
249 final StringBuilder nameBuilder = new StringBuilder();
251 List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
252 for (int i = 0; i < sortedIndexInfos.size(); ++i) {
254 nameBuilder.append("-");
256 nameBuilder.append(isoCodeToLocalizedLanguageName(sortedIndexInfos.get(i).shortName));
258 name = nameBuilder.toString();
260 name = uncompressedFilename.replace(".quickdic", "");
262 fileToNameCache.put(uncompressedFilename, name);
266 public View createButton(final Context context, final DictionaryInfo dictionaryInfo,
267 final IndexInfo indexInfo) {
268 LanguageResources languageResources = Language.isoCodeToResources.get(indexInfo.shortName);
270 if (languageResources == null || languageResources.flagId <= 0) {
271 Button button = new Button(context);
272 button.setText(indexInfo.shortName);
275 ImageButton button = new ImageButton(context);
276 button.setImageResource(languageResources.flagId);
277 button.setScaleType(ScaleType.FIT_CENTER);
280 result.setOnClickListener(
281 new IntentLauncher(context,
282 DictionaryActivity.getLaunchIntent(getPath(dictionaryInfo.uncompressedFilename), indexInfo.shortName, "")));
287 public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
288 dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
289 dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
290 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
293 public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
294 while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {};
295 dictionaryConfig.uncompressedFilenameToDictionaryInfo.remove(dictionaryInfo.uncompressedFilename);
296 getPath(dictionaryInfo.uncompressedFilename).delete();
297 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
300 final Collator collator = Collator.getInstance();
301 final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
303 public int compare(String uncompressedFilename1, String uncompressedFilename2) {
304 final String name1 = getDictionaryName(uncompressedFilename1);
305 final String name2 = getDictionaryName(uncompressedFilename2);
306 if (defaultLangName.length() > 0) {
307 if (name1.startsWith(defaultLangName + "-") && !name2.startsWith(defaultLangName + "-")) {
309 } else if (name2.startsWith(defaultLangName + "-") && !name1.startsWith(defaultLangName + "-")) {
313 return collator.compare(name1, name2);
316 final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
318 public int compare(DictionaryInfo d1, DictionaryInfo d2) {
319 // Single-index dictionaries first.
320 if (d1.indexInfos.size() != d2.indexInfos.size()) {
321 return d1.indexInfos.size() - d2.indexInfos.size();
323 return uncompressedFilenameComparator.compare(d1.uncompressedFilename, d2.uncompressedFilename);
327 public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
328 new Thread(new Runnable() {
331 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
333 oldDictionaryConfig.dictionaryFilesOrdered.addAll(dictionaryConfig.dictionaryFilesOrdered);
335 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
336 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
337 final File dictFile = getPath(uncompressedFilename);
338 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
339 if (dictionaryInfo != null) {
340 newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
341 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(uncompressedFilename, dictionaryInfo);
345 // Are there dictionaries on the device that we didn't know about already?
346 // Pick them up and put them at the end of the list.
347 final List<String> toAddSorted = new ArrayList<String>();
348 final File[] dictDirFiles = getDictDir().listFiles();
349 if (dictDirFiles != null) {
350 for (final File file : dictDirFiles) {
351 if (file.getName().endsWith(".zip")) {
352 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.containsKey(file.getName().replace(".zip", ""))) {
356 if (!file.getName().endsWith(".quickdic")) {
359 if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo.containsKey(file.getName())) {
360 // We have it in our list already.
363 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
364 if (dictionaryInfo == null) {
365 Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
369 toAddSorted.add(file.getName());
370 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(file.getName(), dictionaryInfo);
373 Log.w(LOG, "dictDir is not a diretory: " + getDictDir().getPath());
375 if (!toAddSorted.isEmpty()) {
376 Collections.sort(toAddSorted, uncompressedFilenameComparator);
377 newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
380 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
381 synchronized (this) {
382 dictionaryConfig = newDictionaryConfig;
386 onUpdateFinished.run();
387 } catch (Exception e) {
388 Log.e(LOG, "Exception running callback.", e);
393 public synchronized List<DictionaryInfo> getDictionariesOnDevice() {
394 final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(dictionaryConfig.dictionaryFilesOrdered.size());
395 for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
396 final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo.get(uncompressedFilename);
397 if (dictionaryInfo != null) {
398 result.add(dictionaryInfo);
404 public synchronized List<DictionaryInfo> getAllDictionaries() {
405 final List<DictionaryInfo> result = getDictionariesOnDevice();
407 // The downloadable ones.
408 final Map<String,DictionaryInfo> remaining = new LinkedHashMap<String, DictionaryInfo>(DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
409 remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
410 final List<DictionaryInfo> toAddSorted = new ArrayList<DictionaryInfo>(remaining.values());
411 Collections.sort(toAddSorted, dictionaryInfoComparator);
412 result.addAll(toAddSorted);
417 public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
418 return dictionaryConfig.uncompressedFilenameToDictionaryInfo.get(uncompressedFilename) != null;
421 public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
422 final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(dictionaryInfo.uncompressedFilename);
423 return downloadable != null && downloadable.creationMillis > dictionaryInfo.creationMillis;
426 public DictionaryInfo getDownloadable(final String uncompressedFilename) {
427 final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);