diff --git a/build.gradle b/build.gradle index e70e401a..fb5ca7ef 100644 --- a/build.gradle +++ b/build.gradle @@ -3,7 +3,7 @@ buildscript { mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:0.13.2' + classpath 'com.android.tools.build:gradle:0.14.0' } } apply plugin: 'android' diff --git a/res/drawable-hdpi/btn_circle_disable.png b/res/drawable-hdpi/btn_circle_disable.png new file mode 100644 index 00000000..917bc284 Binary files /dev/null and b/res/drawable-hdpi/btn_circle_disable.png differ diff --git a/res/drawable-hdpi/btn_circle_disable_focused.png b/res/drawable-hdpi/btn_circle_disable_focused.png new file mode 100644 index 00000000..749ebb12 Binary files /dev/null and b/res/drawable-hdpi/btn_circle_disable_focused.png differ diff --git a/res/drawable-hdpi/btn_circle_normal.png b/res/drawable-hdpi/btn_circle_normal.png new file mode 100644 index 00000000..72a4388c Binary files /dev/null and b/res/drawable-hdpi/btn_circle_normal.png differ diff --git a/res/drawable-hdpi/btn_circle_pressed.png b/res/drawable-hdpi/btn_circle_pressed.png new file mode 100644 index 00000000..90651cee Binary files /dev/null and b/res/drawable-hdpi/btn_circle_pressed.png differ diff --git a/res/drawable-hdpi/btn_circle_selected.png b/res/drawable-hdpi/btn_circle_selected.png new file mode 100644 index 00000000..e5b58e1e Binary files /dev/null and b/res/drawable-hdpi/btn_circle_selected.png differ diff --git a/res/drawable-hdpi/ic_btn_round_more_disabled.png b/res/drawable-hdpi/ic_btn_round_more_disabled.png new file mode 100644 index 00000000..31291273 Binary files /dev/null and b/res/drawable-hdpi/ic_btn_round_more_disabled.png differ diff --git a/res/drawable-hdpi/ic_btn_round_more_normal.png b/res/drawable-hdpi/ic_btn_round_more_normal.png new file mode 100644 index 00000000..3b0f76b6 Binary files /dev/null and b/res/drawable-hdpi/ic_btn_round_more_normal.png differ diff --git a/res/drawable-hdpi/ime_de_lang_lower.png b/res/drawable-hdpi/ime_de_lang_lower.png index 58019867..aa6413ea 100644 Binary files a/res/drawable-hdpi/ime_de_lang_lower.png and b/res/drawable-hdpi/ime_de_lang_lower.png differ diff --git a/res/drawable-hdpi/ime_de_lang_single.png b/res/drawable-hdpi/ime_de_lang_single.png index e2bc6a50..f8f48ef2 100644 Binary files a/res/drawable-hdpi/ime_de_lang_single.png and b/res/drawable-hdpi/ime_de_lang_single.png differ diff --git a/res/drawable-hdpi/ime_de_lang_upper.png b/res/drawable-hdpi/ime_de_lang_upper.png index 51e5027e..87590ab1 100644 Binary files a/res/drawable-hdpi/ime_de_lang_upper.png and b/res/drawable-hdpi/ime_de_lang_upper.png differ diff --git a/res/drawable/btn_circle.xml b/res/drawable/btn_circle.xml new file mode 100644 index 00000000..9df5abbc --- /dev/null +++ b/res/drawable/btn_circle.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + diff --git a/res/drawable/ic_btn_round_more.xml b/res/drawable/ic_btn_round_more.xml new file mode 100644 index 00000000..b4bfc879 --- /dev/null +++ b/res/drawable/ic_btn_round_more.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/res/drawable/ime_de_lang_lower.png b/res/drawable/ime_de_lang_lower.png index 58019867..aa6413ea 100644 Binary files a/res/drawable/ime_de_lang_lower.png and b/res/drawable/ime_de_lang_lower.png differ diff --git a/res/drawable/ime_de_lang_single.png b/res/drawable/ime_de_lang_single.png index e2bc6a50..f8f48ef2 100644 Binary files a/res/drawable/ime_de_lang_single.png and b/res/drawable/ime_de_lang_single.png differ diff --git a/res/drawable/ime_de_lang_upper.png b/res/drawable/ime_de_lang_upper.png index 51e5027e..87590ab1 100644 Binary files a/res/drawable/ime_de_lang_upper.png and b/res/drawable/ime_de_lang_upper.png differ diff --git a/res/layout/addwordview.xml b/res/layout/addwordview.xml index d2972b25..946e513d 100644 --- a/res/layout/addwordview.xml +++ b/res/layout/addwordview.xml @@ -34,7 +34,7 @@ android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:onClick="cancelButton" - android:text="@string/cancel" /> + android:text="@android:string/cancel" /> diff --git a/res/layout/checkbox.xml b/res/layout/checkbox.xml new file mode 100644 index 00000000..349d6397 --- /dev/null +++ b/res/layout/checkbox.xml @@ -0,0 +1,26 @@ + + + + + + diff --git a/res/layout/preference_dialog.xml b/res/layout/preference_dialog.xml new file mode 100644 index 00000000..0d88ebf8 --- /dev/null +++ b/res/layout/preference_dialog.xml @@ -0,0 +1,10 @@ + + + diff --git a/res/layout/preference_list_content.xml b/res/layout/preference_list_content.xml new file mode 100644 index 00000000..56792935 --- /dev/null +++ b/res/layout/preference_list_content.xml @@ -0,0 +1,25 @@ + + + diff --git a/res/layout/setting.xml b/res/layout/setting.xml new file mode 100644 index 00000000..7b07e2f5 --- /dev/null +++ b/res/layout/setting.xml @@ -0,0 +1,29 @@ + + + + + + + + + + diff --git a/res/layout/setting_sum.xml b/res/layout/setting_sum.xml new file mode 100644 index 00000000..c93ce998 --- /dev/null +++ b/res/layout/setting_sum.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + diff --git a/res/layout/setting_widget.xml b/res/layout/setting_widget.xml new file mode 100644 index 00000000..e7ced890 --- /dev/null +++ b/res/layout/setting_widget.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + diff --git a/res/values-de/strings-german.xml b/res/values-de/strings-german.xml index ec63d48d..421b6254 100644 --- a/res/values-de/strings-german.xml +++ b/res/values-de/strings-german.xml @@ -21,16 +21,15 @@ Seite: %1$s/%2$s Wort hinzufügen - OK Schließen Leeres Wort nicht hinzugefügt. Wort mit nicht zuordbarem Buchstaben für %1$s (%2$s) kann nicht hinzugefügt werden. Das Wort (%1$s) ist bereits in der DB. Das Wort (%1$s) ist bereits für %2$s in der DB. - Abbrechen Wort hinzufügen Einstellungen Datenbank nicht verfügbar. + Database unavailable. Using default settings. Wörterbuch-Datenbank wird aktualisiert… Aktualisiere Wörterbuch-Datenbank. Das könnte einen Moment dauern. diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml index a24fd6cf..a4ec80c6 100644 --- a/res/values-ru/strings.xml +++ b/res/values-ru/strings.xml @@ -7,7 +7,6 @@ Слово (%1$s) уже есть в словаре. Слово (%1$s) уже есть в словаре %2$s. Traditional T9 - Отмена Hello world! Клавиатура T9 Цифры @@ -18,7 +17,6 @@ Commit Изменить IME Режим ввода - OK Ошибка: Внешняя память недоступна. Резервное копирование невозможно невозможно. Резервное копирование базы данных IME Предупреждение: Существующая копия базы данных будет перезаписана. Продолжить? @@ -62,6 +60,7 @@ Ошибка. \n Словарь %1$s не найден. Используется для озвучивания изменения режима ввода. Режим уведомления + Database unavailable. Using default settings. Добавить слово Traditional T9 настройки diff --git a/res/values/arrays.xml b/res/values/arrays.xml index 905df4f8..f8625287 100644 --- a/res/values/arrays.xml +++ b/res/values/arrays.xml @@ -1,29 +1,26 @@ - Dictionary - Text - Number - - - 0 - 1 - 2 + Dictionary + Text + Number + + @integer/INPUT_DICT + @integer/INPUT_TEXT + @integer/INPUT_NUM + - - 0 - - English - Russian - German - - - 0 - 1 - 2 + English + Russian + German + + @integer/LANG_EN + @integer/LANG_RU + @integer/LANG_DE + Caps off diff --git a/res/values/colors.xml b/res/values/colors.xml index 2db951e4..330e3485 100644 --- a/res/values/colors.xml +++ b/res/values/colors.xml @@ -1,10 +1,9 @@ #FF000000 - #FFE35900 - #ff808080 - #bbffffff - #FFFCBE2B + #ffc66ac3 + #ff68f0e9 + #e19185df #FF2A9AEB #FFA8A8A8 #FFFFFFFF diff --git a/res/values/const.xml b/res/values/const.xml new file mode 100644 index 00000000..95b6dc28 --- /dev/null +++ b/res/values/const.xml @@ -0,0 +1,14 @@ + + + + 1 + 2 + 4 + + 0 + 1 + 2 + + @integer/INPUT_DICT + @integer/LANG_EN + diff --git a/res/values/strings.xml b/res/values/strings.xml index cb8fb5b6..d34add4e 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -22,16 +22,15 @@ Page: %1$s/%2$s Add word - OK Close Blank word not added. Cannot add word with unmappable character for %1$s (%2$s). Word (%1$s) already in DB. Word (%1$s) already in DB for %2$s. - Cancel Add Word Settings Database unavailable. + Database unavailable. Using default settings. Updating dictionary database… Updating dictionary database, this might take a while. diff --git a/res/values/styles.xml b/res/values/styles.xml index d10f8464..fae1512c 100644 --- a/res/values/styles.xml +++ b/res/values/styles.xml @@ -17,4 +17,8 @@ + + + + diff --git a/res/xml/prefs.xml b/res/xml/prefs.xml index 1754fddf..2eebe11b 100644 --- a/res/xml/prefs.xml +++ b/res/xml/prefs.xml @@ -1,35 +1,29 @@ - - - - - - + + + + + - - - - - - - + + + + + + diff --git a/src/org/nyanya/android/traditionalt9/AddWordAct.java b/src/org/nyanya/android/traditionalt9/AddWordAct.java index 8b4290ac..a9d2ed31 100644 --- a/src/org/nyanya/android/traditionalt9/AddWordAct.java +++ b/src/org/nyanya/android/traditionalt9/AddWordAct.java @@ -3,20 +3,19 @@ package org.nyanya.android.traditionalt9; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; -import android.content.SharedPreferences; import android.os.Bundle; import android.app.Activity; -import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.EditText; +import org.nyanya.android.traditionalt9.T9DB.DBSettings.SETTING; + public class AddWordAct extends Activity { View main; int lang; - SharedPreferences pref; String origword; @Override @@ -36,7 +35,6 @@ public class AddWordAct extends Activity { et.setSelection(origword.length()); setContentView(v); main = v; - pref = PreferenceManager.getDefaultSharedPreferences(this); } public void addWordButton(View v) { @@ -49,13 +47,13 @@ public class AddWordAct extends Activity { public void doAddWord(String text) { T9DB db = T9DB.getInstance(this); try { - db.addWord(text, lang); + db.addWord(text, LangHelper.LANGUAGE.get(lang)); } catch (DBException e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); String msg = e.getMessage(); //Log.e("AddWord.doAddWord", msg); builder.setMessage(msg).setTitle(R.string.add_word) - .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); @@ -64,9 +62,7 @@ public class AddWordAct extends Activity { AlertDialog dialog = builder.create(); dialog.show(); } - SharedPreferences.Editor prefedit = pref.edit(); - prefedit.putString("last_word", text); - prefedit.commit(); + db.storeSettingString(SETTING.LAST_WORD, text); } diff --git a/src/org/nyanya/android/traditionalt9/CharMap.java b/src/org/nyanya/android/traditionalt9/CharMap.java index 1e1deffc..ac605a8b 100644 --- a/src/org/nyanya/android/traditionalt9/CharMap.java +++ b/src/org/nyanya/android/traditionalt9/CharMap.java @@ -8,6 +8,8 @@ import java.util.Map; import android.util.Log; +import org.nyanya.android.traditionalt9.LangHelper.LANGUAGE; + public class CharMap { protected static final AbstractList> CHARTABLE = new ArrayList>(LangHelper.NLANGS); static { @@ -16,12 +18,10 @@ public class CharMap { enMap.put('.', 1); enMap.put(',', 1); enMap.put('!', 1); enMap.put('?', 1); enMap.put('-', 1); enMap.put('"', 1); enMap.put('\'', 1); enMap.put('@', 1); enMap.put('#', 1); enMap.put('$', 1); enMap.put('%', 1); enMap.put('&', 1); - enMap.put('*', 1); enMap.put('(', 1); enMap.put(')', 1); enMap.put('1', 1); - enMap.put(':', 1); enMap.put(';', 1); enMap.put('/', 1); enMap.put('\\', 1); - enMap.put('+', 1); enMap.put('=', 1); enMap.put('<', 1); enMap.put('>', 1); - enMap.put('[', 1); enMap.put(']', 1); enMap.put('{', 1); enMap.put('}', 1); - enMap.put('^', 1); enMap.put('|', 1); enMap.put('_', 1); enMap.put('~', 1); - enMap.put('`', 1); + enMap.put('*', 1); enMap.put('(', 1); enMap.put(')', 1); enMap.put(':', 1); + enMap.put(';', 1); enMap.put('/', 1); enMap.put('+', 1); enMap.put('=', 1); + enMap.put('<', 1); enMap.put('>', 1); enMap.put('^', 1); enMap.put('_', 1); + enMap.put('~', 1); enMap.put('1', 1); enMap.put('a', 2); enMap.put('á', 2); enMap.put('ä', 2); enMap.put('â', 2); enMap.put('à', 2); enMap.put('å', 2); enMap.put('b', 2); enMap.put('c', 2); enMap.put('ç', 2); enMap.put('2', 2); @@ -48,12 +48,10 @@ public class CharMap { ruMap.put('.', 1); ruMap.put(',', 1); ruMap.put('!', 1); ruMap.put('?', 1); ruMap.put('-', 1); ruMap.put('"', 1); ruMap.put('\'', 1); ruMap.put('@', 1); ruMap.put('#', 1); ruMap.put('$', 1); ruMap.put('%', 1); ruMap.put('&', 1); - ruMap.put('*', 1); ruMap.put('(', 1); ruMap.put(')', 1); ruMap.put('1', 1); - ruMap.put(':', 1); ruMap.put(';', 1); ruMap.put('/', 1); ruMap.put('\\', 1); - ruMap.put('+', 1); ruMap.put('=', 1); ruMap.put('<', 1); ruMap.put('>', 1); - ruMap.put('[', 1); ruMap.put(']', 1); ruMap.put('{', 1); ruMap.put('}', 1); - ruMap.put('^', 1); ruMap.put('|', 1); ruMap.put('_', 1); ruMap.put('~', 1); - ruMap.put('`', 1); ruMap.put('1', 1); + ruMap.put('*', 1); ruMap.put('(', 1); ruMap.put(')', 1); ruMap.put(':', 1); + ruMap.put(';', 1); ruMap.put('/', 1); ruMap.put('+', 1); ruMap.put('=', 1); + ruMap.put('<', 1); ruMap.put('>', 1); ruMap.put('^', 1); ruMap.put('_', 1); + ruMap.put('~', 1); ruMap.put('1', 1); ruMap.put('а', 2); ruMap.put('б', 2); ruMap.put('в', 2); ruMap.put('г', 2); ruMap.put('2', 2); ruMap.put('д', 3); ruMap.put('е', 3); ruMap.put('ё', 3); ruMap.put('ж', 3); @@ -92,33 +90,33 @@ public class CharMap { { 'ш', 'щ', 'ъ', 'ы', 'Ш', 'Щ', 'Ъ', 'Ы', '8' }, { 'ь', 'э', 'ю', 'я', 'Ь', 'Э', 'Ю', 'Я', '9' }, { ' ', '\n' } }; protected static final char[][] DET9TABLE = { - { '0', '+' }, - { '.', ',', '?', '!', '"', '\'', '-', '@', '€', '$', '%', '&', '*', '(', ')', '_', '1' }, - { 'a', 'á', 'ä', 'â', 'à', 'å', 'b', 'c', 'ç', 'A', 'Á', 'Ä', 'Â', 'À', 'Å', 'B', 'C', 'Ç', '2' }, - { 'd', 'e', 'é','ë','è','ê', 'f', 'D', 'E', 'É', 'Ë', 'È', 'Ê', 'F', '3' }, - { 'g', 'h', 'i', 'í', 'ï', 'G', 'H', 'I', 'Í', 'Ï', '4' }, + { ' ', '+', '0' }, + { '.', ',', '?', '!', ':', ';', '"', '\'', '-', '@', '^', '€', '$', '%', '&', '*', '(', ')', '_', '1' }, + { 'a', 'b', 'c', 'A', 'B', 'C', 'ä', 'Ä','á', 'â', 'à', 'å', 'ç', 'Á', 'Â', 'À', 'Å', 'Ç', '2' }, + { 'd', 'e', 'f', 'D', 'E', 'F', 'é','ë','è','ê', 'É', 'Ë', 'È', 'Ê', '3' }, + { 'g', 'h', 'i', 'G', 'H', 'I', 'í', 'ï', 'Í', 'Ï', '4' }, { 'j', 'k', 'l', 'J', 'K', 'L', '5' }, - { 'm', 'n', 'ñ', 'o', 'ó','ö','ô', 'M', 'N', 'Ñ', 'O', 'Ó', 'Ö', 'Ô', '6' }, - { 'p', 'q', 'r', 's', 'ß', 'P', 'Q', 'R', 'S', '7' }, - { 't', 'u', 'û','ü', 'v', 'T', 'U', 'Û', 'Ü', 'V', '8' }, + { 'm', 'n', 'o', 'M', 'N', 'O', 'ö', 'Ö', 'ñ','ó','ô', 'Ñ', 'Ó', 'Ô', '6' }, + { 'p', 'q', 'r', 's', 'P', 'Q', 'R', 'S', 'ß', '7' }, + { 't', 'u', 'v', 'T', 'U', 'V', 'ü', 'Ü', 'û', 'Û', '8' }, { 'w', 'x', 'y', 'z', 'W', 'X', 'Y', 'Z', '9' }, - { ' ', '\n' } }; + { '\n' } }; protected static final char[][][] T9TABLE = {ENT9TABLE, RUT9TABLE, DET9TABLE}; protected static final int[] ENT9CAPSTART = { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4, 0 }; protected static final int [] RUT9CAPSTART = {0, 0, 4, 5, 4, 4, 4, 4, 4, 4, 0}; - protected static final int[] DET9CAPSTART = { 0, 0, 9, 7, 5, 3, 7, 5, 5, 4, 0 }; + protected static final int[] DET9CAPSTART = { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4, 0 }; protected static final int[][] T9CAPSTART = {ENT9CAPSTART, RUT9CAPSTART, DET9CAPSTART}; - protected static String getStringSequence(String word, int lang) { + protected static String getStringSequence(String word, LANGUAGE lang) { StringBuilder seq = new StringBuilder(); - String tword = word.toLowerCase(LangHelper.LOCALES[lang]); + String tword = word.toLowerCase(LangHelper.LOCALES[lang.index]); for (int i = 0; i < word.length(); i++) { char c = tword.charAt(i); - Integer z = CharMap.CHARTABLE.get(lang).get(c); + Integer z = CharMap.CHARTABLE.get(lang.index).get(c); if (z == null) { Log.e("getStringSequence", - "ERROR: " + (int) c + " NOT FOUND FOR [" + lang + "] (" + Integer.toHexString((int) c) + ") Index: " + i); + "ERROR: " + (int) c + " NOT FOUND FOR [" + lang.name() + "] (" + Integer.toHexString((int) c) + ") Index: " + i); throw new NullPointerException(); } seq.append(z.toString()); diff --git a/src/org/nyanya/android/traditionalt9/LangHelper.java b/src/org/nyanya/android/traditionalt9/LangHelper.java index 9f1e3b9e..0131837b 100644 --- a/src/org/nyanya/android/traditionalt9/LangHelper.java +++ b/src/org/nyanya/android/traditionalt9/LangHelper.java @@ -1,23 +1,45 @@ package org.nyanya.android.traditionalt9; +import android.util.Log; + +import java.util.HashMap; import java.util.Locale; +import java.util.Map; import pl.wavesoftware.widget.MultiSelectListPreference; public class LangHelper { protected static final Locale RUSSIAN = new Locale("ru","RU"); - protected static final int EN = 0; - protected static final int RU = 1; - protected static final int DE = 1; - protected static final Locale[] LOCALES = {Locale.ENGLISH, RUSSIAN, Locale.GERMAN}; - protected static final String[] LANGS = {"EN", "RU", "DE"}; + public enum LANGUAGE { + // MAKE SURE THESE MATCH WITH values/const.xml + NONE(-1, -1), EN(0,1), RU(1,2), DE(2,4), ; + public final int id; + public final int index; + // lookup map + private static final Map lookup = new HashMap(); + private static final LANGUAGE[] ids = LANGUAGE.values(); + static { for (LANGUAGE l : ids) lookup.put(l.id, l); } - protected static final int NLANGS = LANGS.length; + private LANGUAGE(int index, int id) { this.index = index; this.id = id; } + + public static LANGUAGE get(int i) { return lookup.get(i);} + } + + protected static final Locale[] LOCALES = {Locale.ENGLISH, RUSSIAN, Locale.GERMAN}; + //protected static final String[] LANGS = {"EN", "RU", "DE"}; + + public static final int LANG_DEFAULT = LANGUAGE.EN.id; + + protected static final int NLANGS = LANGUAGE.lookup.size(); protected static String getString(int lang) { - return LANGS[lang]; + return LANGUAGE.get(lang).name(); } + protected static int getIndex(LANGUAGE l) { + return l.index; + } + //[LANG][MODE][CAPSMODE] = iconref // first group en, first line LANG, second line TEXT, last line NUM protected static final int[][][] ICONMAP = { @@ -42,31 +64,43 @@ public class LangHelper { }; - protected static int[] buildLangs(CharSequence s) { - int[] ia = MultiSelectListPreference.defaultunpack2Int(s); + public static LANGUAGE[] buildLangs(int i) { int num = 0; //calc size of filtered array - for (int i : ia) { - if (i >= 0 && i < LangHelper.NLANGS) { + for (LANGUAGE l : LANGUAGE.ids) { + if ((i & l.id) == l.id) { num++; } } - int[] ian = new int[num]; - int iansize = 0; - for (int i : ia) { - if (i >= 0 && i < LangHelper.NLANGS) { - ian[iansize] = i; - iansize++; + LANGUAGE[] la = new LANGUAGE[num]; + int lai = 0; + for (LANGUAGE l : LANGUAGE.ids) { + if ((i & l.id) == l.id) { + la[lai] = l; + lai++; } } - return ian; + return la; } - protected static int findIndex(int[] ia, int target) { + public static int shrinkLangs(LANGUAGE[] langs) { + int i = 0; + for (LANGUAGE l : langs) + i = i | l.id; + return i; + } + public static int shrinkLangs(int[] langs) { + int i = 0; + for (int l : langs) + i = i | l; + return i; + } + + protected static int findIndex(LANGUAGE[] ia, LANGUAGE target) { for (int x=0; x lookup = new HashMap(); + private static final SETTING[] settings = SETTING.values(); + static { for (SETTING l : settings) lookup.put(l.id, l); } + + private SETTING(String id, Integer defval) { this.id = id; this.defvalue = defval;} + + public static SETTING get(String i) { return lookup.get(i);} + public static StringBuilder join(SETTING[] settings, StringBuilder sb) { + for (int x=0; x= 2) { - char c = is.charAt(islen - 1); - c++; - q = "SELECT " + COLUMN_WORD + " FROM " + WORD_TABLE_NAME + - " WHERE " + COLUMN_LANG + "=? AND " + COLUMN_SEQ + " >= '" + is + "1" + - "' AND " + COLUMN_SEQ + " < '" + is.substring(0, islen - 1) + c + "'" + - " ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" + - " LIMIT " + (MAX_RESULTS - hits); - cur = db.rawQuery(q, new String[]{String.valueOf(lang)}); - - if (cur.moveToFirst()) { - result = cur.getString(0); - } - if (result == null) { - result = ""; - } - cur.close(); - } - } - return result; - } - protected void updateWords(String is, AbstractList stringList, List intList, - int capsMode, int lang) { + int capsMode, LANGUAGE lang) { stringList.clear(); intList.clear(); // String[] sa = packInts(stringToInts(is), true); @@ -245,20 +347,18 @@ public class T9DB { Toast.makeText(mContext, R.string.database_notready, Toast.LENGTH_SHORT).show(); return; } - Cursor cur = db.rawQuery(QUERY1, new String[] { String.valueOf(lang), is }); + Cursor cur = db.rawQuery(QUERY1, new String[] { String.valueOf(lang.id), is }); int hits = 0; for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { intList.add(cur.getInt(0)); stringList.add(cur.getString(1)); -// if (hits >= 15) { -// break; -// } + if (hits >= MAX_MAX_RESULTS) { break; } // to stop index error in candidate view hits++; } cur.close(); - if ((hits < MINHITS) && (islen <= 2)) { + if ((hits < MINHITS) && (islen >= 2)) { char c = is.charAt(islen - 1); c++; String q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + @@ -267,12 +367,12 @@ public class T9DB { "' AND " + COLUMN_SEQ + " < '" + is.substring(0, islen - 1) + c + "'" + " ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" + " LIMIT " + (MAX_RESULTS - hits); - cur = db.rawQuery(q, new String[] { String.valueOf(lang) }); + cur = db.rawQuery(q, new String[] { String.valueOf(lang.id) }); for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { intList.add(cur.getInt(0)); stringList.add(cur.getString(1)); - if (hits >= 20) { + if (hits >= MAX_MAX_RESULTS) { break; } hits++; @@ -294,7 +394,7 @@ public class T9DB { word = iter.next(); switch (capsMode) { case CAPS_ALL: - wordtemp = word.toUpperCase(LangHelper.LOCALES[lang]); + wordtemp = word.toUpperCase(LangHelper.LOCALES[lang.index]); if (wordtemp.equals(word)) { index++; continue; @@ -308,9 +408,9 @@ public class T9DB { break; case CAPS_SINGLE: if (word.length() > 1) { - wordtemp = word.substring(0, 1).toUpperCase(LangHelper.LOCALES[lang]) + word.substring(1); + wordtemp = word.substring(0, 1).toUpperCase(LangHelper.LOCALES[lang.index]) + word.substring(1); } else { - wordtemp = word.toUpperCase(LangHelper.LOCALES[lang]); + wordtemp = word.toUpperCase(LangHelper.LOCALES[lang.index]); } if (wordtemp.equals(word)) { index++; @@ -334,58 +434,6 @@ public class T9DB { //Log.d("T9DB.updateWords", "i:" + is + " words:" + Arrays.toString(stringList.toArray())); } - protected void updateWordsW(String is, Collection stringList, - Collection intList, Collection freq, int lang) { - stringList.clear(); - intList.clear(); - freq.clear(); - // String[] sa = packInts(stringToInts(is), true); - int islen = is.length(); - String q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + ", " + COLUMN_FREQUENCY + - " FROM " + WORD_TABLE_NAME + - " WHERE " + COLUMN_LANG + "=? AND " + COLUMN_SEQ + "=?" + - " ORDER BY " + COLUMN_FREQUENCY + " DESC"; - if (!checkReady()) { - Log.e("T9DB.updateWordsW", "not ready"); - Toast.makeText(mContext, R.string.database_notready, Toast.LENGTH_SHORT).show(); - return; - } - Cursor cur = db.rawQuery(q, new String[] { is, String.valueOf(lang) }); - int hits = 0; - for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { - intList.add(cur.getInt(0)); - stringList.add(cur.getString(1)); - freq.add(cur.getInt(2)); - if (hits >= 10) { - break; - } - hits++; - } - cur.close(); - if (hits < MINHITS) { - char c = is.charAt(islen - 1); - c++; - q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + ", " + COLUMN_FREQUENCY + - " FROM " + WORD_TABLE_NAME + - " WHERE " + COLUMN_LANG + "=? AND " + COLUMN_SEQ + " >= '" + is + - "' AND " + COLUMN_SEQ + " < '" + is.substring(0, islen - 1) + c + "'" + - " ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" + - " LIMIT " + (MAX_RESULTS - hits); - cur = db.rawQuery(q, new String[] { String.valueOf(lang) }); - - for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { - intList.add(cur.getInt(0)); - stringList.add(cur.getString(1)); - freq.add(cur.getInt(2)); - if (hits >= 10) { - break; - } - hits++; - } - cur.close(); - } - } - private static class DatabaseHelper extends SQLiteOpenHelper { Context mContext = null; @@ -416,7 +464,7 @@ public class T9DB { COLUMN_WORD + " TEXT, " + COLUMN_FREQUENCY + " INTEGER, " + "UNIQUE(" + COLUMN_LANG + ", " + COLUMN_WORD + ") )"); - db.execSQL("CREATE INDEX idx ON " + WORD_TABLE_NAME + "(" + db.execSQL("CREATE INDEX IF NOT EXISTS idx ON " + WORD_TABLE_NAME + "(" + COLUMN_LANG + ", " + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + " DESC )"); db.execSQL("CREATE TRIGGER IF NOT EXISTS " + FREQ_TRIGGER_NAME + " AFTER UPDATE ON " + WORD_TABLE_NAME + @@ -426,19 +474,51 @@ public class T9DB { + COLUMN_FREQUENCY + " / " + FREQ_DIV + " WHERE " + COLUMN_SEQ + " = NEW." + COLUMN_SEQ + ";" + " END;"); + // protected static final String[] setting_keys = {INPUT_MODE, LANG_SUPPORT, MODE_NOTIFY, LAST_LANG}; + db.execSQL("CREATE TABLE IF NOT EXISTS " + SETTING_TABLE_NAME + " (" + + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + DBSettings.SETTING.INPUT_MODE.id + " INTEGER, " + + DBSettings.SETTING.LANG_SUPPORT.id + " INTEGER, " + + DBSettings.SETTING.MODE_NOTIFY.id + " INTEGER, " + + DBSettings.SETTING.LAST_LANG.id + " INTEGER, " + + DBSettings.SETTING.LAST_WORD.id + " TEXT )"); + StringBuilder sb = new StringBuilder("INSERT OR IGNORE INTO "); sb.append(SETTING_TABLE_NAME); + sb.append(" ("); sb.append(COLUMN_ID); sb.append(", "); + sb = DBSettings.SETTING.join(DBSettings.SETTING.settings, sb); + sb.append(") VALUES (1,"); + for (int x=0;x= LangHelper.NLANGS) { - Log.w("T9.sanitizeLang", "Previous lang not supported: " + lang + " langs: " + Arrays.toString(LangHelper.LANGS)); return mLangsAvailable[0]; - } else { + } + else { int index = LangHelper.findIndex(mLangsAvailable, lang); - if (index == -1) { - return mLangsAvailable[mLangIndex]; - } else { - mLangIndex = index; - return lang; - } + mLangIndex = index; + return mLangsAvailable[index]; } } /** @@ -252,8 +238,15 @@ public class TraditionalT9 extends InputMethodService implements // way. clearState(); - mLangsAvailable = LangHelper.buildLangs(pref.getString("pref_lang_support", null)); - mLang = sanitizeLang(pref.getInt("last_lang", 0)); + // get settings + Object[] settings = db.getSettings(new SETTING[] + // 0, 1, 2, + {SETTING.LANG_SUPPORT, SETTING.LAST_LANG, SETTING.MODE_NOTIFY, + // 3, 4 + SETTING.INPUT_MODE, SETTING.LAST_WORD} ); + + mLangsAvailable = LangHelper.buildLangs((Integer)settings[0]); + mLang = sanitizeLang(LANGUAGE.get((Integer)settings[1])); updateCandidates(); @@ -261,7 +254,7 @@ public class TraditionalT9 extends InputMethodService implements mKeyMode = MODE_TEXT; - boolean modenotify = pref.getBoolean("pref_mode_notify", false); + boolean modenotify = settings[2].equals("1"); if (!modenotify && modeNotification != null) { modeNotification = null; } else if (modenotify && modeNotification == null){ @@ -289,7 +282,7 @@ public class TraditionalT9 extends InputMethodService implements // normal alphabetic keyboard, and assume that we should // be doing predictive text (showing candidates as the // user types). - mKeyMode = Integer.parseInt(pref.getString("pref_inputmode", "0")); + mKeyMode = (Integer)settings[3]; // We now look for a few special variations of text that will // modify our behavior. @@ -316,7 +309,7 @@ public class TraditionalT9 extends InputMethodService implements // candidates when in fullscreen mode, otherwise relying // own it displaying its own UI. // ???? - mKeyMode = Integer.parseInt(pref.getString("pref_inputmode", "0")); + mKeyMode = (Integer)settings[3]; } // handle filter list cases... do not hijack DPAD center and make @@ -351,20 +344,18 @@ public class TraditionalT9 extends InputMethodService implements } else { mAddingWord = false; // Log.d("onStartInput", "not adding word"); - prevword = pref.getString("last_word", null); + prevword = (String)settings[4]; if (prevword != null) { onText(prevword); - Editor prefedit = pref.edit(); - prefedit.remove("last_word"); - prefedit.commit(); + db.storeSettingString(SETTING.LAST_WORD, null); } if (modenotify) { Resources r = getResources(); if (mKeyMode != MODE_NUM) - modeNotify(String.format("%s %s %s", r.getStringArray(R.array.pref_lang_titles)[mLang], + modeNotify(String.format("%s %s %s", r.getStringArray(R.array.pref_lang_titles)[mLang.index], r.getStringArray(R.array.keyMode)[mKeyMode], r.getStringArray(R.array.capsMode)[mCapsMode])); else - modeNotify(String.format("%s %s", r.getStringArray(R.array.pref_lang_titles)[mLang], + modeNotify(String.format("%s %s", r.getStringArray(R.array.pref_lang_titles)[mLang.index], r.getStringArray(R.array.keyMode)[mKeyMode])); } } @@ -393,9 +384,7 @@ public class TraditionalT9 extends InputMethodService implements public void onFinishInput() { super.onFinishInput(); // Log.d("onFinishInput", "When is this called?"); - Editor prefedit = pref.edit(); - prefedit.putInt("last_lang", mLang); - prefedit.commit(); + db.storeSettingInt(SETTING.LAST_LANG, mLang.id); if (mEditing == EDITING) { commitTyped(); finish(); @@ -575,6 +564,7 @@ public class TraditionalT9 extends InputMethodService implements case KeyEvent.KEYCODE_9: case KeyEvent.KEYCODE_POUND: case KeyEvent.KEYCODE_STAR: + case 94: event.startTracking(); return true; default: @@ -779,6 +769,7 @@ public class TraditionalT9 extends InputMethodService implements case KeyEvent.KEYCODE_9: case KeyEvent.KEYCODE_POUND: case KeyEvent.KEYCODE_STAR: + case 94: //case KeyEvent.KEYCODE_FOCUS: // if (!isInputViewShown()){ // Log.d("onKeyUp", "showing window."); @@ -892,10 +883,6 @@ public class TraditionalT9 extends InputMethodService implements break; case KeyEvent.KEYCODE_SOFT_RIGHT: nextKeyMode(); - break; - case KeyEvent.KEYCODE_FOCUS: - // do IME action - break; default: if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) { @@ -1020,7 +1007,8 @@ public class TraditionalT9 extends InputMethodService implements } else if (mKeyMode == MODE_TEXT) { if (mComposing.length() > 0) { mSuggestionStrings.clear(); - char[] ca = CharMap.T9TABLE[mLang][mPrevious]; + + char[] ca = CharMap.T9TABLE[mLang.index][mPrevious]; for (char c : ca) { mSuggestionStrings.add(String.valueOf(c)); } @@ -1050,14 +1038,16 @@ public class TraditionalT9 extends InputMethodService implements } setCandidatesViewShown(false); } + Log.d("handleBS", "Stage1: (" + length + "," + length2 + ")"); + Log.d("handleBS", "Stage1: (" + mComposingI.toString() + ")"); if (length2 > 1) { - if (mComposingI.charAt(length2-1) == '1' ) { + if (mComposingI.charAt(length2 - 1) == '1') { // revert previous word - mPreviousWord = mPreviousWord.substring(0, mPreviousWord.length()-1); + mPreviousWord = mPreviousWord.substring(0, mPreviousWord.length() - 1); } mComposingI.delete(length2 - 1, length2); - if (length2-1 > 1) { - if (mComposingI.charAt(length2-2) != '1') { + if (length2 - 1 > 1) { + if (mComposingI.charAt(length2 - 2) != '1') { if (mComposingI.indexOf("1") == -1) { // no longer contains punctuation so we no longer care mPreviousWord = ""; @@ -1069,6 +1059,7 @@ public class TraditionalT9 extends InputMethodService implements updateCandidates(true); getCurrentInputConnection().setComposingText(mComposing, 1); } else if (length > 0 || length2 > 0) { + Log.d("handleBS", "resetting thing"); mComposing.setLength(0); mComposingI.setLength(0); interfacehandler.midButtonUpdate(false); @@ -1129,7 +1120,6 @@ public class TraditionalT9 extends InputMethodService implements updateCandidates(); getCurrentInputConnection().setComposingText(mComposing, 1); } - break; case MODE_TEXT: @@ -1154,20 +1144,19 @@ public class TraditionalT9 extends InputMethodService implements // start at caps if CapMode // Log.d("handleChar", "Cm: " + mCapsMode); if (mCharIndex == 0 && mCapsMode != CAPS_OFF) { - mCharIndex = CharMap.T9CAPSTART[mLang][keyCode]; + mCharIndex = CharMap.T9CAPSTART[mLang.index][keyCode]; } // private int mPrevious; // private int mCharindex; mComposing.setLength(0); mComposingI.setLength(0); - char[] ca = CharMap.T9TABLE[mLang][keyCode]; + char[] ca = CharMap.T9TABLE[mLang.index][keyCode]; if (mCharIndex >= ca.length) { mCharIndex = 0; } mComposing.append(ca[mCharIndex]); - mComposingI.append(keyCode); getCurrentInputConnection().setComposingText(mComposing, 1); t9releasehandler.postDelayed(mt9release, T9DELAY); @@ -1318,7 +1307,7 @@ public class TraditionalT9 extends InputMethodService implements mLang = mLangsAvailable[mLangIndex]; updateKeyMode(); if (modeNotification != null) { - modeNotify(getResources().getStringArray(R.array.pref_lang_titles)[mLang]); + modeNotify(getResources().getStringArray(R.array.pref_lang_titles)[mLang.index]); } } @@ -1342,7 +1331,7 @@ public class TraditionalT9 extends InputMethodService implements switch (mKeyMode) { case MODE_TEXT: interfacehandler.showHold(false); - icon = LangHelper.ICONMAP[mLang][mKeyMode][mCapsMode]; + icon = LangHelper.ICONMAP[mLang.index][mKeyMode][mCapsMode]; break; case MODE_LANG: if (!db.ready) { @@ -1364,7 +1353,7 @@ public class TraditionalT9 extends InputMethodService implements } //Log.d("T9.updateKeyMode", "lang: " + mLang + " mKeyMode: " + mKeyMode + " mCapsMode" // + mCapsMode); - icon = LangHelper.ICONMAP[mLang][mKeyMode][mCapsMode]; + icon = LangHelper.ICONMAP[mLang.index][mKeyMode][mCapsMode]; break; case MODE_NUM: interfacehandler.showHold(false); diff --git a/src/org/nyanya/android/traditionalt9/TraditionalT9Settings.java b/src/org/nyanya/android/traditionalt9/TraditionalT9Settings.java index 140ddd09..f3a634d1 100644 --- a/src/org/nyanya/android/traditionalt9/TraditionalT9Settings.java +++ b/src/org/nyanya/android/traditionalt9/TraditionalT9Settings.java @@ -21,7 +21,6 @@ import java.io.UnsupportedEncodingException; import java.util.AbstractList; import java.util.ArrayList; import java.util.Iterator; -import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; @@ -29,11 +28,11 @@ import java.util.Properties; import android.app.Activity; import android.app.AlertDialog; +import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; -import android.content.SharedPreferences; import android.content.res.Resources; import android.database.Cursor; import android.database.DatabaseUtils.InsertHelper; @@ -43,19 +42,23 @@ import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.SystemClock; -import android.preference.ListPreference; -import android.preference.Preference; -import android.preference.PreferenceActivity; -import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; + +import android.view.View; +import android.widget.ListAdapter; +import android.widget.ListView; import android.widget.Toast; import com.stackoverflow.answer.UnicodeBOMInputStream; -import pl.wavesoftware.widget.MultiSelectListPreference; +import org.nyanya.android.traditionalt9.settings.CustomInflater; +import org.nyanya.android.traditionalt9.settings.Setting; +import org.nyanya.android.traditionalt9.settings.SettingAdapter; +import org.nyanya.android.traditionalt9.LangHelper.LANGUAGE; +import org.nyanya.android.traditionalt9.T9DB.DBSettings.SETTING; -public class TraditionalT9Settings extends PreferenceActivity implements +public class TraditionalT9Settings extends ListActivity implements DialogInterface.OnCancelListener { AsyncTask task = null; @@ -82,7 +85,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements protected Reply() { this.status = true; - this.msgs = new LinkedList(); + this.msgs = new ArrayList(4); } protected void addMsg(String msg) throws LoadException { @@ -117,7 +120,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements } } - private void closeStream(Closeable is, Reply reply) { + private static void closeStream(Closeable is, Reply reply) { if (is == null) { return; } @@ -140,9 +143,9 @@ public class TraditionalT9Settings extends PreferenceActivity implements boolean internal; boolean restore; String[] dicts; - int[] mSupportedLanguages; + LANGUAGE[] mSupportedLanguages; - LoadDictTask(int msgid, boolean intern, boolean restorebackup, int[] supportedLanguages) { + LoadDictTask(int msgid, boolean intern, boolean restorebackup, LANGUAGE[] supportedLanguages) { internal = intern; restore = restorebackup; @@ -150,11 +153,9 @@ public class TraditionalT9Settings extends PreferenceActivity implements dicts = new String[suplanglen]; for (int x=0; x entry : CharMap.CHARTABLE.get(lang).entrySet()) { - wordhelp.prepareForReplace(); - wordhelp.bind(langColumn, Integer.toString(lang)); - wordhelp.bind(seqColumn, Integer.toString(entry.getValue())); - wordhelp.bind(wordColumn, Character.toString(entry.getKey())); - wordhelp.bind(freqColumn, 0); - wordhelp.execute(); - // upper case - wordhelp.prepareForReplace(); - wordhelp.bind(langColumn, Integer.toString(lang)); - wordhelp.bind(seqColumn, Integer.toString(entry.getValue())); - wordhelp.bind(wordColumn, Character.toString(Character.toUpperCase(entry.getKey()))); - wordhelp.bind(freqColumn, 0); - wordhelp.execute(); - } - char[][] chartable = CharMap.T9TABLE[lang]; - for (int numkey=0; numkey entry : CharMap.CHARTABLE.get(lang.index).entrySet()) { wordhelp.prepareForReplace(); - wordhelp.bind(langColumn, Integer.toString(lang)); - wordhelp.bind(seqColumn, Integer.toString(numkey)); - wordhelp.bind(wordColumn, Character.toString(chars[charindex])); + wordhelp.bind(langColumn, lang.id); + wordhelp.bind(seqColumn, Integer.toString(entry.getValue())); + wordhelp.bind(wordColumn, Character.toString(entry.getKey())); + wordhelp.bind(freqColumn, 0); + wordhelp.execute(); + // upper case + wordhelp.prepareForReplace(); + wordhelp.bind(langColumn, lang.id); + wordhelp.bind(seqColumn, Integer.toString(entry.getValue())); + wordhelp.bind(wordColumn, Character.toString(Character.toUpperCase(entry.getKey()))); wordhelp.bind(freqColumn, 0); wordhelp.execute(); } + char[][] chartable = CharMap.T9TABLE[lang.index]; + for (int numkey = 0; numkey < chartable.length; numkey++) { + char[] chars = chartable[numkey]; + for (int charindex = 0; charindex < chars.length; charindex++) { + wordhelp.prepareForReplace(); + wordhelp.bind(langColumn, lang.id); + wordhelp.bind(seqColumn, Integer.toString(numkey)); + wordhelp.bind(wordColumn, Character.toString(chars[charindex])); + wordhelp.bind(freqColumn, 0); + wordhelp.execute(); + } + } + } finally { + wordhelp.close(); } } @@ -368,7 +373,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements return null; } - private Reply processFile(InputStream is, Reply rpl, SQLiteDatabase db, int lang, String fname) + private Reply processFile(InputStream is, Reply rpl, SQLiteDatabase db, LANGUAGE lang, String fname) throws LoadException, IOException { long last = 0; UnicodeBOMInputStream ubis = new UnicodeBOMInputStream(is); @@ -408,21 +413,21 @@ public class TraditionalT9Settings extends PreferenceActivity implements rpl.addMsg("Number error ("+fname+") at line " + linecount+". Using 0 for frequency."); freq = 0; } - if (lang == -1 && ws.length == 3) { + if (lang == LANGUAGE.NONE && ws.length == 3) { try { - lang = Integer.parseInt(ws[2]); + lang = LANGUAGE.get(Integer.parseInt(ws[2])); } catch (NumberFormatException e) { rpl.status = false; - rpl.addMsg("Number error ("+fname+") at line " + linecount+". Using 0 (en) for language."); - lang = 0; + rpl.addMsg("Number error ("+fname+") at line " + linecount+". Using 1 (en) for language."); + lang = LANGUAGE.EN; } - if (lang >= LangHelper.LANGS.length) { + if (lang == null) { rpl.status = false; - rpl.addMsg("Unsupported language ("+fname+") at line " + linecount+". Trying 0 (en) for language."); - lang = 0; + rpl.addMsg("Unsupported language ("+fname+") at line " + linecount+". Trying 1 (en) for language."); + lang = LANGUAGE.EN; } - } else if (lang == -1) { - lang = 0; + } else if (lang == LANGUAGE.NONE) { + lang = LANGUAGE.EN; } } else { freq = 0; @@ -445,13 +450,13 @@ public class TraditionalT9Settings extends PreferenceActivity implements rpl.status = false; rpl.addMsg("Error on word ("+word+") line "+ linecount+" in (" + fname+"): "+ - getResources().getString(R.string.add_word_badchar, LangHelper.LANGS[lang], word)); + getResources().getString(R.string.add_word_badchar, lang.name(), word)); break; } linecount++; wordhelp.prepareForReplace(); wordhelp.bind(seqColumn, seq); - wordhelp.bind(langColumn, lang); + wordhelp.bind(langColumn, lang.id); wordhelp.bind(wordColumn, word); wordhelp.bind(freqColumn, freq); wordhelp.execute(); @@ -597,7 +602,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements cur.close(); } } finally { - + cur.close(); } publishProgress(10000); @@ -606,10 +611,6 @@ public class TraditionalT9Settings extends PreferenceActivity implements Log.d("doInBackground", "entries: " + entries + " last: " + pos); try { bw.flush(); - } catch (IOException e) { - e.printStackTrace(); - } - try { bw.close(); } catch (IOException e) { e.printStackTrace(); @@ -683,86 +684,44 @@ public class TraditionalT9Settings extends PreferenceActivity implements @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - addPreferencesFromResource(R.xml.prefs); - Preference button = getPreferenceManager().findPreference("help"); - if (button != null) { - button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference arg0) { - openHelp(); - return true; - } - }); + // maybe need this? + // http://stackoverflow.com/questions/7645880/listview-with-onitemclicklistener-android + + // get settings + Object[] settings = T9DB.getInstance(this).getSettings(new SETTING[] + // 0, 1, 2 + {SETTING.INPUT_MODE, SETTING.LANG_SUPPORT, SETTING.MODE_NOTIFY}); + ListAdapter settingitems; + try { + settingitems = new SettingAdapter(this, CustomInflater.inflate(this, R.xml.prefs, settings)); + } catch (Exception e) { + e.printStackTrace(); + return; } - - button = getPreferenceManager().findPreference("loaddict"); - if (button != null) { - button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference arg0) { - preloader(R.string.pref_loadingdict, true, false); - return true; - } - }); - } - - button = getPreferenceManager().findPreference("loaduserdict"); - if (button != null) { - button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference arg0) { - preloader(R.string.pref_loadinguserdict, false, false); - return true; - } - }); - } - - button = getPreferenceManager().findPreference("nukedict"); - if (button != null) { - button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference arg0) { - nukeDict(); - return true; - } - }); - } - - button = getPreferenceManager().findPreference("backupdict"); - if (button != null) { - button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference arg0) { - backupDict(); - return true; - } - }); - } - - button = getPreferenceManager().findPreference("restoredict"); - if (button != null) { - button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference arg0) { - restoreDict(); - return true; - } - }); - } - - button = getPreferenceManager().findPreference("querytest"); - if (button != null) { - button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference arg0) { - test(); - return true; - } - }); - } - + setContentView(R.layout.preference_list_content); + setListAdapter(settingitems); mContext = this; + + } + + @Override + protected void onListItemClick(ListView l, View v, int position, long id) { + Setting s = (Setting)getListView().getItemAtPosition(position); + if (s.id.equals("help")) + openHelp(); + else if (s.id.equals("loaddict")) + preloader(R.string.pref_loadingdict, true, false); + else if (s.id.equals("loaduserdict")) + preloader(R.string.pref_loadinguserdict, false, false); + else if (s.id.equals("nukedict")) + nukeDict(); + else if (s.id.equals("backupdict")) + backupDict(); + else if (s.id.equals("restoredict")) + restoreDict(); + else + s.clicked(mContext); } private void openHelp() { @@ -775,7 +734,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements private void preloader(int msgid, boolean internal, boolean restorebackup) { task = new LoadDictTask(msgid, internal, restorebackup, - LangHelper.buildLangs(((ListPreference) findPreference("pref_lang_support")).getValue())); + LangHelper.buildLangs(T9DB.getInstance(mContext).getSettingInt(SETTING.LANG_SUPPORT))); task.execute(); } @@ -787,13 +746,13 @@ public class TraditionalT9Settings extends PreferenceActivity implements private void nukeDict() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.pref_nuke_warn).setTitle(R.string.pref_nuke_title) - .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { task = new NukeDictTask(R.string.pref_nukingdict); task.execute(); } - }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); @@ -818,12 +777,12 @@ public class TraditionalT9Settings extends PreferenceActivity implements saveloc = new File(saveloc, backupname); if (saveloc.exists()) { builder.setMessage(R.string.pref_backup_warn).setTitle(R.string.pref_backup_title) - .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { predumper(R.string.pref_savingbackup); } - }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); @@ -845,7 +804,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements private void showErrorDialog(AlertDialog.Builder builder, CharSequence title, CharSequence msg) { builder.setMessage(msg).setTitle(title) - .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { + .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); @@ -857,7 +816,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements private void showErrorDialogID(AlertDialog.Builder builder, int titleid, int msgid) { builder.setMessage(msgid).setTitle(titleid) - .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { + .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); @@ -881,12 +840,12 @@ public class TraditionalT9Settings extends PreferenceActivity implements res.getString(R.string.pref_restore_warn, res.getString(R.string.pref_nukedict))) .setTitle(R.string.pref_restore_title) - .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { preloader(R.string.pref_loadingbackup, false, true); } - }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); @@ -913,17 +872,17 @@ public class TraditionalT9Settings extends PreferenceActivity implements T9DB tdb = T9DB.getInstance(this); Log.d("queryTestDebug", "Testing..."); - tdb.updateWords("123", words, ids, 0, LangHelper.EN); + tdb.updateWords("123", words, ids, 0, LangHelper.LANGUAGE.EN); Log.d("queryTestDebug", "123->" + words.toString()); Log.d("queryTestDebug", "269->"); - tdb.updateWords("269", words, ids, 0, LangHelper.EN); + tdb.updateWords("269", words, ids, 0, LangHelper.LANGUAGE.EN); Iterator i = words.iterator(); while (i.hasNext()) { Log.d("queryTestDebug", "word: " + i.next()); } Log.d("queryTestDebug", "228->"); - tdb.updateWords("228", words, ids, 0, LangHelper.EN); + tdb.updateWords("228", words, ids, 0, LangHelper.LANGUAGE.EN); i = words.iterator(); while (i.hasNext()) { Log.d("queryTestDebug", "word: " + i.next()); @@ -961,7 +920,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements T9DB tdb = T9DB.getInstance(this); - tdb.updateWords("222", words, ids, 0, LangHelper.EN); + tdb.updateWords("222", words, ids, 0, LangHelper.LANGUAGE.EN); size = ids.size(); if (size > 0) { tdb.incrementWord(ids.get(0)); @@ -977,7 +936,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements Log.d("TIMING", "Execution time: " + (endnow - startnow) + " ms"); List freqs = new ArrayList(8); - tdb.updateWordsW("222", words, ids, freqs, LangHelper.EN); + //tdb.updateWordsW("222", words, ids, freqs, LangHelper.EN); Log.d("VALUES", "..."); size = freqs.size(); for (int x = 0; x < size; x++) { @@ -986,13 +945,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements } Log.d("queryTestSingle", "done."); } - private void test() { - SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); - if ( "".equalsIgnoreCase(pref.getString("pref_lang_support", null)) ) { - Log.d("T9Settings.test", "AAAAAAAAAA blank string"); - } - Log.d("T9Settings.test", pref.getString("pref_lang_support", "aaaaaaaaaa")); - } + @Override public void onCancel(DialogInterface dint) { task.cancel(false); diff --git a/src/org/nyanya/android/traditionalt9/settings/CustomInflater.java b/src/org/nyanya/android/traditionalt9/settings/CustomInflater.java new file mode 100644 index 00000000..b9a9073a --- /dev/null +++ b/src/org/nyanya/android/traditionalt9/settings/CustomInflater.java @@ -0,0 +1,41 @@ +package org.nyanya.android.traditionalt9.settings; + +// http://stackoverflow.com/a/8488691 + +import android.content.Context; +import android.content.res.XmlResourceParser; +import android.util.AttributeSet; +import android.util.Log; + +import org.nyanya.android.traditionalt9.R; +import org.xmlpull.v1.XmlPullParser; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; + +public class CustomInflater { + public static ArrayList inflate(Context context, int xmlFileResId, Object[] isettings) + throws Exception { + ArrayList settings = new ArrayList(); + + XmlResourceParser parser = context.getResources().getXml(xmlFileResId); + int token; + while ((token = parser.next()) != XmlPullParser.END_DOCUMENT) { + if (token == XmlPullParser.START_TAG) { + if (!parser.getName().equals("Settings")) { + //prepend package + Class aClass = Class.forName("org.nyanya.android.traditionalt9.settings."+parser.getName()); + Class[] params = new Class[]{Context.class, AttributeSet.class, isettings.getClass()}; + Constructor constructor = aClass.getConstructor(params); + try { + settings.add((Setting) constructor.newInstance(context, parser, isettings)); + } catch (InstantiationException e) { + e.printStackTrace(); + } + } + } + } + + return settings; + } +} diff --git a/src/org/nyanya/android/traditionalt9/settings/Setting.java b/src/org/nyanya/android/traditionalt9/settings/Setting.java new file mode 100644 index 00000000..a32a251f --- /dev/null +++ b/src/org/nyanya/android/traditionalt9/settings/Setting.java @@ -0,0 +1,41 @@ +package org.nyanya.android.traditionalt9.settings; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.View; + +import org.nyanya.android.traditionalt9.R; + +public class Setting { + String title; + String summary = null; + public String id; + public int widgetID = 0; + public int layout; + protected View view; + + public Setting (Context context, AttributeSet attrs, Object[] isettings) { + // http://stackoverflow.com/a/8488691 + for (int i = 0; i < attrs.getAttributeCount(); i++) { + String attr = attrs.getAttributeName(i); + if ("title".equals(attr)) { + // load string resource + title = context.getString(attrs.getAttributeResourceValue(i, 0)); + } else if ("summary".equals(attr)) { + summary = context.getString(attrs.getAttributeResourceValue(i, 0)); + } else if ("id".equals(attr)){ + id = attrs.getAttributeValue(i); + } + } + if (summary == null) + layout = R.layout.setting; + else + layout = R.layout.setting_sum; + } + + public void clicked(final Context context) {} + + public void setView(View view) { + this.view = view; + } +} diff --git a/src/org/nyanya/android/traditionalt9/settings/SettingAdapter.java b/src/org/nyanya/android/traditionalt9/settings/SettingAdapter.java new file mode 100644 index 00000000..9e59bb56 --- /dev/null +++ b/src/org/nyanya/android/traditionalt9/settings/SettingAdapter.java @@ -0,0 +1,45 @@ +package org.nyanya.android.traditionalt9.settings; + +// https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView + +import android.content.Context; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.TextView; + +import org.nyanya.android.traditionalt9.R; + +import java.util.ArrayList; + +public class SettingAdapter extends ArrayAdapter { + public SettingAdapter(Context context, ArrayList settings) { + super(context, 0, settings); + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + // Get the data item for this position + Setting setting = getItem(position); + final LayoutInflater layoutInflater = LayoutInflater.from(getContext()); + // Check if an existing view is being reused, otherwise inflate the view + if (convertView == null) { + convertView = layoutInflater.inflate(setting.layout, parent, false); + } + setting.setView(convertView); + // Lookup view for data population + ((TextView) convertView.findViewById(R.id.title)).setText(setting.title); + if (setting.summary != null) + ((TextView) convertView.findViewById(R.id.summary)).setText(setting.summary); + + if (setting.widgetID != 0) { + final ViewGroup widgetFrame = (ViewGroup) convertView.findViewById(R.id.widget_frame); + layoutInflater.inflate(setting.widgetID, widgetFrame); + } + + // Return the completed view to render on screen + return convertView; + } +} diff --git a/src/org/nyanya/android/traditionalt9/settings/SettingCheck.java b/src/org/nyanya/android/traditionalt9/settings/SettingCheck.java new file mode 100644 index 00000000..e0ab06c0 --- /dev/null +++ b/src/org/nyanya/android/traditionalt9/settings/SettingCheck.java @@ -0,0 +1,37 @@ +package org.nyanya.android.traditionalt9.settings; + + +import android.content.Context; +import android.util.AttributeSet; + +import org.nyanya.android.traditionalt9.R; + +public class SettingCheck extends Setting { + boolean value; + boolean defaultValue; + + public SettingCheck (Context context, AttributeSet attrs, Object[] isettings) { + super(context, attrs, isettings); + // http://stackoverflow.com/a/8488691 + for (int i = 0; i < attrs.getAttributeCount(); i++) { + String attr = attrs.getAttributeName(i); + if ("defaultValue".equals(attr)) { + defaultValue = attrs.getAttributeBooleanValue(i, false); + } + } + if (id.equals("pref_mode_notify")){ + if (isettings[2] != null) + value = isettings[2].equals(1); + else + value = defaultValue; + } + widgetID = R.layout.checkbox; + } + + @Override + public void clicked(Context context) { + + } + + +} diff --git a/src/org/nyanya/android/traditionalt9/settings/SettingList.java b/src/org/nyanya/android/traditionalt9/settings/SettingList.java new file mode 100644 index 00000000..853169c7 --- /dev/null +++ b/src/org/nyanya/android/traditionalt9/settings/SettingList.java @@ -0,0 +1,66 @@ +package org.nyanya.android.traditionalt9.settings; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.util.AttributeSet; + +import org.nyanya.android.traditionalt9.R; +import org.nyanya.android.traditionalt9.T9DB; +import org.nyanya.android.traditionalt9.T9DB.DBSettings.SETTING; + +public class SettingList extends Setting { + String[] entries; + int[] entryValues; + int defaultValue; + int value; + + public SettingList (Context context, AttributeSet attrs, Object[] isettings) { + super(context, attrs, isettings); + // http://stackoverflow.com/a/8488691 + for (int i = 0; i < attrs.getAttributeCount(); i++) { + String attr = attrs.getAttributeName(i); + if ("defaultValue".equals(attr)) { + defaultValue = attrs.getAttributeIntValue(i, -1); + } else if ("entryValues".equals(attr)) { + // load string resource + entryValues = context.getResources().getIntArray(attrs.getAttributeResourceValue(i, 0)); + } else if ("entries".equals(attr)) { + entries = context.getResources().getStringArray(attrs.getAttributeResourceValue(i, 0)); + } + } + + if (id.equals("pref_inputmode")){ + if (isettings[0] != null) + value = (Integer)isettings[0]; + else + value = defaultValue; + } + widgetID = R.layout.preference_dialog; + layout = R.layout.setting_widget; + } + + public void clicked(final Context context) { + AlertDialog.Builder builderSingle = new AlertDialog.Builder(context); + builderSingle.setTitle(title); + + builderSingle.setNegativeButton(android.R.string.cancel, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + builderSingle.setSingleChoiceItems(entries, value, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + T9DB.getInstance(context).storeSettingInt(SETTING.get(id), entryValues[which]); + value = entryValues[which]; + dialog.dismiss(); + } + }); + builderSingle.show(); + } +} diff --git a/src/org/nyanya/android/traditionalt9/settings/SettingMultiList.java b/src/org/nyanya/android/traditionalt9/settings/SettingMultiList.java new file mode 100644 index 00000000..f0b1f85f --- /dev/null +++ b/src/org/nyanya/android/traditionalt9/settings/SettingMultiList.java @@ -0,0 +1,87 @@ +package org.nyanya.android.traditionalt9.settings; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.util.AttributeSet; +import android.util.Log; +import android.widget.TextView; + +import org.nyanya.android.traditionalt9.LangHelper; +import org.nyanya.android.traditionalt9.R; +import org.nyanya.android.traditionalt9.T9DB; +import org.nyanya.android.traditionalt9.T9DB.DBSettings.SETTING; + +public class SettingMultiList extends SettingList { + boolean[] selectedEntries = new boolean[0]; + + public SettingMultiList (Context context, AttributeSet attrs, Object[] isettings) { + super(context, attrs, isettings); + selectedEntries = new boolean[entries.length]; + Log.d("Multi", "len:" + entries.length + " setting:" + isettings[1]); + for (LangHelper.LANGUAGE l : LangHelper.buildLangs((Integer)isettings[1])) { + Log.d("Multi", "index:" + l.index); + selectedEntries[l.index] = true; + } + summary = buildItems(); + } + + public void clicked(final Context context) { + AlertDialog.Builder builderMulti = new AlertDialog.Builder(context); + builderMulti.setTitle(title); + + builderMulti.setNegativeButton(android.R.string.cancel, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + builderMulti.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + T9DB.getInstance(context).storeSettingInt(SETTING.get(id), LangHelper.shrinkLangs(buildSelection())); + summary = buildItems(); + dialog.dismiss(); + ((TextView)view.findViewById(R.id.summary)).setText(summary); + } + }); + builderMulti.setMultiChoiceItems(entries, selectedEntries, + new DialogInterface.OnMultiChoiceClickListener() { + @Override + public void onClick(DialogInterface dialog, int which, boolean opt) { + selectedEntries[which] = opt; + } + }); + builderMulti.show(); + } + + private int[] buildSelection(){ + int count = 0; + for (boolean b: selectedEntries) {if (b) count++;} + int[] selection = new int[count]; + count = 0; + for (int x=0;x 1) + sb.setLength(sb.length()-2); + return sb.toString(); + } +} diff --git a/src/pl/wavesoftware/widget/MultiSelectListPreference.java b/src/pl/wavesoftware/widget/MultiSelectListPreference.java index f5f2b216..955ff07c 100644 --- a/src/pl/wavesoftware/widget/MultiSelectListPreference.java +++ b/src/pl/wavesoftware/widget/MultiSelectListPreference.java @@ -12,13 +12,14 @@ import android.content.DialogInterface; import android.content.DialogInterface.OnMultiChoiceClickListener; import android.content.res.TypedArray; import android.preference.ListPreference; +import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; public class MultiSelectListPreference extends ListPreference { private String separator; - private static final String DEFAULT_SEPARATOR = "\u0001\u0007\u001D\u0007\u0001"; + private static final String DEFAULT_SEPARATOR = "|"; private boolean[] entryChecked; public MultiSelectListPreference(Context context, AttributeSet attributeSet) { @@ -55,7 +56,7 @@ public class MultiSelectListPreference extends ListPreference { if (val == null || "".equals(val)) { return new CharSequence[0]; } else { - return ((String) val).split(separator); + return ((String) val).split("\\"+separator); } } @@ -65,7 +66,7 @@ public class MultiSelectListPreference extends ListPreference { //Log.w("MultiSelectPref.defaultunpack", "val is null or empty"); return new int[] {0}; //default pref } else { - String[] sa = ((String) val).split(DEFAULT_SEPARATOR); + String[] sa = ((String) val).split("\\"+DEFAULT_SEPARATOR); if (sa.length < 1) { Log.w("MultiSelectPref.defaultunpack", "split is less than 1"); return new int[] {0}; //default pref @@ -115,7 +116,7 @@ public class MultiSelectListPreference extends ListPreference { } } - String value = join(values, separator); + String value = TextUtils.join(separator, values); setSummary(prepareSummary(values)); setValueAndEvent(value); } @@ -143,7 +144,7 @@ public class MultiSelectListPreference extends ListPreference { } ix += 1; } - return join(titles, ", "); + return TextUtils.join(", ", titles); } @Override @@ -157,12 +158,11 @@ public class MultiSelectListPreference extends ListPreference { String value = null; CharSequence[] defaultValue; if (rawDefaultValue == null) { - defaultValue = new CharSequence[0]; + defaultValue = new CharSequence[] {"0"}; } else { defaultValue = (CharSequence[]) rawDefaultValue; } - List joined = Arrays.asList(defaultValue); - String joinedDefaultValue = join(joined, separator); + String joinedDefaultValue = TextUtils.join(separator, defaultValue); if (restoreValue) { value = getPersistedString(joinedDefaultValue); } else { @@ -173,26 +173,4 @@ public class MultiSelectListPreference extends ListPreference { setValueAndEvent(value); } - /** - * Joins array of object to single string by separator - * - * Credits to kurellajunior on this post - * http://snippets.dzone.com/posts/show/91 - * - * @param iterable - * any kind of iterable ex.: ["a", "b", "c"] - * @param separator - * separetes entries ex.: "," - * @return joined string ex.: "a,b,c" - */ - protected static String join(Iterable iterable, String separator) { - Iterator oIter; - if (iterable == null || (!(oIter = iterable.iterator()).hasNext())) - return ""; - StringBuilder oBuilder = new StringBuilder(String.valueOf(oIter.next())); - while (oIter.hasNext()) - oBuilder.append(separator).append(oIter.next()); - return oBuilder.toString(); - } - }