1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settings.inputmethod;
18
19import android.app.Activity;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.database.Cursor;
23import android.os.Bundle;
24import android.provider.UserDictionary;
25import android.text.TextUtils;
26import android.view.View;
27import android.widget.EditText;
28
29import com.android.settings.R;
30import com.android.settings.UserDictionarySettings;
31import com.android.settings.Utils;
32
33import java.util.ArrayList;
34import java.util.Locale;
35import java.util.TreeSet;
36
37/**
38 * A container class to factor common code to UserDictionaryAddWordFragment
39 * and UserDictionaryAddWordActivity.
40 */
41public class UserDictionaryAddWordContents {
42    public static final String EXTRA_MODE = "mode";
43    public static final String EXTRA_WORD = "word";
44    public static final String EXTRA_SHORTCUT = "shortcut";
45    public static final String EXTRA_LOCALE = "locale";
46    public static final String EXTRA_ORIGINAL_WORD = "originalWord";
47    public static final String EXTRA_ORIGINAL_SHORTCUT = "originalShortcut";
48
49    public static final int MODE_EDIT = 0;
50    public static final int MODE_INSERT = 1;
51
52    private static final int FREQUENCY_FOR_USER_DICTIONARY_ADDS = 250;
53
54    private final int mMode; // Either MODE_EDIT or MODE_INSERT
55    private final EditText mWordEditText;
56    private final EditText mShortcutEditText;
57    private String mLocale;
58    private final String mOldWord;
59    private final String mOldShortcut;
60
61    /* package */ UserDictionaryAddWordContents(final View view, final Bundle args) {
62        mWordEditText = (EditText)view.findViewById(R.id.user_dictionary_add_word_text);
63        mShortcutEditText = (EditText)view.findViewById(R.id.user_dictionary_add_shortcut);
64        final String word = args.getString(EXTRA_WORD);
65        if (null != word) {
66            mWordEditText.setText(word);
67            mWordEditText.setSelection(word.length());
68        }
69        final String shortcut = args.getString(EXTRA_SHORTCUT);
70        if (null != shortcut && null != mShortcutEditText) {
71            mShortcutEditText.setText(shortcut);
72        }
73        mMode = args.getInt(EXTRA_MODE); // default return value for #getInt() is 0 = MODE_EDIT
74        mOldWord = args.getString(EXTRA_WORD);
75        mOldShortcut = args.getString(EXTRA_SHORTCUT);
76        updateLocale(args.getString(EXTRA_LOCALE));
77    }
78
79    // locale may be null, this means default locale
80    // It may also be the empty string, which means "all locales"
81    /* package */ void updateLocale(final String locale) {
82        mLocale = null == locale ? Locale.getDefault().toString() : locale;
83    }
84
85    /* package */ void saveStateIntoBundle(final Bundle outState) {
86        outState.putString(EXTRA_WORD, mWordEditText.getText().toString());
87        outState.putString(EXTRA_ORIGINAL_WORD, mOldWord);
88        if (null != mShortcutEditText) {
89            outState.putString(EXTRA_SHORTCUT, mShortcutEditText.getText().toString());
90        }
91        if (null != mOldShortcut) {
92            outState.putString(EXTRA_ORIGINAL_SHORTCUT, mOldShortcut);
93        }
94        outState.putString(EXTRA_LOCALE, mLocale);
95    }
96
97    /* package */ void delete(final Context context) {
98        if (MODE_EDIT == mMode && !TextUtils.isEmpty(mOldWord)) {
99            // Mode edit: remove the old entry.
100            final ContentResolver resolver = context.getContentResolver();
101            UserDictionarySettings.deleteWord(mOldWord, mOldShortcut, resolver);
102        }
103        // If we are in add mode, nothing was added, so we don't need to do anything.
104    }
105
106    /* package */ int apply(final Context context, final Bundle outParameters) {
107        if (null != outParameters) saveStateIntoBundle(outParameters);
108        final ContentResolver resolver = context.getContentResolver();
109        if (MODE_EDIT == mMode && !TextUtils.isEmpty(mOldWord)) {
110            // Mode edit: remove the old entry.
111            UserDictionarySettings.deleteWord(mOldWord, mOldShortcut, resolver);
112        }
113        final String newWord = mWordEditText.getText().toString();
114        final String newShortcut;
115        if (null == mShortcutEditText) {
116            newShortcut = null;
117        } else {
118            final String tmpShortcut = mShortcutEditText.getText().toString();
119            if (TextUtils.isEmpty(tmpShortcut)) {
120                newShortcut = null;
121            } else {
122                newShortcut = tmpShortcut;
123            }
124        }
125        if (TextUtils.isEmpty(newWord)) {
126            // If the word is somehow empty, don't insert it.
127            return UserDictionaryAddWordActivity.CODE_CANCEL;
128        }
129        // If there is no shortcut, and the word already exists in the database, then we
130        // should not insert, because either A. the word exists with no shortcut, in which
131        // case the exact same thing we want to insert is already there, or B. the word
132        // exists with at least one shortcut, in which case it has priority on our word.
133        if (hasWord(newWord, context)) return UserDictionaryAddWordActivity.CODE_ALREADY_PRESENT;
134
135        // Disallow duplicates. If the same word with no shortcut is defined, remove it; if
136        // the same word with the same shortcut is defined, remove it; but we don't mind if
137        // there is the same word with a different, non-empty shortcut.
138        UserDictionarySettings.deleteWord(newWord, null, resolver);
139        if (!TextUtils.isEmpty(newShortcut)) {
140            // If newShortcut is empty we just deleted this, no need to do it again
141            UserDictionarySettings.deleteWord(newWord, newShortcut, resolver);
142        }
143
144        // In this class we use the empty string to represent 'all locales' and mLocale cannot
145        // be null. However the addWord method takes null to mean 'all locales'.
146        UserDictionary.Words.addWord(context, newWord.toString(),
147                FREQUENCY_FOR_USER_DICTIONARY_ADDS, newShortcut,
148                TextUtils.isEmpty(mLocale) ? null : Utils.createLocaleFromString(mLocale));
149
150        return UserDictionaryAddWordActivity.CODE_WORD_ADDED;
151    }
152
153    private static final String[] HAS_WORD_PROJECTION = { UserDictionary.Words.WORD };
154    private static final String HAS_WORD_SELECTION_ONE_LOCALE = UserDictionary.Words.WORD
155            + "=? AND " + UserDictionary.Words.LOCALE + "=?";
156    private static final String HAS_WORD_SELECTION_ALL_LOCALES = UserDictionary.Words.WORD
157            + "=? AND " + UserDictionary.Words.LOCALE + " is null";
158    private boolean hasWord(final String word, final Context context) {
159        final Cursor cursor;
160        // mLocale == "" indicates this is an entry for all languages. Here, mLocale can't
161        // be null at all (it's ensured by the updateLocale method).
162        if ("".equals(mLocale)) {
163            cursor = context.getContentResolver().query(UserDictionary.Words.CONTENT_URI,
164                      HAS_WORD_PROJECTION, HAS_WORD_SELECTION_ALL_LOCALES,
165                      new String[] { word }, null /* sort order */);
166        } else {
167            cursor = context.getContentResolver().query(UserDictionary.Words.CONTENT_URI,
168                      HAS_WORD_PROJECTION, HAS_WORD_SELECTION_ONE_LOCALE,
169                      new String[] { word, mLocale }, null /* sort order */);
170        }
171        try {
172            if (null == cursor) return false;
173            return cursor.getCount() > 0;
174        } finally {
175            if (null != cursor) cursor.close();
176        }
177    }
178
179    public static class LocaleRenderer {
180        private final String mLocaleString;
181        private final String mDescription;
182        // LocaleString may NOT be null.
183        public LocaleRenderer(final Context context, final String localeString) {
184            mLocaleString = localeString;
185            if (null == localeString) {
186                mDescription = context.getString(R.string.user_dict_settings_more_languages);
187            } else if ("".equals(localeString)) {
188                mDescription = context.getString(R.string.user_dict_settings_all_languages);
189            } else {
190                mDescription = Utils.createLocaleFromString(localeString).getDisplayName();
191            }
192        }
193        @Override
194        public String toString() {
195            return mDescription;
196        }
197        public String getLocaleString() {
198            return mLocaleString;
199        }
200        // "More languages..." is null ; "All languages" is the empty string.
201        public boolean isMoreLanguages() {
202            return null == mLocaleString;
203        }
204    }
205
206    private static void addLocaleDisplayNameToList(final Context context,
207            final ArrayList<LocaleRenderer> list, final String locale) {
208        if (null != locale) {
209            list.add(new LocaleRenderer(context, locale));
210        }
211    }
212
213    // Helper method to get the list of locales to display for this word
214    public ArrayList<LocaleRenderer> getLocalesList(final Activity activity) {
215        final TreeSet<String> locales = UserDictionaryList.getUserDictionaryLocalesSet(activity);
216        // Remove our locale if it's in, because we're always gonna put it at the top
217        locales.remove(mLocale); // mLocale may not be null
218        final String systemLocale = Locale.getDefault().toString();
219        // The system locale should be inside. We want it at the 2nd spot.
220        locales.remove(systemLocale); // system locale may not be null
221        locales.remove(""); // Remove the empty string if it's there
222        final ArrayList<LocaleRenderer> localesList = new ArrayList<LocaleRenderer>();
223        // Add the passed locale, then the system locale at the top of the list. Add an
224        // "all languages" entry at the bottom of the list.
225        addLocaleDisplayNameToList(activity, localesList, mLocale);
226        if (!systemLocale.equals(mLocale)) {
227            addLocaleDisplayNameToList(activity, localesList, systemLocale);
228        }
229        for (final String l : locales) {
230            // TODO: sort in unicode order
231            addLocaleDisplayNameToList(activity, localesList, l);
232        }
233        if (!"".equals(mLocale)) {
234            // If mLocale is "", then we already inserted the "all languages" item, so don't do it
235            addLocaleDisplayNameToList(activity, localesList, ""); // meaning: all languages
236        }
237        localesList.add(new LocaleRenderer(activity, null)); // meaning: select another locale
238        return localesList;
239    }
240}
241