]> gitweb.fperrin.net Git - Dictionary.git/blobdiff - src/com/hughes/android/dictionary/DictionaryApplication.java
List files only once, also avoids a potential race condition.
[Dictionary.git] / src / com / hughes / android / dictionary / DictionaryApplication.java
index 24fe0b405e7b9b619a665a4aa095c37180d885b1..1e46f4b0c1adb87b8bd25e9d1d82768dfc7a7143 100644 (file)
@@ -33,6 +33,7 @@ import android.view.View;
 import android.widget.Button;
 import android.widget.ImageButton;
 import android.widget.ImageView.ScaleType;
+import android.widget.LinearLayout;
 import android.widget.Toast;
 
 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
@@ -42,7 +43,7 @@ import com.hughes.android.dictionary.engine.Language.LanguageResources;
 import com.hughes.android.dictionary.engine.TransliteratorManager;
 import com.hughes.android.util.PersistentObjectCache;
 import com.hughes.util.ListUtil;
-import com.ibm.icu.text.Collator;
+import java.text.Collator;
 
 import java.io.BufferedReader;
 import java.io.File;
@@ -52,7 +53,7 @@ import java.io.Serializable;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
-import java.util.LinkedHashMap;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
@@ -61,6 +62,16 @@ public class DictionaryApplication extends Application {
 
     static final String LOG = "QuickDicApp";
 
+    // If set to false, avoid use of ICU collator
+    // Works well enough for most european languages,
+    // gives faster startup and avoids crashes on some
+    // devices due to Dalvik bugs (e.g. ARMv6, S5570i, CM11)
+    // when using ICU4J.
+    // Leave it enabled by default for correctness except
+    // for my known broken development/performance test device config.
+    //static public final boolean USE_COLLATOR = !android.os.Build.FINGERPRINT.equals("Samsung/cm_tassve/tassve:4.4.4/KTU84Q/20150211:userdebug/release-keys");
+    static public final boolean USE_COLLATOR = true;
+
     // Static, determined by resources (and locale).
     // Unordered.
     static Map<String, DictionaryInfo> DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = null;
@@ -102,7 +113,7 @@ public class DictionaryApplication extends Application {
 
     // Useful:
     // http://www.loc.gov/standards/iso639-2/php/code_list.php
-    public static final Map<String, LanguageResources> isoCodeToResources = new LinkedHashMap<String, LanguageResources>();
+    public static final Map<String, LanguageResources> isoCodeToResources = new HashMap<String, LanguageResources>();
     static {
         isoCodeToResources.put("AF", new LanguageResources("Afrikaans", R.string.AF,
                 R.drawable.flag_of_south_africa));
@@ -265,14 +276,14 @@ public class DictionaryApplication extends Application {
 
     }
 
-    static final class DictionaryConfig implements Serializable {
+    public static final class DictionaryConfig implements Serializable {
         private static final long serialVersionUID = -1444177164708201263L;
         // User-ordered list, persisted, just the ones that are/have been
         // present.
         final List<String> dictionaryFilesOrdered = new ArrayList<String>();
 
-        final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new LinkedHashMap<String, DictionaryInfo>();
-        
+        final Map<String, DictionaryInfo> uncompressedFilenameToDictionaryInfo = new HashMap<String, DictionaryInfo>();
+
         /**
          * Sometimes a deserialized version of this data structure isn't valid.
          * @return
@@ -290,7 +301,7 @@ public class DictionaryApplication extends Application {
         if (DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO != null) {
             return;
         }
-        DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new LinkedHashMap<String, DictionaryInfo>();
+        DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO = new HashMap<String, DictionaryInfo>();
         final BufferedReader reader = new BufferedReader(
                 new InputStreamReader(context.getResources().openRawResource(R.raw.dictionary_info)));
         try {
@@ -303,10 +314,10 @@ public class DictionaryApplication extends Application {
                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO.put(
                         dictionaryInfo.uncompressedFilename, dictionaryInfo);
             }
-            reader.close();
         } catch (IOException e) {
             Log.e(LOG, "Failed to load downloadable dictionary lists.", e);
         }
+        try { reader.close(); } catch (IOException e) {}
     }
 
     private File dictDir;
@@ -391,35 +402,61 @@ public class DictionaryApplication extends Application {
         });
     }
 
+    private String selectDefaultDir() {
+        final File defaultDictDir = new File(Environment.getExternalStorageDirectory(), "quickDic");
+        String dir = defaultDictDir.getAbsolutePath();
+        File dictDir = new File(dir);
+        String[] fileList = dictDir.isDirectory() ? dictDir.list() : null;
+        if (fileList != null && fileList.length > 0) {
+            return dir;
+        }
+        File efd = null;
+        try {
+            efd = getApplicationContext().getExternalFilesDir(null);
+        } catch (Exception e) {
+        }
+        if (efd != null) {
+            efd.mkdirs();
+            if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+                getApplicationContext().getExternalFilesDirs(null);
+            }
+            if (efd.isDirectory() && efd.canWrite() && checkFileCreate(efd)) {
+                return efd.getAbsolutePath();
+            }
+        }
+        if (!dictDir.isDirectory() && !dictDir.mkdirs()) {
+            return getApplicationContext().getFilesDir().getAbsolutePath();
+        }
+        return dir;
+    }
+
     public synchronized File getDictDir() {
         // This metaphor doesn't work, because we've already reset
         // prefsMightHaveChanged.
         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
         String dir = prefs.getString(getString(R.string.quickdicDirectoryKey), "");
         if (dir.isEmpty()) {
-            final File defaultDictDir = new File(Environment.getExternalStorageDirectory(), "quickDic");
-            dir = defaultDictDir.getAbsolutePath();
+            dir = selectDefaultDir();
         }
         dictDir = new File(dir);
         dictDir.mkdirs();
         if (!dictDir.isDirectory() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
              getApplicationContext().getExternalFilesDirs(null);
         }
-        if (!dictDir.isDirectory() || !dictDir.canWrite()) {
-            String dirs = " " + Environment.getExternalStorageDirectory();
-            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
-                File[] files = getApplicationContext().getExternalFilesDirs(null);
-                for (File f : files) {
-                    dirs += " " + f.getAbsolutePath();
-                }
-            } else {
-                dirs += " " + getApplicationContext().getExternalFilesDir(null).getAbsolutePath();
-            }
-            Toast.makeText(getApplicationContext(), "Chosen directory not writeable, try one of" + dirs, Toast.LENGTH_LONG).show();
-        }
         return dictDir;
     }
 
+    static public boolean checkFileCreate(File dir) {
+        boolean res = false;
+        File testfile = new File(dir, "quickdic_writetest");
+        try {
+            testfile.delete();
+            res = testfile.createNewFile() & testfile.delete();
+        } catch (Exception e) {
+        }
+        return res;
+    }
+
     public File getWordListFile() {
         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
         String file = prefs.getString(getString(R.string.wordListFileKey), "");
@@ -445,7 +482,7 @@ public class DictionaryApplication extends Application {
 
     String defaultLangISO2 = Locale.getDefault().getLanguage().toLowerCase();
     String defaultLangName = null;
-    final Map<String, String> fileToNameCache = new LinkedHashMap<String, String>();
+    final Map<String, String> fileToNameCache = new HashMap<String, String>();
 
     public String isoCodeToLocalizedLanguageName(final String isoCode) {
         final Language.LanguageResources languageResources = isoCodeToResources
@@ -518,10 +555,7 @@ public class DictionaryApplication extends Application {
             button.setScaleType(ScaleType.FIT_CENTER);
             result = button;
         }
-        result.setMinimumWidth(languageButtonPixels);
-        result.setMinimumHeight(languageButtonPixels * 2 / 3);
-        // result.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
-        // LayoutParams.WRAP_CONTENT));
+        result.setLayoutParams(new LinearLayout.LayoutParams(languageButtonPixels, languageButtonPixels * 2 / 3));
         return result;
     }
 
@@ -531,6 +565,11 @@ public class DictionaryApplication extends Application {
         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
     }
 
+    public synchronized void sortDictionaries() {
+        Collections.sort(dictionaryConfig.dictionaryFilesOrdered, uncompressedFilenameComparator);
+        PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
+    }
+
     public synchronized void deleteDictionary(final DictionaryInfo dictionaryInfo) {
         while (dictionaryConfig.dictionaryFilesOrdered.remove(dictionaryInfo.uncompressedFilename)) {
         }
@@ -540,7 +579,7 @@ public class DictionaryApplication extends Application {
         PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, dictionaryConfig);
     }
 
-    final Collator collator = Collator.getInstance();
+    final Comparator collator = USE_COLLATOR ? Collator.getInstance() : String.CASE_INSENSITIVE_ORDER;
     final Comparator<String> uncompressedFilenameComparator = new Comparator<String>() {
         @Override
         public int compare(String uncompressedFilename1, String uncompressedFilename2) {
@@ -575,7 +614,7 @@ public class DictionaryApplication extends Application {
             @Override
             public void run() {
                 final DictionaryConfig oldDictionaryConfig = new DictionaryConfig();
-                synchronized (this) {
+                synchronized (DictionaryApplication.this) {
                     oldDictionaryConfig.dictionaryFilesOrdered
                             .addAll(dictionaryConfig.dictionaryFilesOrdered);
                 }
@@ -583,7 +622,7 @@ public class DictionaryApplication extends Application {
                 for (final String uncompressedFilename : oldDictionaryConfig.dictionaryFilesOrdered) {
                     final File dictFile = getPath(uncompressedFilename);
                     final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(dictFile);
-                    if (dictionaryInfo != null) {
+                    if (dictionaryInfo.isValid() || dictFile.exists()) {
                         newDictionaryConfig.dictionaryFilesOrdered.add(uncompressedFilename);
                         newDictionaryConfig.uncompressedFilenameToDictionaryInfo.put(
                                 uncompressedFilename, dictionaryInfo);
@@ -612,9 +651,8 @@ public class DictionaryApplication extends Application {
                             continue;
                         }
                         final DictionaryInfo dictionaryInfo = Dictionary.getDictionaryInfo(file);
-                        if (dictionaryInfo == null) {
+                        if (!dictionaryInfo.isValid()) {
                             Log.e(LOG, "Unable to parse dictionary: " + file.getPath());
-                            continue;
                         }
 
                         toAddSorted.add(file.getName());
@@ -629,9 +667,14 @@ public class DictionaryApplication extends Application {
                     newDictionaryConfig.dictionaryFilesOrdered.addAll(toAddSorted);
                 }
 
-                PersistentObjectCache.getInstance()
-                        .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
-                synchronized (this) {
+                try {
+                    PersistentObjectCache.getInstance()
+                                 .write(C.DICTIONARY_CONFIGS, newDictionaryConfig);
+                } catch (Exception e) {
+                    Log.e(LOG, "Failed persisting dictionary configs", e);
+                }
+
+                synchronized (DictionaryApplication.this) {
                     dictionaryConfig = newDictionaryConfig;
                 }
 
@@ -674,7 +717,7 @@ public class DictionaryApplication extends Application {
         final List<DictionaryInfo> result = new ArrayList<DictionaryInfo>(
                 dictionaryConfig.dictionaryFilesOrdered.size());
 
-        final Map<String, DictionaryInfo> remaining = new LinkedHashMap<String, DictionaryInfo>(
+        final Map<String, DictionaryInfo> remaining = new HashMap<String, DictionaryInfo>(
                 DOWNLOADABLE_UNCOMPRESSED_FILENAME_NAME_TO_DICTIONARY_INFO);
         remaining.keySet().removeAll(dictionaryConfig.dictionaryFilesOrdered);
         for (final DictionaryInfo dictionaryInfo : remaining.values()) {