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.util.TypedValue;
26 import android.view.View;
27 import android.view.View.OnClickListener;
28 import android.view.ViewGroup.LayoutParams;
29 import android.widget.Button;
30 import android.widget.ImageButton;
31 import android.widget.ImageView.ScaleType;
32 import android.widget.LinearLayout;
34 import com.actionbarsherlock.view.Menu;
35 import com.actionbarsherlock.view.MenuItem;
36 import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
37 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
38 import com.hughes.android.dictionary.engine.Dictionary;
39 import com.hughes.android.dictionary.engine.Language;
40 import com.hughes.android.dictionary.engine.TransliteratorManager;
41 import com.hughes.android.dictionary.engine.Language.LanguageResources;
42 import com.hughes.android.util.IntentLauncher;
43 import com.hughes.android.util.PersistentObjectCache;
44 import com.hughes.util.ListUtil;
45 import com.ibm.icu.text.Collator;
47 import java.io.BufferedReader;
49 import java.io.IOException;
50 import java.io.InputStreamReader;
51 import java.io.Serializable;
52 import java.util.ArrayList;
53 import java.util.Collections;
54 import java.util.Comparator;
55 import java.util.LinkedHashMap;
56 import java.util.List;
57 import java.util.Locale;
60 public class DictionaryApplication extends Application {
62 static final String LOG = "QuickDicApp";
64 // Static, determined by resources (and locale).
66 static Map<String,DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
68 static final class DictionaryConfig implements Serializable {
69 private static final long serialVersionUID = -1444177164708201263L;
70 // User-ordered list, persisted, just the ones that are/have been present.
71 final List<String> dictionaryFilesOrdered = new ArrayList<String>();
73 final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new LinkedHashMap<String, DictionaryInfo>();
75 DictionaryConfig dictionaryConfig = null;
78 int languageButtonPixels = 22;
80 // static final class DictionaryHistory implements Serializable {
81 // private static final long serialVersionUID = -4842995032541390284L;
82 // // User-ordered list, persisted, just the ones that are/have been present.
83 // final List<DictionaryLink> dictionaryLinks = new ArrayList<DictionaryLink>();
85 // DictionaryHistory dictionaryHistory = null;
87 static synchronized void staticInit(final Context context) {
88 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
91 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new LinkedHashMap<String,DictionaryInfo>();
92 final BufferedReader reader = new BufferedReader(
93 new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
96 while ((line = reader.readLine()) != null) {
97 if (line.startsWith("#") || line.length() == 0) {
100 final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
101 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
102 dictionaryInfo.uncompressedFilename, dictionaryInfo);
105 } catch (IOException e) {
106 Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
111 private File dictDir;
114 public void onCreate() {
116 Log.d("QuickDic", "Application: onCreate");
117 TransliteratorManager.init(null);
118 staticInit(getApplicationContext());
120 languageButtonPixels = (int) TypedValue.applyDimension(
121 TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics());
124 // Load the dictionaries we know about.
125 dictionaryConfig = PersistentObjectCache.init(getApplicationContext()).read(
126 C.DICTIONARY_CONFIGS, DictionaryConfig.class);
127 if (dictionaryConfig == null) {
128 dictionaryConfig = new DictionaryConfig();
132 setTheme(getSelectedTheme().themeId);
133 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
134 prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
136 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
138 Log.d("QuickDic", "prefs changed: " + key);
139 if (key.equals(getString(R.string.themeKey))) {
140 setTheme(getSelectedTheme().themeId);
146 public void onCreateGlobalOptionsMenu(
147 final Context context, final Menu menu) {
148 final MenuItem about = menu.add(getString(R.string.about));
149 about.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
150 about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
151 public boolean onMenuItemClick(final MenuItem menuItem) {
152 final Intent intent = new Intent().setClassName(AboutActivity.class
153 .getPackage().getName(), AboutActivity.class.getCanonicalName());
154 context.startActivity(intent);
159 final MenuItem help = menu.add(getString(R.string.help));
160 help.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
161 help.setOnMenuItemClickListener(new OnMenuItemClickListener() {
162 public boolean onMenuItemClick(final MenuItem menuItem) {
163 context.startActivity(HtmlDisplayActivity.getHelpLaunchIntent());
168 final MenuItem preferences = menu.add(getString(R.string.settings));
169 preferences.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
170 preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
171 public boolean onMenuItemClick(final MenuItem menuItem) {
172 PreferenceActivity.prefsMightHaveChanged = true;
173 final Intent intent = new Intent().setClassName(PreferenceActivity.class
174 .getPackage().getName(), PreferenceActivity.class.getCanonicalName());
175 context.startActivity(intent);
181 final MenuItem reportIssue = menu.add(getString(R.string.reportIssue));
182 reportIssue.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
183 reportIssue.setOnMenuItemClickListener(new OnMenuItemClickListener() {
184 public boolean onMenuItemClick(final MenuItem menuItem) {
185 final Intent intent = new Intent(Intent.ACTION_VIEW);
186 intent.setData(Uri.parse("http://code.google.com/p/quickdic-dictionary/issues/entry"));
187 context.startActivity(intent);
193 public synchronized File getDictDir() {
194 // This metaphore doesn't work, because we've already reset prefsMightHaveChanged.
195 // if (dictDir == null || PreferenceActivity.prefsMightHaveChanged) {
196 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
197 final String dir = prefs.getString(getString(R.string.quickdicDirectoryKey), getString(R.string.quickdicDirectoryDefault));
198 dictDir = new File(dir);
204 public C.Theme getSelectedTheme() {
205 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
206 final String theme = prefs.getString(getString(R.string.themeKey), "themeLight");
207 if (theme.equals("themeLight")) {
208 return C.Theme.LIGHT;
210 return C.Theme.DEFAULT;
214 public File getPath(String uncompressedFilename) {
215 return new File(getDictDir(), uncompressedFilename);
219 String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
220 String defaultLangName = null;
221 final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
223 public String isoCodeToLocalizedLanguageName(final String isoCode) {
224 final Language.LanguageResources languageResources = Language.isoCodeToResources.get(isoCode);
225 final String lang = languageResources != null ? getApplicationContext().getString(languageResources.nameId) : isoCode;
229 public List<IndexInfo> sortedIndexInfos(List<IndexInfo> indexInfos) {
230 // Hack to put the default locale first in the name.
231 if (indexInfos.size() > 1 &&
232 indexInfos.get(1).shortName.toLowerCase().equals(defaultLangISO2)) {
233 List<IndexInfo> result = new ArrayList<DictionaryInfo.IndexInfo>(indexInfos);
234 ListUtil.swap(result, 0, 1);
241 public synchronized String getDictionaryName(final String uncompressedFilename) {
242 final String currentLocale = Locale.getDefault().getLanguage().toLowerCase();
243 if (!currentLocale.equals(defaultLangISO2)) {
244 defaultLangISO2 = currentLocale;
245 fileToNameCache.clear();
246 defaultLangName = null;
248 if (defaultLangName == null) {
249 defaultLangName = isoCodeToLocalizedLanguageName(defaultLangISO2);
252 String name = fileToNameCache.get(uncompressedFilename);
257 final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);
258 if (dictionaryInfo != null) {
259 final StringBuilder nameBuilder = new StringBuilder();
261 List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
262 for (int i = 0; i < sortedIndexInfos.size(); ++i) {
264 nameBuilder.append("-");
266 nameBuilder.append(isoCodeToLocalizedLanguageName(sortedIndexInfos.get(i).shortName));
268 name = nameBuilder.toString();
270 name = uncompressedFilename.replace(".quickdic", "");
272 fileToNameCache.put(uncompressedFilename, name);
276 public View createButton(final Context context, final DictionaryInfo dictionaryInfo,
277 final IndexInfo indexInfo) {
278 LanguageResources languageResources = Language.isoCodeToResources.get(indexInfo.shortName);
281 if (languageResources == null || languageResources.flagId <= 0) {
282 Button button = new Button(context);
283 button.setText(indexInfo.shortName);
286 ImageButton button = new ImageButton(context);
287 button.setImageResource(languageResources.flagId);
288 button.setScaleType(ScaleType.FIT_CENTER);
291 result.setMinimumWidth(languageButtonPixels);
292 result.setMinimumHeight(languageButtonPixels * 2 / 3);
293 result.setOnClickListener(
294 new IntentLauncher(context,
295 DictionaryActivity.getLaunchIntent(getPath(dictionaryInfo.uncompressedFilename), indexInfo.shortName, "")));
296 // result.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
301 public synchronized void moveDictionaryToTop(final DictionaryInfo dictionaryInfo) {
302 dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename);
303 dictionaryConfig.dictionaryFilesOrdered.add(0, dictionaryInfo.uncompressedFilename);
304 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
307 public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
308 while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {};
309 dictionaryConfig.uncompressedFilenameToDictionaryInfo.remove(dictionaryInfo.uncompressedFilename);
310 getPath(dictionaryInfo.uncompressedFilename).delete();
311 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
314 final Collator collator = Collator.getInstance();
315 final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
317 public int compare(String uncompressedFilename1, String uncompressedFilename2) {
318 final String name1 = getDictionaryName(uncompressedFilename1);
319 final String name2 = getDictionaryName(uncompressedFilename2);
320 if (defaultLangName.length() > 0) {
321 if (name1.startsWith(defaultLangName + "-") && !name2.startsWith(defaultLangName + "-")) {
323 } else if (name2.startsWith(defaultLangName + "-") && !name1.startsWith(defaultLangName + "-")) {
327 return collator.compare(name1, name2);
330 final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
332 public int compare(DictionaryInfo d1, DictionaryInfo d2) {
333 // Single-index dictionaries first.
334 if (d1.indexInfos.size() != d2.indexInfos.size()) {
335 return d1.indexInfos.size() - d2.indexInfos.size();
337 return uncompressedFilenameComparator.compare(d1.uncompressedFilename, d2.uncompressedFilename);
341 public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
342 new Thread(new Runnable() {
345 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
347 oldDictionaryConfig.dictionaryFilesOrdered.addAll(dictionaryConfig.dictionaryFilesOrdered);
349 final DictionaryConfig newDictionaryConfig = new DictionaryConfig();
350 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
351 final File dictFile = getPath(uncompressedFilename);
352 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
353 if (dictionaryInfo != null) {
354 newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
355 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(uncompressedFilename, dictionaryInfo);
359 // Are there dictionaries on the device that we didn't know about already?
360 // Pick them up and put them at the end of the list.
361 final List<String> toAddSorted = new ArrayList<String>();
362 final File[] dictDirFiles = getDictDir().listFiles();
363 if (dictDirFiles != null) {
364 for (final File file : dictDirFiles) {
365 if (file.getName().endsWith(".zip")) {
366 if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.containsKey(file.getName().replace(".zip", ""))) {
370 if (!file.getName().endsWith(".quickdic")) {
373 if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo.containsKey(file.getName())) {
374 // We have it in our list already.
377 final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
378 if (dictionaryInfo == null) {
379 Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
383 toAddSorted.add(file.getName());
384 newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(file.getName(), dictionaryInfo);
387 Log.w(LOG, "dictDir is not a diretory: " + getDictDir().getPath());
389 if (!toAddSorted.isEmpty()) {
390 Collections.sort(toAddSorted, uncompressedFilenameComparator);
391 newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
394 PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
395 synchronized (this) {
396 dictionaryConfig = newDictionaryConfig;
400 onUpdateFinished.run();
401 } catch (Exception e) {
402 Log.e(LOG, "Exception running callback.", e);
407 public synchronized List<DictionaryInfo> getDictionariesOnDevice() {
408 final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(dictionaryConfig.dictionaryFilesOrdered.size());
409 for (final String uncompressedFilename : dictionaryConfig.dictionaryFilesOrdered) {
410 final DictionaryInfo dictionaryInfo = dictionaryConfig.uncompressedFilenameToDictionaryInfo.get(uncompressedFilename);
411 if (dictionaryInfo != null) {
412 result.add(dictionaryInfo);
418 public List<DictionaryInfo> getDownloadableDictionaries() {
419 final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(dictionaryConfig.dictionaryFilesOrdered.size());
421 // The downloadable ones.
422 final Map<String,DictionaryInfo> remaining = new LinkedHashMap<String, DictionaryInfo>(DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
423 remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
424 final List<DictionaryInfo> toAddSorted = new ArrayList<DictionaryInfo>(remaining.values());
425 Collections.sort(toAddSorted, dictionaryInfoComparator);
426 result.addAll(toAddSorted);
431 public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
432 return dictionaryConfig.uncompressedFilenameToDictionaryInfo.get(uncompressedFilename) != null;
435 public boolean updateAvailable(final DictionaryInfo dictionaryInfo) {
436 final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(dictionaryInfo.uncompressedFilename);
437 return downloadable != null && downloadable.creationMillis > dictionaryInfo.creationMillis;
440 public DictionaryInfo getDownloadable(final String uncompressedFilename) {
441 final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);