• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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 
17 package com.android.inputmethod.latin;
18 
19 import android.content.ContentProviderClient;
20 import android.content.ContentResolver;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.database.ContentObserver;
24 import android.database.Cursor;
25 import android.provider.UserDictionary.Words;
26 import android.text.TextUtils;
27 
28 import com.android.inputmethod.keyboard.ProximityInfo;
29 
30 import java.util.Arrays;
31 
32 // TODO: This class is superseded by {@link UserBinaryDictionary}. Should be cleaned up.
33 /**
34  * An expandable dictionary that stores the words in the user unigram dictionary.
35  *
36  * @deprecated Use {@link UserBinaryDictionary}.
37  */
38 @Deprecated
39 public class UserDictionary extends ExpandableDictionary {
40 
41     // TODO: use Words.SHORTCUT when it's public in the SDK
42     final static String SHORTCUT = "shortcut";
43     private static final String[] PROJECTION_QUERY = {
44         Words.WORD,
45         SHORTCUT,
46         Words.FREQUENCY,
47     };
48 
49     // This is not exported by the framework so we pretty much have to write it here verbatim
50     private static final String ACTION_USER_DICTIONARY_INSERT =
51             "com.android.settings.USER_DICTIONARY_INSERT";
52 
53     private ContentObserver mObserver;
54     final private String mLocale;
55     final private boolean mAlsoUseMoreRestrictiveLocales;
56 
UserDictionary(final Context context, final String locale)57     public UserDictionary(final Context context, final String locale) {
58         this(context, locale, false);
59     }
60 
UserDictionary(final Context context, final String locale, final boolean alsoUseMoreRestrictiveLocales)61     public UserDictionary(final Context context, final String locale,
62             final boolean alsoUseMoreRestrictiveLocales) {
63         super(context, Suggest.DIC_USER);
64         if (null == locale) throw new NullPointerException(); // Catch the error earlier
65         mLocale = locale;
66         mAlsoUseMoreRestrictiveLocales = alsoUseMoreRestrictiveLocales;
67         // Perform a managed query. The Activity will handle closing and re-querying the cursor
68         // when needed.
69         ContentResolver cres = context.getContentResolver();
70 
71         mObserver = new ContentObserver(null) {
72             @Override
73             public void onChange(boolean self) {
74                 setRequiresReload(true);
75             }
76         };
77         cres.registerContentObserver(Words.CONTENT_URI, true, mObserver);
78 
79         loadDictionary();
80     }
81 
82     @Override
close()83     public synchronized void close() {
84         if (mObserver != null) {
85             getContext().getContentResolver().unregisterContentObserver(mObserver);
86             mObserver = null;
87         }
88         super.close();
89     }
90 
91     @Override
loadDictionaryAsync()92     public void loadDictionaryAsync() {
93         // Split the locale. For example "en" => ["en"], "de_DE" => ["de", "DE"],
94         // "en_US_foo_bar_qux" => ["en", "US", "foo_bar_qux"] because of the limit of 3.
95         // This is correct for locale processing.
96         // For this example, we'll look at the "en_US_POSIX" case.
97         final String[] localeElements =
98                 TextUtils.isEmpty(mLocale) ? new String[] {} : mLocale.split("_", 3);
99         final int length = localeElements.length;
100 
101         final StringBuilder request = new StringBuilder("(locale is NULL)");
102         String localeSoFar = "";
103         // At start, localeElements = ["en", "US", "POSIX"] ; localeSoFar = "" ;
104         // and request = "(locale is NULL)"
105         for (int i = 0; i < length; ++i) {
106             // i | localeSoFar    | localeElements
107             // 0 | ""             | ["en", "US", "POSIX"]
108             // 1 | "en_"          | ["en", "US", "POSIX"]
109             // 2 | "en_US_"       | ["en", "en_US", "POSIX"]
110             localeElements[i] = localeSoFar + localeElements[i];
111             localeSoFar = localeElements[i] + "_";
112             // i | request
113             // 0 | "(locale is NULL)"
114             // 1 | "(locale is NULL) or (locale=?)"
115             // 2 | "(locale is NULL) or (locale=?) or (locale=?)"
116             request.append(" or (locale=?)");
117         }
118         // At the end, localeElements = ["en", "en_US", "en_US_POSIX"]; localeSoFar = en_US_POSIX_"
119         // and request = "(locale is NULL) or (locale=?) or (locale=?) or (locale=?)"
120 
121         final String[] requestArguments;
122         // If length == 3, we already have all the arguments we need (common prefix is meaningless
123         // inside variants
124         if (mAlsoUseMoreRestrictiveLocales && length < 3) {
125             request.append(" or (locale like ?)");
126             // The following creates an array with one more (null) position
127             final String[] localeElementsWithMoreRestrictiveLocalesIncluded =
128                     Arrays.copyOf(localeElements, length + 1);
129             localeElementsWithMoreRestrictiveLocalesIncluded[length] =
130                     localeElements[length - 1] + "_%";
131             requestArguments = localeElementsWithMoreRestrictiveLocalesIncluded;
132             // If for example localeElements = ["en"]
133             // then requestArguments = ["en", "en_%"]
134             // and request = (locale is NULL) or (locale=?) or (locale like ?)
135             // If localeElements = ["en", "en_US"]
136             // then requestArguments = ["en", "en_US", "en_US_%"]
137         } else {
138             requestArguments = localeElements;
139         }
140         final Cursor cursor = getContext().getContentResolver()
141                 .query(Words.CONTENT_URI, PROJECTION_QUERY, request.toString(),
142                         requestArguments, null);
143         try {
144             addWords(cursor);
145         } finally {
146             if (null != cursor) cursor.close();
147         }
148     }
149 
isEnabled()150     public boolean isEnabled() {
151         final ContentResolver cr = getContext().getContentResolver();
152         final ContentProviderClient client = cr.acquireContentProviderClient(Words.CONTENT_URI);
153         if (client != null) {
154             client.release();
155             return true;
156         } else {
157             return false;
158         }
159     }
160 
161     /**
162      * Adds a word to the user dictionary and makes it persistent.
163      *
164      * This will call upon the system interface to do the actual work through the intent
165      * readied by the system to this effect.
166      *
167      * @param word the word to add. If the word is capitalized, then the dictionary will
168      * recognize it as a capitalized word when searched.
169      * @param frequency the frequency of occurrence of the word. A frequency of 255 is considered
170      * the highest.
171      * @TODO use a higher or float range for frequency
172      */
addWordToUserDictionary(final String word, final int frequency)173     public synchronized void addWordToUserDictionary(final String word, final int frequency) {
174         // Force load the dictionary here synchronously
175         if (getRequiresReload()) loadDictionaryAsync();
176         // TODO: do something for the UI. With the following, any sufficiently long word will
177         // look like it will go to the user dictionary but it won't.
178         // Safeguard against adding long words. Can cause stack overflow.
179         if (word.length() >= getMaxWordLength()) return;
180 
181         // TODO: Add an argument to the intent to specify the frequency.
182         Intent intent = new Intent(ACTION_USER_DICTIONARY_INSERT);
183         intent.putExtra(Words.WORD, word);
184         intent.putExtra(Words.LOCALE, mLocale);
185         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
186         getContext().startActivity(intent);
187     }
188 
189     @Override
getWords(final WordComposer codes, final CharSequence prevWordForBigrams, final WordCallback callback, final ProximityInfo proximityInfo)190     public synchronized void getWords(final WordComposer codes,
191             final CharSequence prevWordForBigrams, final WordCallback callback,
192             final ProximityInfo proximityInfo) {
193         super.getWords(codes, prevWordForBigrams, callback, proximityInfo);
194     }
195 
196     @Override
isValidWord(CharSequence word)197     public synchronized boolean isValidWord(CharSequence word) {
198         return super.isValidWord(word);
199     }
200 
addWords(Cursor cursor)201     private void addWords(Cursor cursor) {
202         clearDictionary();
203         if (cursor == null) return;
204         final int maxWordLength = getMaxWordLength();
205         if (cursor.moveToFirst()) {
206             final int indexWord = cursor.getColumnIndex(Words.WORD);
207             final int indexShortcut = cursor.getColumnIndex(SHORTCUT);
208             final int indexFrequency = cursor.getColumnIndex(Words.FREQUENCY);
209             while (!cursor.isAfterLast()) {
210                 String word = cursor.getString(indexWord);
211                 String shortcut = cursor.getString(indexShortcut);
212                 int frequency = cursor.getInt(indexFrequency);
213                 // Safeguard against adding really long words. Stack may overflow due
214                 // to recursion
215                 if (word.length() < maxWordLength) {
216                     super.addWord(word, null, frequency);
217                 }
218                 if (null != shortcut && shortcut.length() < maxWordLength) {
219                     super.addWord(shortcut, word, frequency);
220                 }
221                 cursor.moveToNext();
222             }
223         }
224     }
225 }
226