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