SpellChecker.java revision bec154c50036bc70a37518dc93f6821209f58728
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.SpannableStringBuilder;
23import android.text.Spanned;
24import android.text.TextUtils;
25import android.text.method.WordIterator;
26import android.text.style.SpellCheckSpan;
27import android.text.style.SuggestionSpan;
28import android.util.Log;
29import android.util.LruCache;
30import android.view.textservice.SentenceSuggestionsInfo;
31import android.view.textservice.SpellCheckerSession;
32import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener;
33import android.view.textservice.SuggestionsInfo;
34import android.view.textservice.TextInfo;
35import android.view.textservice.TextServicesManager;
36
37import com.android.internal.util.ArrayUtils;
38
39import java.text.BreakIterator;
40import java.util.Locale;
41
42
43/**
44 * Helper class for TextView. Bridge between the TextView and the Dictionnary service.
45 *
46 * @hide
47 */
48public class SpellChecker implements SpellCheckerSessionListener {
49    private static final String TAG = SpellChecker.class.getSimpleName();
50    private static final boolean DBG = false;
51
52    // No more than this number of words will be parsed on each iteration to ensure a minimum
53    // lock of the UI thread
54    public static final int MAX_NUMBER_OF_WORDS = 50;
55
56    // Rough estimate, such that the word iterator interval usually does not need to be shifted
57    public static final int AVERAGE_WORD_LENGTH = 7;
58
59    // When parsing, use a character window of that size. Will be shifted if needed
60    public static final int WORD_ITERATOR_INTERVAL = AVERAGE_WORD_LENGTH * MAX_NUMBER_OF_WORDS;
61
62    // Pause between each spell check to keep the UI smooth
63    private final static int SPELL_PAUSE_DURATION = 400; // milliseconds
64
65    private static final int MIN_SENTENCE_LENGTH = 50;
66
67    private static final int USE_SPAN_RANGE = -1;
68
69    private final TextView mTextView;
70
71    SpellCheckerSession mSpellCheckerSession;
72    // We assume that the sentence level spell check will always provide better results than words.
73    // Although word SC has a sequential option.
74    private boolean mIsSentenceSpellCheckSupported;
75    final int mCookie;
76
77    // Paired arrays for the (id, spellCheckSpan) pair. A negative id means the associated
78    // SpellCheckSpan has been recycled and can be-reused.
79    // Contains null SpellCheckSpans after index mLength.
80    private int[] mIds;
81    private SpellCheckSpan[] mSpellCheckSpans;
82    // The mLength first elements of the above arrays have been initialized
83    private int mLength;
84
85    // Parsers on chunck of text, cutting text into words that will be checked
86    private SpellParser[] mSpellParsers = new SpellParser[0];
87
88    private int mSpanSequenceCounter = 0;
89
90    private Locale mCurrentLocale;
91
92    // Shared by all SpellParsers. Cannot be shared with TextView since it may be used
93    // concurrently due to the asynchronous nature of onGetSuggestions.
94    private WordIterator mWordIterator;
95
96    private TextServicesManager mTextServicesManager;
97
98    private Runnable mSpellRunnable;
99
100    private static final int SUGGESTION_SPAN_CACHE_SIZE = 10;
101    private final LruCache<Long, SuggestionSpan> mSuggestionSpanCache =
102            new LruCache<Long, SuggestionSpan>(SUGGESTION_SPAN_CACHE_SIZE);
103
104    public SpellChecker(TextView textView) {
105        mTextView = textView;
106
107        // Arbitrary: these arrays will automatically double their sizes on demand
108        final int size = ArrayUtils.idealObjectArraySize(1);
109        mIds = new int[size];
110        mSpellCheckSpans = new SpellCheckSpan[size];
111
112        setLocale(mTextView.getTextServicesLocale());
113
114        mCookie = hashCode();
115    }
116
117    private void resetSession() {
118        closeSession();
119
120        mTextServicesManager = (TextServicesManager) mTextView.getContext().
121                getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
122        if (!mTextServicesManager.isSpellCheckerEnabled()
123                ||  mTextServicesManager.getCurrentSpellCheckerSubtype(true) == null) {
124            mSpellCheckerSession = null;
125        } else {
126            mSpellCheckerSession = mTextServicesManager.newSpellCheckerSession(
127                    null /* Bundle not currently used by the textServicesManager */,
128                    mCurrentLocale, this,
129                    false /* means any available languages from current spell checker */);
130            mIsSentenceSpellCheckSupported = true;
131        }
132
133        // Restore SpellCheckSpans in pool
134        for (int i = 0; i < mLength; i++) {
135            // Resets id and progress to invalidate spell check span
136            mSpellCheckSpans[i].setSpellCheckInProgress(false);
137            mIds[i] = -1;
138        }
139        mLength = 0;
140
141        // Remove existing misspelled SuggestionSpans
142        mTextView.removeMisspelledSpans((Editable) mTextView.getText());
143        mSuggestionSpanCache.evictAll();
144    }
145
146    private void setLocale(Locale locale) {
147        mCurrentLocale = locale;
148
149        resetSession();
150
151        // Change SpellParsers' wordIterator locale
152        mWordIterator = new WordIterator(locale);
153
154        // This class is the listener for locale change: warn other locale-aware objects
155        mTextView.onLocaleChanged();
156    }
157
158    /**
159     * @return true if a spell checker session has successfully been created. Returns false if not,
160     * for instance when spell checking has been disabled in settings.
161     */
162    private boolean isSessionActive() {
163        return mSpellCheckerSession != null;
164    }
165
166    public void closeSession() {
167        if (mSpellCheckerSession != null) {
168            mSpellCheckerSession.close();
169        }
170
171        final int length = mSpellParsers.length;
172        for (int i = 0; i < length; i++) {
173            mSpellParsers[i].stop();
174        }
175
176        if (mSpellRunnable != null) {
177            mTextView.removeCallbacks(mSpellRunnable);
178        }
179    }
180
181    private int nextSpellCheckSpanIndex() {
182        for (int i = 0; i < mLength; i++) {
183            if (mIds[i] < 0) return i;
184        }
185
186        if (mLength == mSpellCheckSpans.length) {
187            final int newSize = mLength * 2;
188            int[] newIds = new int[newSize];
189            SpellCheckSpan[] newSpellCheckSpans = new SpellCheckSpan[newSize];
190            System.arraycopy(mIds, 0, newIds, 0, mLength);
191            System.arraycopy(mSpellCheckSpans, 0, newSpellCheckSpans, 0, mLength);
192            mIds = newIds;
193            mSpellCheckSpans = newSpellCheckSpans;
194        }
195
196        mSpellCheckSpans[mLength] = new SpellCheckSpan();
197        mLength++;
198        return mLength - 1;
199    }
200
201    private void addSpellCheckSpan(Editable editable, int start, int end) {
202        final int index = nextSpellCheckSpanIndex();
203        editable.setSpan(mSpellCheckSpans[index], start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
204        mIds[index] = mSpanSequenceCounter++;
205    }
206
207    public void removeSpellCheckSpan(SpellCheckSpan spellCheckSpan) {
208        for (int i = 0; i < mLength; i++) {
209            if (mSpellCheckSpans[i] == spellCheckSpan) {
210                // Resets id and progress to invalidate spell check span
211                mSpellCheckSpans[i].setSpellCheckInProgress(false);
212                mIds[i] = -1;
213                return;
214            }
215        }
216    }
217
218    public void onSelectionChanged() {
219        spellCheck();
220    }
221
222    public void spellCheck(int start, int end) {
223        if (DBG) {
224            Log.d(TAG, "Start spell-checking: " + start + ", " + end);
225        }
226        final Locale locale = mTextView.getTextServicesLocale();
227        final boolean isSessionActive = isSessionActive();
228        if (mCurrentLocale == null || (!(mCurrentLocale.equals(locale)))) {
229            setLocale(locale);
230            // Re-check the entire text
231            start = 0;
232            end = mTextView.getText().length();
233        } else {
234            final boolean spellCheckerActivated = mTextServicesManager.isSpellCheckerEnabled();
235            if (isSessionActive != spellCheckerActivated) {
236                // Spell checker has been turned of or off since last spellCheck
237                resetSession();
238            }
239        }
240
241        if (!isSessionActive) return;
242
243        // Find first available SpellParser from pool
244        final int length = mSpellParsers.length;
245        for (int i = 0; i < length; i++) {
246            final SpellParser spellParser = mSpellParsers[i];
247            if (spellParser.isFinished()) {
248                spellParser.parse(start, end);
249                return;
250            }
251        }
252
253        if (DBG) {
254            Log.d(TAG, "new spell parser.");
255        }
256        // No available parser found in pool, create a new one
257        SpellParser[] newSpellParsers = new SpellParser[length + 1];
258        System.arraycopy(mSpellParsers, 0, newSpellParsers, 0, length);
259        mSpellParsers = newSpellParsers;
260
261        SpellParser spellParser = new SpellParser();
262        mSpellParsers[length] = spellParser;
263        spellParser.parse(start, end);
264    }
265
266    private void spellCheck() {
267        if (mSpellCheckerSession == null) return;
268
269        Editable editable = (Editable) mTextView.getText();
270        final int selectionStart = Selection.getSelectionStart(editable);
271        final int selectionEnd = Selection.getSelectionEnd(editable);
272
273        TextInfo[] textInfos = new TextInfo[mLength];
274        int textInfosCount = 0;
275
276        for (int i = 0; i < mLength; i++) {
277            final SpellCheckSpan spellCheckSpan = mSpellCheckSpans[i];
278            if (mIds[i] < 0 || spellCheckSpan.isSpellCheckInProgress()) continue;
279
280            final int start = editable.getSpanStart(spellCheckSpan);
281            final int end = editable.getSpanEnd(spellCheckSpan);
282
283            // Do not check this word if the user is currently editing it
284            final boolean isEditing;
285            if (mIsSentenceSpellCheckSupported) {
286                // Allow the overlap of the cursor and the first boundary of the spell check span
287                // no to skip the spell check of the following word because the
288                // following word will never be spell-checked even if the user finishes composing
289                isEditing = selectionEnd <= start || selectionStart > end;
290            } else {
291                isEditing = selectionEnd < start || selectionStart > end;
292            }
293            if (start >= 0 && end > start && isEditing) {
294                final String word = (editable instanceof SpannableStringBuilder) ?
295                        ((SpannableStringBuilder) editable).substring(start, end) :
296                        editable.subSequence(start, end).toString();
297                spellCheckSpan.setSpellCheckInProgress(true);
298                textInfos[textInfosCount++] = new TextInfo(word, mCookie, mIds[i]);
299                if (DBG) {
300                    Log.d(TAG, "create TextInfo: (" + i + "/" + mLength + ")" + word
301                            + ", cookie = " + mCookie + ", seq = "
302                            + mIds[i] + ", sel start = " + selectionStart + ", sel end = "
303                            + selectionEnd + ", start = " + start + ", end = " + end);
304                }
305            }
306        }
307
308        if (textInfosCount > 0) {
309            if (textInfosCount < textInfos.length) {
310                TextInfo[] textInfosCopy = new TextInfo[textInfosCount];
311                System.arraycopy(textInfos, 0, textInfosCopy, 0, textInfosCount);
312                textInfos = textInfosCopy;
313            }
314
315            if (mIsSentenceSpellCheckSupported) {
316                mSpellCheckerSession.getSentenceSuggestions(
317                        textInfos, SuggestionSpan.SUGGESTIONS_MAX_SIZE);
318            } else {
319                mSpellCheckerSession.getSuggestions(textInfos, SuggestionSpan.SUGGESTIONS_MAX_SIZE,
320                        false /* TODO Set sequentialWords to true for initial spell check */);
321            }
322        }
323    }
324
325    private SpellCheckSpan onGetSuggestionsInternal(
326            SuggestionsInfo suggestionsInfo, int offset, int length) {
327        if (suggestionsInfo == null || suggestionsInfo.getCookie() != mCookie) {
328            return null;
329        }
330        final Editable editable = (Editable) mTextView.getText();
331        final int sequenceNumber = suggestionsInfo.getSequence();
332        for (int k = 0; k < mLength; ++k) {
333            if (sequenceNumber == mIds[k]) {
334                final int attributes = suggestionsInfo.getSuggestionsAttributes();
335                final boolean isInDictionary =
336                        ((attributes & SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) > 0);
337                final boolean looksLikeTypo =
338                        ((attributes & SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) > 0);
339
340                final SpellCheckSpan spellCheckSpan = mSpellCheckSpans[k];
341                //TODO: we need to change that rule for results from a sentence-level spell
342                // checker that will probably be in dictionary.
343                if (!isInDictionary && looksLikeTypo) {
344                    createMisspelledSuggestionSpan(
345                            editable, suggestionsInfo, spellCheckSpan, offset, length);
346                } else {
347                    // Valid word -- isInDictionary || !looksLikeTypo
348                    if (mIsSentenceSpellCheckSupported) {
349                        // Allow the spell checker to remove existing misspelled span by
350                        // overwriting the span over the same place
351                        final int spellCheckSpanStart = editable.getSpanStart(spellCheckSpan);
352                        final int spellCheckSpanEnd = editable.getSpanEnd(spellCheckSpan);
353                        final int start;
354                        final int end;
355                        if (offset != USE_SPAN_RANGE && length != USE_SPAN_RANGE) {
356                            start = spellCheckSpanStart + offset;
357                            end = start + length;
358                        } else {
359                            start = spellCheckSpanStart;
360                            end = spellCheckSpanEnd;
361                        }
362                        if (spellCheckSpanStart >= 0 && spellCheckSpanEnd > spellCheckSpanStart
363                                && end > start) {
364                            final Long key = Long.valueOf(TextUtils.packRangeInLong(start, end));
365                            final SuggestionSpan tempSuggestionSpan = mSuggestionSpanCache.get(key);
366                            if (tempSuggestionSpan != null) {
367                                if (DBG) {
368                                    Log.i(TAG, "Remove existing misspelled span. "
369                                            + editable.subSequence(start, end));
370                                }
371                                editable.removeSpan(tempSuggestionSpan);
372                                mSuggestionSpanCache.remove(key);
373                            }
374                        }
375                    }
376                }
377                return spellCheckSpan;
378            }
379        }
380        return null;
381    }
382
383    @Override
384    public void onGetSuggestions(SuggestionsInfo[] results) {
385        final Editable editable = (Editable) mTextView.getText();
386        for (int i = 0; i < results.length; ++i) {
387            final SpellCheckSpan spellCheckSpan =
388                    onGetSuggestionsInternal(results[i], USE_SPAN_RANGE, USE_SPAN_RANGE);
389            if (spellCheckSpan != null) {
390                editable.removeSpan(spellCheckSpan);
391            }
392        }
393        scheduleNewSpellCheck();
394    }
395
396    @Override
397    public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] results) {
398        final Editable editable = (Editable) mTextView.getText();
399
400        for (int i = 0; i < results.length; ++i) {
401            final SentenceSuggestionsInfo ssi = results[i];
402            if (ssi == null) {
403                continue;
404            }
405            SpellCheckSpan spellCheckSpan = null;
406            for (int j = 0; j < ssi.getSuggestionsCount(); ++j) {
407                final SuggestionsInfo suggestionsInfo = ssi.getSuggestionsInfoAt(j);
408                if (suggestionsInfo == null) {
409                    continue;
410                }
411                final int offset = ssi.getOffsetAt(j);
412                final int length = ssi.getLengthAt(j);
413                final SpellCheckSpan scs = onGetSuggestionsInternal(
414                        suggestionsInfo, offset, length);
415                if (spellCheckSpan == null && scs != null) {
416                    // the spellCheckSpan is shared by all the "SuggestionsInfo"s in the same
417                    // SentenceSuggestionsInfo
418                    spellCheckSpan = scs;
419                }
420            }
421            if (spellCheckSpan != null) {
422                editable.removeSpan(spellCheckSpan);
423            }
424        }
425        scheduleNewSpellCheck();
426    }
427
428    private void scheduleNewSpellCheck() {
429        if (DBG) {
430            Log.i(TAG, "schedule new spell check.");
431        }
432        if (mSpellRunnable == null) {
433            mSpellRunnable = new Runnable() {
434                @Override
435                public void run() {
436                    final int length = mSpellParsers.length;
437                    for (int i = 0; i < length; i++) {
438                        final SpellParser spellParser = mSpellParsers[i];
439                        if (!spellParser.isFinished()) {
440                            spellParser.parse();
441                            break; // run one spell parser at a time to bound running time
442                        }
443                    }
444                }
445            };
446        } else {
447            mTextView.removeCallbacks(mSpellRunnable);
448        }
449
450        mTextView.postDelayed(mSpellRunnable, SPELL_PAUSE_DURATION);
451    }
452
453    private void createMisspelledSuggestionSpan(Editable editable, SuggestionsInfo suggestionsInfo,
454            SpellCheckSpan spellCheckSpan, int offset, int length) {
455        final int spellCheckSpanStart = editable.getSpanStart(spellCheckSpan);
456        final int spellCheckSpanEnd = editable.getSpanEnd(spellCheckSpan);
457        if (spellCheckSpanStart < 0 || spellCheckSpanEnd <= spellCheckSpanStart)
458            return; // span was removed in the meantime
459
460        final int start;
461        final int end;
462        if (offset != USE_SPAN_RANGE && length != USE_SPAN_RANGE) {
463            start = spellCheckSpanStart + offset;
464            end = start + length;
465        } else {
466            start = spellCheckSpanStart;
467            end = spellCheckSpanEnd;
468        }
469
470        final int suggestionsCount = suggestionsInfo.getSuggestionsCount();
471        String[] suggestions;
472        if (suggestionsCount > 0) {
473            suggestions = new String[suggestionsCount];
474            for (int i = 0; i < suggestionsCount; i++) {
475                suggestions[i] = suggestionsInfo.getSuggestionAt(i);
476            }
477        } else {
478            suggestions = ArrayUtils.emptyArray(String.class);
479        }
480
481        SuggestionSpan suggestionSpan = new SuggestionSpan(mTextView.getContext(), suggestions,
482                SuggestionSpan.FLAG_EASY_CORRECT | SuggestionSpan.FLAG_MISSPELLED);
483        // TODO: Remove mIsSentenceSpellCheckSupported by extracting an interface
484        // to share the logic of word level spell checker and sentence level spell checker
485        if (mIsSentenceSpellCheckSupported) {
486            final Long key = Long.valueOf(TextUtils.packRangeInLong(start, end));
487            final SuggestionSpan tempSuggestionSpan = mSuggestionSpanCache.get(key);
488            if (tempSuggestionSpan != null) {
489                if (DBG) {
490                    Log.i(TAG, "Cached span on the same position is cleard. "
491                            + editable.subSequence(start, end));
492                }
493                editable.removeSpan(tempSuggestionSpan);
494            }
495            mSuggestionSpanCache.put(key, suggestionSpan);
496        }
497        editable.setSpan(suggestionSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
498
499        mTextView.invalidateRegion(start, end, false /* No cursor involved */);
500    }
501
502    private class SpellParser {
503        private Object mRange = new Object();
504
505        public void parse(int start, int end) {
506            final int max = mTextView.length();
507            final int parseEnd;
508            if (end > max) {
509                Log.w(TAG, "Parse invalid region, from " + start + " to " + end);
510                parseEnd = max;
511            } else {
512                parseEnd = end;
513            }
514            if (parseEnd > start) {
515                setRangeSpan((Editable) mTextView.getText(), start, parseEnd);
516                parse();
517            }
518        }
519
520        public boolean isFinished() {
521            return ((Editable) mTextView.getText()).getSpanStart(mRange) < 0;
522        }
523
524        public void stop() {
525            removeRangeSpan((Editable) mTextView.getText());
526        }
527
528        private void setRangeSpan(Editable editable, int start, int end) {
529            if (DBG) {
530                Log.d(TAG, "set next range span: " + start + ", " + end);
531            }
532            editable.setSpan(mRange, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
533        }
534
535        private void removeRangeSpan(Editable editable) {
536            if (DBG) {
537                Log.d(TAG, "Remove range span." + editable.getSpanStart(editable)
538                        + editable.getSpanEnd(editable));
539            }
540            editable.removeSpan(mRange);
541        }
542
543        public void parse() {
544            Editable editable = (Editable) mTextView.getText();
545            // Iterate over the newly added text and schedule new SpellCheckSpans
546            final int start;
547            if (mIsSentenceSpellCheckSupported) {
548                // TODO: Find the start position of the sentence.
549                // Set span with the context
550                start =  Math.max(
551                        0, editable.getSpanStart(mRange) - MIN_SENTENCE_LENGTH);
552            } else {
553                start = editable.getSpanStart(mRange);
554            }
555
556            final int end = editable.getSpanEnd(mRange);
557
558            int wordIteratorWindowEnd = Math.min(end, start + WORD_ITERATOR_INTERVAL);
559            mWordIterator.setCharSequence(editable, start, wordIteratorWindowEnd);
560
561            // Move back to the beginning of the current word, if any
562            int wordStart = mWordIterator.preceding(start);
563            int wordEnd;
564            if (wordStart == BreakIterator.DONE) {
565                wordEnd = mWordIterator.following(start);
566                if (wordEnd != BreakIterator.DONE) {
567                    wordStart = mWordIterator.getBeginning(wordEnd);
568                }
569            } else {
570                wordEnd = mWordIterator.getEnd(wordStart);
571            }
572            if (wordEnd == BreakIterator.DONE) {
573                if (DBG) {
574                    Log.i(TAG, "No more spell check.");
575                }
576                removeRangeSpan(editable);
577                return;
578            }
579
580            // We need to expand by one character because we want to include the spans that
581            // end/start at position start/end respectively.
582            SpellCheckSpan[] spellCheckSpans = editable.getSpans(start - 1, end + 1,
583                    SpellCheckSpan.class);
584            SuggestionSpan[] suggestionSpans = editable.getSpans(start - 1, end + 1,
585                    SuggestionSpan.class);
586
587            int wordCount = 0;
588            boolean scheduleOtherSpellCheck = false;
589
590            if (mIsSentenceSpellCheckSupported) {
591                if (wordIteratorWindowEnd < end) {
592                    if (DBG) {
593                        Log.i(TAG, "schedule other spell check.");
594                    }
595                    // Several batches needed on that region. Cut after last previous word
596                    scheduleOtherSpellCheck = true;
597                }
598                int spellCheckEnd = mWordIterator.preceding(wordIteratorWindowEnd);
599                boolean correct = spellCheckEnd != BreakIterator.DONE;
600                if (correct) {
601                    spellCheckEnd = mWordIterator.getEnd(spellCheckEnd);
602                    correct = spellCheckEnd != BreakIterator.DONE;
603                }
604                if (!correct) {
605                    if (DBG) {
606                        Log.i(TAG, "Incorrect range span.");
607                    }
608                    removeRangeSpan(editable);
609                    return;
610                }
611                do {
612                    // TODO: Find the start position of the sentence.
613                    int spellCheckStart = wordStart;
614                    boolean createSpellCheckSpan = true;
615                    // Cancel or merge overlapped spell check spans
616                    for (int i = 0; i < mLength; ++i) {
617                        final SpellCheckSpan spellCheckSpan = mSpellCheckSpans[i];
618                        if (mIds[i] < 0 || spellCheckSpan.isSpellCheckInProgress()) {
619                            continue;
620                        }
621                        final int spanStart = editable.getSpanStart(spellCheckSpan);
622                        final int spanEnd = editable.getSpanEnd(spellCheckSpan);
623                        if (spanEnd < spellCheckStart || spellCheckEnd < spanStart) {
624                            // No need to merge
625                            continue;
626                        }
627                        if (spanStart <= spellCheckStart && spellCheckEnd <= spanEnd) {
628                            // There is a completely overlapped spell check span
629                            // skip this span
630                            createSpellCheckSpan = false;
631                            if (DBG) {
632                                Log.i(TAG, "The range is overrapped. Skip spell check.");
633                            }
634                            break;
635                        }
636                        removeSpellCheckSpan(spellCheckSpan);
637                        spellCheckStart = Math.min(spanStart, spellCheckStart);
638                        spellCheckEnd = Math.max(spanEnd, spellCheckEnd);
639                    }
640
641                    if (DBG) {
642                        Log.d(TAG, "addSpellCheckSpan: "
643                                + ", End = " + spellCheckEnd + ", Start = " + spellCheckStart
644                                + ", next = " + scheduleOtherSpellCheck + "\n"
645                                + editable.subSequence(spellCheckStart, spellCheckEnd));
646                    }
647
648                    // Stop spell checking when there are no characters in the range.
649                    if (spellCheckEnd < start) {
650                        break;
651                    }
652                    if (spellCheckEnd <= spellCheckStart) {
653                        Log.w(TAG, "Trying to spellcheck invalid region, from "
654                                + start + " to " + end);
655                        break;
656                    }
657                    if (createSpellCheckSpan) {
658                        addSpellCheckSpan(editable, spellCheckStart, spellCheckEnd);
659                    }
660                } while (false);
661                wordStart = spellCheckEnd;
662            } else {
663                while (wordStart <= end) {
664                    if (wordEnd >= start && wordEnd > wordStart) {
665                        if (wordCount >= MAX_NUMBER_OF_WORDS) {
666                            scheduleOtherSpellCheck = true;
667                            break;
668                        }
669                        // A new word has been created across the interval boundaries with this
670                        // edit. The previous spans (that ended on start / started on end) are
671                        // not valid anymore and must be removed.
672                        if (wordStart < start && wordEnd > start) {
673                            removeSpansAt(editable, start, spellCheckSpans);
674                            removeSpansAt(editable, start, suggestionSpans);
675                        }
676
677                        if (wordStart < end && wordEnd > end) {
678                            removeSpansAt(editable, end, spellCheckSpans);
679                            removeSpansAt(editable, end, suggestionSpans);
680                        }
681
682                        // Do not create new boundary spans if they already exist
683                        boolean createSpellCheckSpan = true;
684                        if (wordEnd == start) {
685                            for (int i = 0; i < spellCheckSpans.length; i++) {
686                                final int spanEnd = editable.getSpanEnd(spellCheckSpans[i]);
687                                if (spanEnd == start) {
688                                    createSpellCheckSpan = false;
689                                    break;
690                                }
691                            }
692                        }
693
694                        if (wordStart == end) {
695                            for (int i = 0; i < spellCheckSpans.length; i++) {
696                                final int spanStart = editable.getSpanStart(spellCheckSpans[i]);
697                                if (spanStart == end) {
698                                    createSpellCheckSpan = false;
699                                    break;
700                                }
701                            }
702                        }
703
704                        if (createSpellCheckSpan) {
705                            addSpellCheckSpan(editable, wordStart, wordEnd);
706                        }
707                        wordCount++;
708                    }
709
710                    // iterate word by word
711                    int originalWordEnd = wordEnd;
712                    wordEnd = mWordIterator.following(wordEnd);
713                    if ((wordIteratorWindowEnd < end) &&
714                            (wordEnd == BreakIterator.DONE || wordEnd >= wordIteratorWindowEnd)) {
715                        wordIteratorWindowEnd =
716                                Math.min(end, originalWordEnd + WORD_ITERATOR_INTERVAL);
717                        mWordIterator.setCharSequence(
718                                editable, originalWordEnd, wordIteratorWindowEnd);
719                        wordEnd = mWordIterator.following(originalWordEnd);
720                    }
721                    if (wordEnd == BreakIterator.DONE) break;
722                    wordStart = mWordIterator.getBeginning(wordEnd);
723                    if (wordStart == BreakIterator.DONE) {
724                        break;
725                    }
726                }
727            }
728
729            if (scheduleOtherSpellCheck) {
730                // Update range span: start new spell check from last wordStart
731                setRangeSpan(editable, wordStart, end);
732            } else {
733                removeRangeSpan(editable);
734            }
735
736            spellCheck();
737        }
738
739        private <T> void removeSpansAt(Editable editable, int offset, T[] spans) {
740            final int length = spans.length;
741            for (int i = 0; i < length; i++) {
742                final T span = spans[i];
743                final int start = editable.getSpanStart(span);
744                if (start > offset) continue;
745                final int end = editable.getSpanEnd(span);
746                if (end < offset) continue;
747                editable.removeSpan(span);
748            }
749        }
750    }
751}
752