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