WordComposer.java revision 4399849dea9f3cc1c8b1828739a0dd7bedc1f730
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
17package com.android.inputmethod.latin;
18
19import com.android.inputmethod.event.CombinerChain;
20import com.android.inputmethod.event.Event;
21import com.android.inputmethod.latin.define.DebugFlags;
22import com.android.inputmethod.latin.utils.CoordinateUtils;
23import com.android.inputmethod.latin.utils.StringUtils;
24
25import java.util.ArrayList;
26import java.util.Collections;
27
28/**
29 * A place to store the currently composing word with information such as adjacent key codes as well
30 */
31public final class WordComposer {
32    private static final int MAX_WORD_LENGTH = Constants.DICTIONARY_MAX_WORD_LENGTH;
33    private static final boolean DBG = DebugFlags.DEBUG_ENABLED;
34
35    public static final int CAPS_MODE_OFF = 0;
36    // 1 is shift bit, 2 is caps bit, 4 is auto bit but this is just a convention as these bits
37    // aren't used anywhere in the code
38    public static final int CAPS_MODE_MANUAL_SHIFTED = 0x1;
39    public static final int CAPS_MODE_MANUAL_SHIFT_LOCKED = 0x3;
40    public static final int CAPS_MODE_AUTO_SHIFTED = 0x5;
41    public static final int CAPS_MODE_AUTO_SHIFT_LOCKED = 0x7;
42
43    private CombinerChain mCombinerChain;
44    private String mCombiningSpec; // Memory so that we don't uselessly recreate the combiner chain
45
46    // The list of events that served to compose this string.
47    private final ArrayList<Event> mEvents;
48    private final InputPointers mInputPointers = new InputPointers(MAX_WORD_LENGTH);
49    private String mAutoCorrection;
50    private boolean mIsResumed;
51    private boolean mIsBatchMode;
52    // A memory of the last rejected batch mode suggestion, if any. This goes like this: the user
53    // gestures a word, is displeased with the results and hits backspace, then gestures again.
54    // At the very least we should avoid re-suggesting the same thing, and to do that we memorize
55    // the rejected suggestion in this variable.
56    // TODO: this should be done in a comprehensive way by the User History feature instead of
57    // as an ad-hockery here.
58    private String mRejectedBatchModeSuggestion;
59
60    // Cache these values for performance
61    private CharSequence mTypedWordCache;
62    private int mCapsCount;
63    private int mDigitsCount;
64    private int mCapitalizedMode;
65    // This is the number of code points entered so far. This is not limited to MAX_WORD_LENGTH.
66    // In general, this contains the size of mPrimaryKeyCodes, except when this is greater than
67    // MAX_WORD_LENGTH in which case mPrimaryKeyCodes only contain the first MAX_WORD_LENGTH
68    // code points.
69    private int mCodePointSize;
70    private int mCursorPositionWithinWord;
71
72    /**
73     * Whether the composing word has the only first char capitalized.
74     */
75    private boolean mIsOnlyFirstCharCapitalized;
76
77    public WordComposer() {
78        mCombinerChain = new CombinerChain("");
79        mEvents = new ArrayList<>();
80        mAutoCorrection = null;
81        mIsResumed = false;
82        mIsBatchMode = false;
83        mCursorPositionWithinWord = 0;
84        mRejectedBatchModeSuggestion = null;
85        refreshTypedWordCache();
86    }
87
88    /**
89     * Restart the combiners, possibly with a new spec.
90     * @param combiningSpec The spec string for combining. This is found in the extra value.
91     */
92    public void restartCombining(final String combiningSpec) {
93        final String nonNullCombiningSpec = null == combiningSpec ? "" : combiningSpec;
94        if (!nonNullCombiningSpec.equals(mCombiningSpec)) {
95            mCombinerChain = new CombinerChain(
96                    mCombinerChain.getComposingWordWithCombiningFeedback().toString(),
97                    CombinerChain.createCombiners(nonNullCombiningSpec));
98            mCombiningSpec = nonNullCombiningSpec;
99        }
100    }
101
102    /**
103     * Clear out the keys registered so far.
104     */
105    public void reset() {
106        mCombinerChain.reset();
107        mEvents.clear();
108        mAutoCorrection = null;
109        mCapsCount = 0;
110        mDigitsCount = 0;
111        mIsOnlyFirstCharCapitalized = false;
112        mIsResumed = false;
113        mIsBatchMode = false;
114        mCursorPositionWithinWord = 0;
115        mRejectedBatchModeSuggestion = null;
116        refreshTypedWordCache();
117    }
118
119    private final void refreshTypedWordCache() {
120        mTypedWordCache = mCombinerChain.getComposingWordWithCombiningFeedback();
121        mCodePointSize = Character.codePointCount(mTypedWordCache, 0, mTypedWordCache.length());
122    }
123
124    /**
125     * Number of keystrokes in the composing word.
126     * @return the number of keystrokes
127     */
128    // This may be made public if need be, but right now it's not used anywhere
129    /* package for tests */ int size() {
130        return mCodePointSize;
131    }
132
133    /**
134     * Copy the code points in the typed word to a destination array of ints.
135     *
136     * If the array is too small to hold the code points in the typed word, nothing is copied and
137     * -1 is returned.
138     *
139     * @param destination the array of ints.
140     * @return the number of copied code points.
141     */
142    public int copyCodePointsExceptTrailingSingleQuotesAndReturnCodePointCount(
143            final int[] destination) {
144        // This method can be called on a separate thread and mTypedWordCache can change while we
145        // are executing this method.
146        final String typedWord = mTypedWordCache.toString();
147        // lastIndex is exclusive
148        final int lastIndex = typedWord.length()
149                - StringUtils.getTrailingSingleQuotesCount(typedWord);
150        if (lastIndex <= 0) {
151            // The string is empty or contains only single quotes.
152            return 0;
153        }
154
155        // The following function counts the number of code points in the text range which begins
156        // at index 0 and extends to the character at lastIndex.
157        final int codePointSize = Character.codePointCount(typedWord, 0, lastIndex);
158        if (codePointSize > destination.length) {
159            return -1;
160        }
161        return StringUtils.copyCodePointsAndReturnCodePointCount(destination, typedWord, 0,
162                lastIndex, true /* downCase */);
163    }
164
165    public boolean isSingleLetter() {
166        return size() == 1;
167    }
168
169    public final boolean isComposingWord() {
170        return size() > 0;
171    }
172
173    public InputPointers getInputPointers() {
174        return mInputPointers;
175    }
176
177    /**
178     * Process an input event.
179     *
180     * All input events should be supported, including software/hardware events, characters as well
181     * as deletions, multiple inputs and gestures.
182     *
183     * @param event the event to process.
184     */
185    public void processEvent(final Event event) {
186        final int primaryCode = event.mCodePoint;
187        final int keyX = event.mX;
188        final int keyY = event.mY;
189        final int newIndex = size();
190        mCombinerChain.processEvent(mEvents, event);
191        mEvents.add(event);
192        refreshTypedWordCache();
193        mCursorPositionWithinWord = mCodePointSize;
194        // We may have deleted the last one.
195        if (0 == mCodePointSize) {
196            mIsOnlyFirstCharCapitalized = false;
197        }
198        if (Constants.CODE_DELETE != event.mKeyCode) {
199            if (newIndex < MAX_WORD_LENGTH) {
200                // In the batch input mode, the {@code mInputPointers} holds batch input points and
201                // shouldn't be overridden by the "typed key" coordinates
202                // (See {@link #setBatchInputWord}).
203                if (!mIsBatchMode) {
204                    // TODO: Set correct pointer id and time
205                    mInputPointers.addPointerAt(newIndex, keyX, keyY, 0, 0);
206                }
207            }
208            if (0 == newIndex) {
209                mIsOnlyFirstCharCapitalized = Character.isUpperCase(primaryCode);
210            } else {
211                mIsOnlyFirstCharCapitalized = mIsOnlyFirstCharCapitalized
212                        && !Character.isUpperCase(primaryCode);
213            }
214            if (Character.isUpperCase(primaryCode)) mCapsCount++;
215            if (Character.isDigit(primaryCode)) mDigitsCount++;
216        }
217        mAutoCorrection = null;
218    }
219
220    public void setCursorPositionWithinWord(final int posWithinWord) {
221        mCursorPositionWithinWord = posWithinWord;
222        // TODO: compute where that puts us inside the events
223    }
224
225    public boolean isCursorFrontOrMiddleOfComposingWord() {
226        if (DBG && mCursorPositionWithinWord > mCodePointSize) {
227            throw new RuntimeException("Wrong cursor position : " + mCursorPositionWithinWord
228                    + "in a word of size " + mCodePointSize);
229        }
230        return mCursorPositionWithinWord != mCodePointSize;
231    }
232
233    /**
234     * When the cursor is moved by the user, we need to update its position.
235     * If it falls inside the currently composing word, we don't reset the composition, and
236     * only update the cursor position.
237     *
238     * @param expectedMoveAmount How many java chars to move the cursor. Negative values move
239     * the cursor backward, positive values move the cursor forward.
240     * @return true if the cursor is still inside the composing word, false otherwise.
241     */
242    public boolean moveCursorByAndReturnIfInsideComposingWord(final int expectedMoveAmount) {
243        // TODO: should uncommit the composing feedback
244        mCombinerChain.reset();
245        int actualMoveAmountWithinWord = 0;
246        int cursorPos = mCursorPositionWithinWord;
247        // TODO: Don't make that copy. We can do this directly from mTypedWordCache.
248        final int[] codePoints = StringUtils.toCodePointArray(mTypedWordCache);
249        if (expectedMoveAmount >= 0) {
250            // Moving the cursor forward for the expected amount or until the end of the word has
251            // been reached, whichever comes first.
252            while (actualMoveAmountWithinWord < expectedMoveAmount && cursorPos < mCodePointSize) {
253                actualMoveAmountWithinWord += Character.charCount(codePoints[cursorPos]);
254                ++cursorPos;
255            }
256        } else {
257            // Moving the cursor backward for the expected amount or until the start of the word
258            // has been reached, whichever comes first.
259            while (actualMoveAmountWithinWord > expectedMoveAmount && cursorPos > 0) {
260                --cursorPos;
261                actualMoveAmountWithinWord -= Character.charCount(codePoints[cursorPos]);
262            }
263        }
264        // If the actual and expected amounts differ, we crossed the start or the end of the word
265        // so the result would not be inside the composing word.
266        if (actualMoveAmountWithinWord != expectedMoveAmount) return false;
267        mCursorPositionWithinWord = cursorPos;
268        return true;
269    }
270
271    public void setBatchInputPointers(final InputPointers batchPointers) {
272        mInputPointers.set(batchPointers);
273        mIsBatchMode = true;
274    }
275
276    public void setBatchInputWord(final String word) {
277        reset();
278        mIsBatchMode = true;
279        final int length = word.length();
280        for (int i = 0; i < length; i = Character.offsetByCodePoints(word, i, 1)) {
281            final int codePoint = Character.codePointAt(word, i);
282            // We don't want to override the batch input points that are held in mInputPointers
283            // (See {@link #add(int,int,int)}).
284            processEvent(Event.createEventForCodePointFromUnknownSource(codePoint));
285        }
286    }
287
288    /**
289     * Set the currently composing word to the one passed as an argument.
290     * This will register NOT_A_COORDINATE for X and Ys, and use the passed keyboard for proximity.
291     * @param codePoints the code points to set as the composing word.
292     * @param coordinates the x, y coordinates of the key in the CoordinateUtils format
293     */
294    public void setComposingWord(final int[] codePoints, final int[] coordinates) {
295        reset();
296        final int length = codePoints.length;
297        for (int i = 0; i < length; ++i) {
298            processEvent(Event.createEventForCodePointFromAlreadyTypedText(codePoints[i],
299                    CoordinateUtils.xFromArray(coordinates, i),
300                    CoordinateUtils.yFromArray(coordinates, i)));
301        }
302        mIsResumed = true;
303    }
304
305    /**
306     * Returns the word as it was typed, without any correction applied.
307     * @return the word that was typed so far. Never returns null.
308     */
309    public String getTypedWord() {
310        return mTypedWordCache.toString();
311    }
312
313    /**
314     * Whether this composer is composing or about to compose a word in which only the first letter
315     * is a capital.
316     *
317     * If we do have a composing word, we just return whether the word has indeed only its first
318     * character capitalized. If we don't, then we return a value based on the capitalized mode,
319     * which tell us what is likely to happen for the next composing word.
320     *
321     * @return capitalization preference
322     */
323    public boolean isOrWillBeOnlyFirstCharCapitalized() {
324        return isComposingWord() ? mIsOnlyFirstCharCapitalized
325                : (CAPS_MODE_OFF != mCapitalizedMode);
326    }
327
328    /**
329     * Whether or not all of the user typed chars are upper case
330     * @return true if all user typed chars are upper case, false otherwise
331     */
332    public boolean isAllUpperCase() {
333        if (size() <= 1) {
334            return mCapitalizedMode == CAPS_MODE_AUTO_SHIFT_LOCKED
335                    || mCapitalizedMode == CAPS_MODE_MANUAL_SHIFT_LOCKED;
336        } else {
337            return mCapsCount == size();
338        }
339    }
340
341    public boolean wasShiftedNoLock() {
342        return mCapitalizedMode == CAPS_MODE_AUTO_SHIFTED
343                || mCapitalizedMode == CAPS_MODE_MANUAL_SHIFTED;
344    }
345
346    /**
347     * Returns true if more than one character is upper case, otherwise returns false.
348     */
349    public boolean isMostlyCaps() {
350        return mCapsCount > 1;
351    }
352
353    /**
354     * Returns true if we have digits in the composing word.
355     */
356    public boolean hasDigits() {
357        return mDigitsCount > 0;
358    }
359
360    /**
361     * Saves the caps mode at the start of composing.
362     *
363     * WordComposer needs to know about the caps mode for several reasons. The first is, we need
364     * to know after the fact what the reason was, to register the correct form into the user
365     * history dictionary: if the word was automatically capitalized, we should insert it in
366     * all-lower case but if it's a manual pressing of shift, then it should be inserted as is.
367     * Also, batch input needs to know about the current caps mode to display correctly
368     * capitalized suggestions.
369     * @param mode the mode at the time of start
370     */
371    public void setCapitalizedModeAtStartComposingTime(final int mode) {
372        mCapitalizedMode = mode;
373    }
374
375    /**
376     * Before fetching suggestions, we don't necessarily know about the capitalized mode yet.
377     *
378     * If we don't have a composing word yet, we take a note of this mode so that we can then
379     * supply this information to the suggestion process. If we have a composing word, then
380     * the previous mode has priority over this.
381     * @param mode the mode just before fetching suggestions
382     */
383    public void adviseCapitalizedModeBeforeFetchingSuggestions(final int mode) {
384        if (!isComposingWord()) {
385            mCapitalizedMode = mode;
386        }
387    }
388
389    /**
390     * Returns whether the word was automatically capitalized.
391     * @return whether the word was automatically capitalized
392     */
393    public boolean wasAutoCapitalized() {
394        return mCapitalizedMode == CAPS_MODE_AUTO_SHIFT_LOCKED
395                || mCapitalizedMode == CAPS_MODE_AUTO_SHIFTED;
396    }
397
398    /**
399     * Sets the auto-correction for this word.
400     */
401    public void setAutoCorrection(final String correction) {
402        mAutoCorrection = correction;
403    }
404
405    /**
406     * @return the auto-correction for this word, or null if none.
407     */
408    public String getAutoCorrectionOrNull() {
409        return mAutoCorrection;
410    }
411
412    /**
413     * @return whether we started composing this word by resuming suggestion on an existing string
414     */
415    public boolean isResumed() {
416        return mIsResumed;
417    }
418
419    // `type' should be one of the LastComposedWord.COMMIT_TYPE_* constants above.
420    // committedWord should contain suggestion spans if applicable.
421    public LastComposedWord commitWord(final int type, final CharSequence committedWord,
422            final String separatorString, final PrevWordsInfo prevWordsInfo) {
423        // Note: currently, we come here whenever we commit a word. If it's a MANUAL_PICK
424        // or a DECIDED_WORD we may cancel the commit later; otherwise, we should deactivate
425        // the last composed word to ensure this does not happen.
426        final LastComposedWord lastComposedWord = new LastComposedWord(mEvents,
427                mInputPointers, mTypedWordCache.toString(), committedWord, separatorString,
428                prevWordsInfo, mCapitalizedMode);
429        mInputPointers.reset();
430        if (type != LastComposedWord.COMMIT_TYPE_DECIDED_WORD
431                && type != LastComposedWord.COMMIT_TYPE_MANUAL_PICK) {
432            lastComposedWord.deactivate();
433        }
434        mCapsCount = 0;
435        mDigitsCount = 0;
436        mIsBatchMode = false;
437        mCombinerChain.reset();
438        mEvents.clear();
439        mCodePointSize = 0;
440        mIsOnlyFirstCharCapitalized = false;
441        mCapitalizedMode = CAPS_MODE_OFF;
442        refreshTypedWordCache();
443        mAutoCorrection = null;
444        mCursorPositionWithinWord = 0;
445        mIsResumed = false;
446        mRejectedBatchModeSuggestion = null;
447        return lastComposedWord;
448    }
449
450    public void resumeSuggestionOnLastComposedWord(final LastComposedWord lastComposedWord) {
451        mEvents.clear();
452        Collections.copy(mEvents, lastComposedWord.mEvents);
453        mInputPointers.set(lastComposedWord.mInputPointers);
454        mCombinerChain.reset();
455        refreshTypedWordCache();
456        mCapitalizedMode = lastComposedWord.mCapitalizedMode;
457        mAutoCorrection = null; // This will be filled by the next call to updateSuggestion.
458        mCursorPositionWithinWord = mCodePointSize;
459        mRejectedBatchModeSuggestion = null;
460        mIsResumed = true;
461    }
462
463    public boolean isBatchMode() {
464        return mIsBatchMode;
465    }
466
467    public void setRejectedBatchModeSuggestion(final String rejectedSuggestion) {
468        mRejectedBatchModeSuggestion = rejectedSuggestion;
469    }
470
471    public String getRejectedBatchModeSuggestion() {
472        return mRejectedBatchModeSuggestion;
473    }
474}
475