WordComposer.java revision 60a2cd8ac439bf41bfddc5f5f339feda7c7ff175
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            processEvent(Event.createEventForCodePointFromUnknownSource(codePoint));
298        }
299    }
300
301    /**
302     * Set the currently composing word to the one passed as an argument.
303     * This will register NOT_A_COORDINATE for X and Ys, and use the passed keyboard for proximity.
304     * @param codePoints the code points to set as the composing word.
305     * @param coordinates the x, y coordinates of the key in the CoordinateUtils format
306     */
307    public void setComposingWord(final int[] codePoints, final int[] coordinates) {
308        reset();
309        final int length = codePoints.length;
310        for (int i = 0; i < length; ++i) {
311            processEvent(Event.createEventForCodePointFromAlreadyTypedText(codePoints[i],
312                    CoordinateUtils.xFromArray(coordinates, i),
313                    CoordinateUtils.yFromArray(coordinates, i)));
314        }
315        mIsResumed = true;
316    }
317
318    /**
319     * Returns the word as it was typed, without any correction applied.
320     * @return the word that was typed so far. Never returns null.
321     */
322    public String getTypedWord() {
323        return mTypedWordCache.toString();
324    }
325
326    /**
327     * Whether this composer is composing or about to compose a word in which only the first letter
328     * is a capital.
329     *
330     * If we do have a composing word, we just return whether the word has indeed only its first
331     * character capitalized. If we don't, then we return a value based on the capitalized mode,
332     * which tell us what is likely to happen for the next composing word.
333     *
334     * @return capitalization preference
335     */
336    public boolean isOrWillBeOnlyFirstCharCapitalized() {
337        return isComposingWord() ? mIsOnlyFirstCharCapitalized
338                : (CAPS_MODE_OFF != mCapitalizedMode);
339    }
340
341    /**
342     * Whether or not all of the user typed chars are upper case
343     * @return true if all user typed chars are upper case, false otherwise
344     */
345    public boolean isAllUpperCase() {
346        if (size() <= 1) {
347            return mCapitalizedMode == CAPS_MODE_AUTO_SHIFT_LOCKED
348                    || mCapitalizedMode == CAPS_MODE_MANUAL_SHIFT_LOCKED;
349        } else {
350            return mCapsCount == size();
351        }
352    }
353
354    public boolean wasShiftedNoLock() {
355        return mCapitalizedMode == CAPS_MODE_AUTO_SHIFTED
356                || mCapitalizedMode == CAPS_MODE_MANUAL_SHIFTED;
357    }
358
359    /**
360     * Returns true if more than one character is upper case, otherwise returns false.
361     */
362    public boolean isMostlyCaps() {
363        return mCapsCount > 1;
364    }
365
366    /**
367     * Returns true if we have digits in the composing word.
368     */
369    public boolean hasDigits() {
370        return mDigitsCount > 0;
371    }
372
373    /**
374     * Saves the caps mode at the start of composing.
375     *
376     * WordComposer needs to know about the caps mode for several reasons. The first is, we need
377     * to know after the fact what the reason was, to register the correct form into the user
378     * history dictionary: if the word was automatically capitalized, we should insert it in
379     * all-lower case but if it's a manual pressing of shift, then it should be inserted as is.
380     * Also, batch input needs to know about the current caps mode to display correctly
381     * capitalized suggestions.
382     * @param mode the mode at the time of start
383     */
384    public void setCapitalizedModeAtStartComposingTime(final int mode) {
385        mCapitalizedMode = mode;
386    }
387
388    /**
389     * Before fetching suggestions, we don't necessarily know about the capitalized mode yet.
390     *
391     * If we don't have a composing word yet, we take a note of this mode so that we can then
392     * supply this information to the suggestion process. If we have a composing word, then
393     * the previous mode has priority over this.
394     * @param mode the mode just before fetching suggestions
395     */
396    public void adviseCapitalizedModeBeforeFetchingSuggestions(final int mode) {
397        if (!isComposingWord()) {
398            mCapitalizedMode = mode;
399        }
400    }
401
402    /**
403     * Returns whether the word was automatically capitalized.
404     * @return whether the word was automatically capitalized
405     */
406    public boolean wasAutoCapitalized() {
407        return mCapitalizedMode == CAPS_MODE_AUTO_SHIFT_LOCKED
408                || mCapitalizedMode == CAPS_MODE_AUTO_SHIFTED;
409    }
410
411    /**
412     * Sets the auto-correction for this word.
413     */
414    public void setAutoCorrection(final String correction) {
415        mAutoCorrection = correction;
416    }
417
418    /**
419     * @return the auto-correction for this word, or null if none.
420     */
421    public String getAutoCorrectionOrNull() {
422        return mAutoCorrection;
423    }
424
425    /**
426     * @return whether we started composing this word by resuming suggestion on an existing string
427     */
428    public boolean isResumed() {
429        return mIsResumed;
430    }
431
432    // `type' should be one of the LastComposedWord.COMMIT_TYPE_* constants above.
433    // committedWord should contain suggestion spans if applicable.
434    public LastComposedWord commitWord(final int type, final CharSequence committedWord,
435            final String separatorString, final PrevWordsInfo prevWordsInfo) {
436        // Note: currently, we come here whenever we commit a word. If it's a MANUAL_PICK
437        // or a DECIDED_WORD we may cancel the commit later; otherwise, we should deactivate
438        // the last composed word to ensure this does not happen.
439        final LastComposedWord lastComposedWord = new LastComposedWord(mEvents,
440                mInputPointers, mTypedWordCache.toString(), committedWord, separatorString,
441                prevWordsInfo, mCapitalizedMode);
442        mInputPointers.reset();
443        if (type != LastComposedWord.COMMIT_TYPE_DECIDED_WORD
444                && type != LastComposedWord.COMMIT_TYPE_MANUAL_PICK) {
445            lastComposedWord.deactivate();
446        }
447        mCapsCount = 0;
448        mDigitsCount = 0;
449        mIsBatchMode = false;
450        mCombinerChain.reset();
451        mEvents.clear();
452        mCodePointSize = 0;
453        mIsOnlyFirstCharCapitalized = false;
454        mCapitalizedMode = CAPS_MODE_OFF;
455        refreshTypedWordCache();
456        mAutoCorrection = null;
457        mCursorPositionWithinWord = 0;
458        mIsResumed = false;
459        mRejectedBatchModeSuggestion = null;
460        return lastComposedWord;
461    }
462
463    public void resumeSuggestionOnLastComposedWord(final LastComposedWord lastComposedWord) {
464        mEvents.clear();
465        Collections.copy(mEvents, lastComposedWord.mEvents);
466        mInputPointers.set(lastComposedWord.mInputPointers);
467        mCombinerChain.reset();
468        refreshTypedWordCache();
469        mCapitalizedMode = lastComposedWord.mCapitalizedMode;
470        mAutoCorrection = null; // This will be filled by the next call to updateSuggestion.
471        mCursorPositionWithinWord = mCodePointSize;
472        mRejectedBatchModeSuggestion = null;
473        mIsResumed = true;
474    }
475
476    public boolean isBatchMode() {
477        return mIsBatchMode;
478    }
479
480    public void setRejectedBatchModeSuggestion(final String rejectedSuggestion) {
481        mRejectedBatchModeSuggestion = rejectedSuggestion;
482    }
483
484    public String getRejectedBatchModeSuggestion() {
485        return mRejectedBatchModeSuggestion;
486    }
487}
488