]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryApplication.java
Got the flags set to a reasonable size.
[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 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;
33
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;
46
47 import java.io.BufferedReader;
48 import java.io.File;
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;
58 import java.util.Map;
59
60 public class DictionaryApplication extends Application {
61   
62   static final String LOG = "QuickDicApp";
63   
64   // Static, determined by resources (and locale).
65   // Unordered.
66   static Map<String,DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
67   
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>();
72     
73     final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new LinkedHashMap<String, DictionaryInfo>();
74   }
75   DictionaryConfig dictionaryConfig = null;
76   
77   
78   int languageButtonPixels = 22;
79
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>();
84 //  }
85 //  DictionaryHistory dictionaryHistory = null;
86   
87   static synchronized void staticInit(final Context context) {
88     if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
89       return;
90     }
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)));
94     try {
95       String line;
96       while ((line = reader.readLine()) != null) {
97         if (line.startsWith("#") || line.length() == 0) {
98           continue;
99         }
100         final DictionaryInfo dictionaryInfo = new DictionaryInfo(line);
101         DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
102                 dictionaryInfo.uncompressedFilename, dictionaryInfo);
103       }
104       reader.close();
105     } catch (IOException e) {
106       Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
107     }
108   }
109
110   
111   private File dictDir;
112
113   @Override
114   public void onCreate() {
115     super.onCreate();
116     Log.d("QuickDic", "Application: onCreate");
117     TransliteratorManager.init(null);
118     staticInit(getApplicationContext());
119     
120     languageButtonPixels = (int) TypedValue.applyDimension(
121             TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics());
122
123     
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();
129     }
130     
131     // Theme stuff.
132     setTheme(getSelectedTheme().themeId);
133     final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
134     prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
135       @Override
136       public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
137           String key) {
138         Log.d("QuickDic", "prefs changed: " + key);
139         if (key.equals(getString(R.string.themeKey))) {
140           setTheme(getSelectedTheme().themeId);
141         }
142       }
143     });
144   }
145   
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);
155         return false;
156       }
157     });
158
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());
164         return false;
165       }
166     });
167
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);
176         return false;
177       }
178     });
179     
180     
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);
188         return false;
189       }
190     });
191   }
192   
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);
199       dictDir.mkdirs();
200 //    }
201     return dictDir;
202   }
203   
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;
209     } else {
210       return C.Theme.DEFAULT;
211     }
212   }
213     
214   public File getPath(String uncompressedFilename) {
215     return new File(getDictDir(), uncompressedFilename);
216   }
217   
218
219   String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
220   String defaultLangName = null;
221   final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
222
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;
226     return lang;
227   }
228   
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);
235         return result;
236       }
237       return indexInfos;
238   }
239   
240
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;
247     }
248     if (defaultLangName == null) {
249       defaultLangName = isoCodeToLocalizedLanguageName(defaultLangISO2);
250     }
251     
252     String name = fileToNameCache.get(uncompressedFilename);
253     if (name != null) {
254       return name;
255     }
256     
257     final DictionaryInfo dictionaryInfo = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);
258     if (dictionaryInfo != null) {
259       final StringBuilder nameBuilder = new StringBuilder();
260
261       List<IndexInfo> sortedIndexInfos = sortedIndexInfos(dictionaryInfo.indexInfos);
262       for (int i = 0; i < sortedIndexInfos.size(); ++i) {
263         if (i > 0) {
264           nameBuilder.append("-");
265         }
266         nameBuilder.append(isoCodeToLocalizedLanguageName(sortedIndexInfos.get(i).shortName));
267       }
268       name = nameBuilder.toString();
269     } else {
270       name = uncompressedFilename.replace(".quickdic", "");
271     }
272     fileToNameCache.put(uncompressedFilename, name);
273     return name;
274   }
275   
276   public View createButton(final Context context, final DictionaryInfo dictionaryInfo,
277           final IndexInfo indexInfo) {
278       LanguageResources languageResources = Language.isoCodeToResources.get(indexInfo.shortName);
279       View result;
280             
281       if (languageResources == null || languageResources.flagId <= 0) {
282           Button button = new Button(context);
283           button.setText(indexInfo.shortName);
284           result = button;
285       } else {
286           ImageButton button = new ImageButton(context);
287           button.setImageResource(languageResources.flagId);
288           button.setScaleType(ScaleType.FIT_CENTER);
289           result = button;
290       }
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));
297       return result;
298   }
299
300
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);
305   }
306
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);
312   }
313
314   final Collator collator = Collator.getInstance();
315   final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
316     @Override
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 + "-")) {
322           return -1;
323         } else if (name2.startsWith(defaultLangName + "-") && !name1.startsWith(defaultLangName + "-")) {
324           return 1;
325         }
326       }
327       return collator.compare(name1, name2);
328     }
329   };
330   final Comparator<DictionaryInfo> dictionaryInfoComparator = new Comparator<DictionaryInfo>() {
331     @Override
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();
336       }
337       return uncompressedFilenameComparator.compare(d1.uncompressedFilename, d2.uncompressedFilename);
338     }
339   };
340   
341   public void backgroundUpdateDictionaries(final Runnable onUpdateFinished) {
342     new Thread(new Runnable() {
343       @Override
344       public void run() {
345         final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
346         synchronized(this) {
347           oldDictionaryConfig.dictionaryFilesOrdered.addAll(dictionaryConfig.dictionaryFilesOrdered);
348         }
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);
356           }
357         }
358         
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", ""))) {
367                 file.delete();
368               }
369             }
370             if (!file.getName().endsWith(".quickdic")) {
371               continue;
372             }
373             if (newDictionaryConfig.uncompressedFilenameToDictionaryInfo.containsKey(file.getName())) {
374               // We have it in our list already.
375               continue;
376             }
377             final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
378             if (dictionaryInfo == null) {
379               Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
380               continue;
381             }
382             
383             toAddSorted.add(file.getName());
384             newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(file.getName(), dictionaryInfo);
385           }
386         } else {
387           Log.w(LOG, "dictDir is not a diretory: " + getDictDir().getPath());
388         }
389         if (!toAddSorted.isEmpty()) {
390           Collections.sort(toAddSorted, uncompressedFilenameComparator);
391           newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
392         }
393
394         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
395         synchronized (this) {
396           dictionaryConfig = newDictionaryConfig;
397         }
398         
399         try {
400           onUpdateFinished.run();
401         } catch (Exception e) {
402           Log.e(LOG, "Exception running callback.", e);
403         }
404       }}).start();
405   }
406
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);
413       }
414     }
415     return result;
416   }
417   
418   public List<DictionaryInfo> getDownloadableDictionaries() {
419       final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(dictionaryConfig.dictionaryFilesOrdered.size());
420       
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);
427       
428       return result;
429   }
430   
431   public synchronized boolean isDictionaryOnDevice(String uncompressedFilename) {
432     return dictionaryConfig.uncompressedFilenameToDictionaryInfo.get(uncompressedFilename) != null;
433   }
434
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;
438   }
439
440   public DictionaryInfo getDownloadable(final String uncompressedFilename) {
441     final DictionaryInfo downloadable = DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.get(uncompressedFilename);
442     return downloadable;
443   }
444
445 }