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.utils;
18
19import android.text.Spanned;
20import android.text.style.SuggestionSpan;
21
22import java.util.Arrays;
23
24/**
25 * Represents a range of text, relative to the current cursor position.
26 */
27public final class TextRange {
28    private final CharSequence mTextAtCursor;
29    private final int mWordAtCursorStartIndex;
30    private final int mWordAtCursorEndIndex;
31    private final int mCursorIndex;
32
33    public final CharSequence mWord;
34
35    public int getNumberOfCharsInWordBeforeCursor() {
36        return mCursorIndex - mWordAtCursorStartIndex;
37    }
38
39    public int getNumberOfCharsInWordAfterCursor() {
40        return mWordAtCursorEndIndex - mCursorIndex;
41    }
42
43    public int length() {
44        return mWord.length();
45    }
46
47    /**
48     * Gets the suggestion spans that are put squarely on the word, with the exact start
49     * and end of the span matching the boundaries of the word.
50     * @return the list of spans.
51     */
52    public SuggestionSpan[] getSuggestionSpansAtWord() {
53        if (!(mTextAtCursor instanceof Spanned && mWord instanceof Spanned)) {
54            return new SuggestionSpan[0];
55        }
56        final Spanned text = (Spanned)mTextAtCursor;
57        // Note: it's fine to pass indices negative or greater than the length of the string
58        // to the #getSpans() method. The reason we need to get from -1 to +1 is that, the
59        // spans were cut at the cursor position, and #getSpans(start, end) does not return
60        // spans that end at `start' or begin at `end'. Consider the following case:
61        //              this| is          (The | symbolizes the cursor position
62        //              ---- ---
63        // In this case, the cursor is in position 4, so the 0~7 span has been split into
64        // a 0~4 part and a 4~7 part.
65        // If we called #getSpans(0, 4) in this case, we would only get the part from 0 to 4
66        // of the span, and not the part from 4 to 7, so we would not realize the span actually
67        // extends from 0 to 7. But if we call #getSpans(-1, 5) we'll get both the 0~4 and
68        // the 4~7 spans and we can merge them accordingly.
69        // Any span starting more than 1 char away from the word boundaries in any direction
70        // does not touch the word, so we don't need to consider it. That's why requesting
71        // -1 ~ +1 is enough.
72        // Of course this is only relevant if the cursor is at one end of the word. If it's
73        // in the middle, the -1 and +1 are not necessary, but they are harmless.
74        final SuggestionSpan[] spans = text.getSpans(mWordAtCursorStartIndex - 1,
75                mWordAtCursorEndIndex + 1, SuggestionSpan.class);
76        int readIndex = 0;
77        int writeIndex = 0;
78        for (; readIndex < spans.length; ++readIndex) {
79            final SuggestionSpan span = spans[readIndex];
80            // The span may be null, as we null them when we find duplicates. Cf a few lines
81            // down.
82            if (null == span) continue;
83            // Tentative span start and end. This may be modified later if we realize the
84            // same span is also applied to other parts of the string.
85            int spanStart = text.getSpanStart(span);
86            int spanEnd = text.getSpanEnd(span);
87            for (int i = readIndex + 1; i < spans.length; ++i) {
88                if (span.equals(spans[i])) {
89                    // We found the same span somewhere else. Read the new extent of this
90                    // span, and adjust our values accordingly.
91                    spanStart = Math.min(spanStart, text.getSpanStart(spans[i]));
92                    spanEnd = Math.max(spanEnd, text.getSpanEnd(spans[i]));
93                    // ...and mark the span as processed.
94                    spans[i] = null;
95                }
96            }
97            if (spanStart == mWordAtCursorStartIndex && spanEnd == mWordAtCursorEndIndex) {
98                // If the span does not start and stop here, we ignore it. It probably extends
99                // past the start or end of the word, as happens in missing space correction
100                // or EasyEditSpans put by voice input.
101                spans[writeIndex++] = spans[readIndex];
102            }
103        }
104        return writeIndex == readIndex ? spans : Arrays.copyOfRange(spans, 0, writeIndex);
105    }
106
107    public TextRange(final CharSequence textAtCursor, final int wordAtCursorStartIndex,
108            final int wordAtCursorEndIndex, final int cursorIndex) {
109        if (wordAtCursorStartIndex < 0 || cursorIndex < wordAtCursorStartIndex
110                || cursorIndex > wordAtCursorEndIndex
111                || wordAtCursorEndIndex > textAtCursor.length()) {
112            throw new IndexOutOfBoundsException();
113        }
114        mTextAtCursor = textAtCursor;
115        mWordAtCursorStartIndex = wordAtCursorStartIndex;
116        mWordAtCursorEndIndex = wordAtCursorEndIndex;
117        mCursorIndex = cursorIndex;
118        mWord = mTextAtCursor.subSequence(mWordAtCursorStartIndex, mWordAtCursorEndIndex);
119    }
120}