SpellChecker.java revision c95b7412c2d4b6dca0fdee631bd777b6148ddf81
1/*
2 * Copyright (C) 2011 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 android.widget;
18
19import android.content.Context;
20import android.text.Editable;
21import android.text.Selection;
22import android.text.Spanned;
23import android.text.method.WordIterator;
24import android.text.style.SpellCheckSpan;
25import android.text.style.SuggestionSpan;
26import android.view.textservice.SpellCheckerSession;
27import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener;
28import android.view.textservice.SuggestionsInfo;
29import android.view.textservice.TextInfo;
30import android.view.textservice.TextServicesManager;
31
32import com.android.internal.util.ArrayUtils;
33
34import java.text.BreakIterator;
35import java.util.Locale;
36
37
38/**
39 * Helper class for TextView. Bridge between the TextView and the Dictionnary service.
40 *
41 * @hide
42 */
43public class SpellChecker implements SpellCheckerSessionListener {
44
45    // No more than this number of words will be parsed on each iteration to ensure a minimum
46    // lock of the UI thread
47    public static final int MAX_NUMBER_OF_WORDS = 10;
48
49    // Safe estimate, will ensure that the interval below usually does not have to be updated
50    public static final int AVERAGE_WORD_LENGTH = 10;
51
52    // When parsing, use a character window of that size. Will be shifted if needed
53    public static final int WORD_ITERATOR_INTERVAL = AVERAGE_WORD_LENGTH * MAX_NUMBER_OF_WORDS;
54
55    private final static int SPELL_PAUSE_DURATION = 400; // milliseconds
56
57    private final TextView mTextView;
58
59    SpellCheckerSession mSpellCheckerSession;
60    final int mCookie;
61
62    // Paired arrays for the (id, spellCheckSpan) pair. A negative id means the associated
63    // SpellCheckSpan has been recycled and can be-reused.
64    // Contains null SpellCheckSpans after index mLength.
65    private int[] mIds;
66    private SpellCheckSpan[] mSpellCheckSpans;
67    // The mLength first elements of the above arrays have been initialized
68    private int mLength;
69
70    // Parsers on chunck of text, cutting text into words that will be checked
71    private SpellParser[] mSpellParsers = new SpellParser[0];
72
73    private int mSpanSequenceCounter = 0;
74
75    private Locale mCurrentLocale;
76
77    public SpellChecker(TextView textView) {
78        mTextView = textView;
79
80        // Arbitrary: these arrays will automatically double their sizes on demand
81        final int size = ArrayUtils.idealObjectArraySize(1);
82        mIds = new int[size];
83        mSpellCheckSpans = new SpellCheckSpan[size];
84
85        setLocale(mTextView.getTextServicesLocale());
86
87        mCookie = hashCode();
88    }
89
90    private void setLocale(Locale locale) {
91        closeSession();
92        final TextServicesManager textServicesManager = (TextServicesManager)
93                mTextView.getContext().getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
94        if (!textServicesManager.isSpellCheckerEnabled()) {
95            mSpellCheckerSession = null;
96        } else {
97            mSpellCheckerSession = textServicesManager.newSpellCheckerSession(
98                    null /* Bundle not currently used by the textServicesManager */,
99                    locale, this,
100                    false /* means any available languages from current spell checker */);
101        }
102        mCurrentLocale = locale;
103
104        // Restore SpellCheckSpans in pool
105        for (int i = 0; i < mLength; i++) {
106            mSpellCheckSpans[i].setSpellCheckInProgress(false);
107            mIds[i] = -1;
108        }
109        mLength = 0;
110
111        mSpellParsers = new SpellParser[0];
112
113        // This class is the global listener for locale change: warn other locale-aware objects
114        mTextView.onLocaleChanged();
115    }
116
117    /**
118     * @return true if a spell checker session has successfully been created. Returns false if not,
119     * for instance when spell checking has been disabled in settings.
120     */
121    private boolean isSessionActive() {
122        return mSpellCheckerSession != null;
123    }
124
125    public void closeSession() {
126        if (mSpellCheckerSession != null) {
127            mSpellCheckerSession.close();
128        }
129
130        stopAllSpellParsers();
131    }
132
133    private void stopAllSpellParsers() {
134        final int length = mSpellParsers.length;
135        for (int i = 0; i < length; i++) {
136            mSpellParsers[i].stop();
137        }
138    }
139
140    private int nextSpellCheckSpanIndex() {
141        for (int i = 0; i < mLength; i++) {
142            if (mIds[i] < 0) return i;
143        }
144
145        if (mLength == mSpellCheckSpans.length) {
146            final int newSize = mLength * 2;
147            int[] newIds = new int[newSize];
148            SpellCheckSpan[] newSpellCheckSpans = new SpellCheckSpan[newSize];
149            System.arraycopy(mIds, 0, newIds, 0, mLength);
150            System.arraycopy(mSpellCheckSpans, 0, newSpellCheckSpans, 0, mLength);
151            mIds = newIds;
152            mSpellCheckSpans = newSpellCheckSpans;
153        }
154
155        mSpellCheckSpans[mLength] = new SpellCheckSpan();
156        mLength++;
157        return mLength - 1;
158    }
159
160    private void addSpellCheckSpan(Editable editable, int start, int end) {
161        final int index = nextSpellCheckSpanIndex();
162        editable.setSpan(mSpellCheckSpans[index], start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
163        mIds[index] = mSpanSequenceCounter++;
164    }
165
166    public void removeSpellCheckSpan(SpellCheckSpan spellCheckSpan) {
167        for (int i = 0; i < mLength; i++) {
168            if (mSpellCheckSpans[i] == spellCheckSpan) {
169                mSpellCheckSpans[i].setSpellCheckInProgress(false);
170                mIds[i] = -1;
171                return;
172            }
173        }
174    }
175
176    public void onSelectionChanged() {
177        spellCheck();
178    }
179
180    public void spellCheck(int start, int end) {
181        final Locale locale = mTextView.getTextServicesLocale();
182        if (mCurrentLocale == null || (!(mCurrentLocale.equals(locale)))) {
183            setLocale(locale);
184            // Re-check the entire text
185            start = 0;
186            end = mTextView.getText().length();
187        }
188
189        if (!isSessionActive()) return;
190
191        // Find first available SpellParser from pool
192        final int length = mSpellParsers.length;
193        for (int i = 0; i < length; i++) {
194            final SpellParser spellParser = mSpellParsers[i];
195            if (!spellParser.isParsing()) {
196                spellParser.init(start, end);
197                spellParser.parse();
198                return;
199            }
200        }
201
202        // No available parser found in pool, create a new one
203        SpellParser[] newSpellParsers = new SpellParser[length + 1];
204        System.arraycopy(mSpellParsers, 0, newSpellParsers, 0, length);
205        mSpellParsers = newSpellParsers;
206
207        SpellParser spellParser = new SpellParser();
208        mSpellParsers[length] = spellParser;
209        spellParser.init(start, end);
210        spellParser.parse();
211    }
212
213    private void spellCheck() {
214        if (mSpellCheckerSession == null) return;
215
216        Editable editable = (Editable) mTextView.getText();
217        final int selectionStart = Selection.getSelectionStart(editable);
218        final int selectionEnd = Selection.getSelectionEnd(editable);
219
220        TextInfo[] textInfos = new TextInfo[mLength];
221        int textInfosCount = 0;
222
223        final String text = editable.toString();
224        for (int i = 0; i < mLength; i++) {
225            final SpellCheckSpan spellCheckSpan = mSpellCheckSpans[i];
226            if (spellCheckSpan.isSpellCheckInProgress()) continue;
227
228            final int start = editable.getSpanStart(spellCheckSpan);
229            final int end = editable.getSpanEnd(spellCheckSpan);
230
231            // Do not check this word if the user is currently editing it
232            if (start >= 0 && end > start && (selectionEnd < start || selectionStart > end)) {
233                final String word = text.substring(start, end);
234                spellCheckSpan.setSpellCheckInProgress(true);
235                textInfos[textInfosCount++] = new TextInfo(word, mCookie, mIds[i]);
236            }
237        }
238
239        if (textInfosCount > 0) {
240            if (textInfosCount < textInfos.length) {
241                TextInfo[] textInfosCopy = new TextInfo[textInfosCount];
242                System.arraycopy(textInfos, 0, textInfosCopy, 0, textInfosCount);
243                textInfos = textInfosCopy;
244            }
245
246            mSpellCheckerSession.getSuggestions(textInfos, SuggestionSpan.SUGGESTIONS_MAX_SIZE,
247                    false /* TODO Set sequentialWords to true for initial spell check */);
248        }
249    }
250
251    @Override
252    public void onGetSuggestions(SuggestionsInfo[] results) {
253        Editable editable = (Editable) mTextView.getText();
254
255        for (int i = 0; i < results.length; i++) {
256            SuggestionsInfo suggestionsInfo = results[i];
257            if (suggestionsInfo.getCookie() != mCookie) continue;
258            final int sequenceNumber = suggestionsInfo.getSequence();
259
260            for (int j = 0; j < mLength; j++) {
261                if (sequenceNumber == mIds[j]) {
262                    final int attributes = suggestionsInfo.getSuggestionsAttributes();
263                    boolean isInDictionary =
264                            ((attributes & SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) > 0);
265                    boolean looksLikeTypo =
266                            ((attributes & SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) > 0);
267
268                    SpellCheckSpan spellCheckSpan = mSpellCheckSpans[j];
269                    if (!isInDictionary && looksLikeTypo) {
270                        createMisspelledSuggestionSpan(editable, suggestionsInfo, spellCheckSpan);
271                    }
272                    editable.removeSpan(spellCheckSpan);
273                    break;
274                }
275            }
276        }
277
278        mTextView.postDelayed(new Runnable() {
279            @Override
280            public void run() {
281                final int length = mSpellParsers.length;
282                for (int i = 0; i < length; i++) {
283                    final SpellParser spellParser = mSpellParsers[i];
284                    if (spellParser.isParsing()) {
285                        spellParser.parse();
286                    }
287                }
288            }
289        }, SPELL_PAUSE_DURATION);
290    }
291
292    private void createMisspelledSuggestionSpan(Editable editable,
293            SuggestionsInfo suggestionsInfo, SpellCheckSpan spellCheckSpan) {
294        final int start = editable.getSpanStart(spellCheckSpan);
295        final int end = editable.getSpanEnd(spellCheckSpan);
296        if (start < 0 || end < 0) return; // span was removed in the meantime
297
298        // Other suggestion spans may exist on that region, with identical suggestions, filter
299        // them out to avoid duplicates. First, filter suggestion spans on that exact region.
300        SuggestionSpan[] suggestionSpans = editable.getSpans(start, end, SuggestionSpan.class);
301        final int length = suggestionSpans.length;
302        for (int i = 0; i < length; i++) {
303            final int spanStart = editable.getSpanStart(suggestionSpans[i]);
304            final int spanEnd = editable.getSpanEnd(suggestionSpans[i]);
305            if (spanStart != start || spanEnd != end) {
306                suggestionSpans[i] = null;
307            }
308        }
309
310        final int suggestionsCount = suggestionsInfo.getSuggestionsCount();
311        String[] suggestions;
312        if (suggestionsCount <= 0) {
313            // A negative suggestion count is possible
314            suggestions = ArrayUtils.emptyArray(String.class);
315        } else {
316            int numberOfSuggestions = 0;
317            suggestions = new String[suggestionsCount];
318
319            for (int i = 0; i < suggestionsCount; i++) {
320                final String spellSuggestion = suggestionsInfo.getSuggestionAt(i);
321                if (spellSuggestion == null) break;
322                boolean suggestionFound = false;
323
324                for (int j = 0; j < length && !suggestionFound; j++) {
325                    if (suggestionSpans[j] == null) break;
326
327                    String[] suggests = suggestionSpans[j].getSuggestions();
328                    for (int k = 0; k < suggests.length; k++) {
329                        if (spellSuggestion.equals(suggests[k])) {
330                            // The suggestion is already provided by an other SuggestionSpan
331                            suggestionFound = true;
332                            break;
333                        }
334                    }
335                }
336
337                if (!suggestionFound) {
338                    suggestions[numberOfSuggestions++] = spellSuggestion;
339                }
340            }
341
342            if (numberOfSuggestions != suggestionsCount) {
343                String[] newSuggestions = new String[numberOfSuggestions];
344                System.arraycopy(suggestions, 0, newSuggestions, 0, numberOfSuggestions);
345                suggestions = newSuggestions;
346            }
347        }
348
349        SuggestionSpan suggestionSpan = new SuggestionSpan(mTextView.getContext(), suggestions,
350                SuggestionSpan.FLAG_EASY_CORRECT | SuggestionSpan.FLAG_MISSPELLED);
351        editable.setSpan(suggestionSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
352    }
353
354    private class SpellParser {
355        private Object mRange = new Object();
356
357        public void init(int start, int end) {
358            setRangeSpan((Editable) mTextView.getText(), start, end);
359        }
360
361        public void stop() {
362            removeRangeSpan((Editable) mTextView.getText());
363        }
364
365        public boolean isParsing() {
366            return ((Editable) mTextView.getText()).getSpanStart(mRange) >= 0;
367        }
368
369        private void setRangeSpan(Editable editable, int start, int end) {
370            editable.setSpan(mRange, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
371        }
372
373        private void removeRangeSpan(Editable editable) {
374            editable.removeSpan(mRange);
375        }
376
377        public void parse() {
378            Editable editable = (Editable) mTextView.getText();
379            // Iterate over the newly added text and schedule new SpellCheckSpans
380            final int start = editable.getSpanStart(mRange);
381            final int end = editable.getSpanEnd(mRange);
382
383            final WordIterator wordIterator = mTextView.getWordIterator();
384            int wordIteratorWindowEnd = Math.min(end, start + WORD_ITERATOR_INTERVAL);
385            wordIterator.setCharSequence(editable, start, wordIteratorWindowEnd);
386
387            // Move back to the beginning of the current word, if any
388            int wordStart = wordIterator.preceding(start);
389            int wordEnd;
390            if (wordStart == BreakIterator.DONE) {
391                wordEnd = wordIterator.following(start);
392                if (wordEnd != BreakIterator.DONE) {
393                    wordStart = wordIterator.getBeginning(wordEnd);
394                }
395            } else {
396                wordEnd = wordIterator.getEnd(wordStart);
397            }
398            if (wordEnd == BreakIterator.DONE) {
399                removeRangeSpan(editable);
400                return;
401            }
402
403            // We need to expand by one character because we want to include the spans that
404            // end/start at position start/end respectively.
405            SpellCheckSpan[] spellCheckSpans = editable.getSpans(start - 1, end + 1,
406                    SpellCheckSpan.class);
407            SuggestionSpan[] suggestionSpans = editable.getSpans(start - 1, end + 1,
408                    SuggestionSpan.class);
409
410            int wordCount = 0;
411            boolean scheduleOtherSpellCheck = false;
412
413            while (wordStart <= end) {
414                if (wordEnd >= start && wordEnd > wordStart) {
415                    if (wordCount >= MAX_NUMBER_OF_WORDS) {
416                        scheduleOtherSpellCheck = true;
417                        break;
418                    }
419
420                    // A new word has been created across the interval boundaries with this edit.
421                    // Previous spans (ended on start / started on end) removed, not valid anymore
422                    if (wordStart < start && wordEnd > start) {
423                        removeSpansAt(editable, start, spellCheckSpans);
424                        removeSpansAt(editable, start, suggestionSpans);
425                    }
426
427                    if (wordStart < end && wordEnd > end) {
428                        removeSpansAt(editable, end, spellCheckSpans);
429                        removeSpansAt(editable, end, suggestionSpans);
430                    }
431
432                    // Do not create new boundary spans if they already exist
433                    boolean createSpellCheckSpan = true;
434                    if (wordEnd == start) {
435                        for (int i = 0; i < spellCheckSpans.length; i++) {
436                            final int spanEnd = editable.getSpanEnd(spellCheckSpans[i]);
437                            if (spanEnd == start) {
438                                createSpellCheckSpan = false;
439                                break;
440                            }
441                        }
442                    }
443
444                    if (wordStart == end) {
445                        for (int i = 0; i < spellCheckSpans.length; i++) {
446                            final int spanStart = editable.getSpanStart(spellCheckSpans[i]);
447                            if (spanStart == end) {
448                                createSpellCheckSpan = false;
449                                break;
450                            }
451                        }
452                    }
453
454                    if (createSpellCheckSpan) {
455                        addSpellCheckSpan(editable, wordStart, wordEnd);
456                    }
457                    wordCount++;
458                }
459
460                // iterate word by word
461                int originalWordEnd = wordEnd;
462                wordEnd = wordIterator.following(wordEnd);
463                if ((wordIteratorWindowEnd < end) &&
464                        (wordEnd == BreakIterator.DONE || wordEnd >= wordIteratorWindowEnd)) {
465                    wordIteratorWindowEnd = Math.min(end, originalWordEnd + WORD_ITERATOR_INTERVAL);
466                    wordIterator.setCharSequence(editable, originalWordEnd, wordIteratorWindowEnd);
467                    wordEnd = wordIterator.following(originalWordEnd);
468                }
469                if (wordEnd == BreakIterator.DONE) break;
470                wordStart = wordIterator.getBeginning(wordEnd);
471                if (wordStart == BreakIterator.DONE) {
472                    break;
473                }
474            }
475
476            if (scheduleOtherSpellCheck) {
477                // Update range span: start new spell check from last wordStart
478                setRangeSpan(editable, wordStart, end);
479            } else {
480                removeRangeSpan(editable);
481            }
482
483            spellCheck();
484        }
485
486        private <T> void removeSpansAt(Editable editable, int offset, T[] spans) {
487            final int length = spans.length;
488            for (int i = 0; i < length; i++) {
489                final T span = spans[i];
490                final int start = editable.getSpanStart(span);
491                if (start > offset) continue;
492                final int end = editable.getSpanEnd(span);
493                if (end < offset) continue;
494                editable.removeSpan(span);
495            }
496        }
497    }
498}
499