WordComposer.java revision 99aff0af98e66b1d8515225a103f5beb84d098b9
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 event and return an event, and return a processed event to apply.
179     * @param event the unprocessed event.
180     * @return the processed event. Never null, but may be marked as consumed.
181     */
182    public Event processEvent(final Event event) {
183        final Event processedEvent = mCombinerChain.processEvent(mEvents, event);
184        mEvents.add(event);
185        return processedEvent;
186    }
187
188    /**
189     * Apply a processed input event.
190     *
191     * All input events should be supported, including software/hardware events, characters as well
192     * as deletions, multiple inputs and gestures.
193     *
194     * @param event the event to apply. Must not be null.
195     */
196    public void applyProcessedEvent(final Event event) {
197        mCombinerChain.applyProcessedEvent(event);
198        final int primaryCode = event.mCodePoint;
199        final int keyX = event.mX;
200        final int keyY = event.mY;
201        final int newIndex = size();
202        refreshTypedWordCache();
203        mCursorPositionWithinWord = mCodePointSize;
204        // We may have deleted the last one.
205        if (0 == mCodePointSize) {
206            mIsOnlyFirstCharCapitalized = false;
207        }
208        if (Constants.CODE_DELETE != event.mKeyCode) {
209            if (newIndex < MAX_WORD_LENGTH) {
210                // In the batch input mode, the {@code mInputPointers} holds batch input points and
211                // shouldn't be overridden by the "typed key" coordinates
212                // (See {@link #setBatchInputWord}).
213                if (!mIsBatchMode) {
214                    // TODO: Set correct pointer id and time
215                    mInputPointers.addPointerAt(newIndex, keyX, keyY, 0, 0);
216                }
217            }
218            if (0 == newIndex) {
219                mIsOnlyFirstCharCapitalized = Character.isUpperCase(primaryCode);
220            } else {
221                mIsOnlyFirstCharCapitalized = mIsOnlyFirstCharCapitalized
222                        && !Character.isUpperCase(primaryCode);
223            }
224            if (Character.isUpperCase(primaryCode)) mCapsCount++;
225            if (Character.isDigit(primaryCode)) mDigitsCount++;
226        }
227        mAutoCorrection = null;
228    }
229
230    public void setCursorPositionWithinWord(final int posWithinWord) {
231        mCursorPositionWithinWord = posWithinWord;
232        // TODO: compute where that puts us inside the events
233    }
234
235    public boolean isCursorFrontOrMiddleOfComposingWord() {
236        if (DBG && mCursorPositionWithinWord > mCodePointSize) {
237            throw new RuntimeException("Wrong cursor position : " + mCursorPositionWithinWord
238                    + "in a word of size " + mCodePointSize);
239        }
240        return mCursorPositionWithinWord != mCodePointSize;
241    }
242
243    /**
244     * When the cursor is moved by the user, we need to update its position.
245     * If it falls inside the currently composing word, we don't reset the composition, and
246     * only update the cursor position.
247     *
248     * @param expectedMoveAmount How many java chars to move the cursor. Negative values move
249     * the cursor backward, positive values move the cursor forward.
250     * @return true if the cursor is still inside the composing word, false otherwise.
251     */
252    public boolean moveCursorByAndReturnIfInsideComposingWord(final int expectedMoveAmount) {
253        // TODO: should uncommit the composing feedback
254        mCombinerChain.reset();
255        int actualMoveAmountWithinWord = 0;
256        int cursorPos = mCursorPositionWithinWord;
257        // TODO: Don't make that copy. We can do this directly from mTypedWordCache.
258        final int[] codePoints = StringUtils.toCodePointArray(mTypedWordCache);
259        if (expectedMoveAmount >= 0) {
260            // Moving the cursor forward for the expected amount or until the end of the word has
261            // been reached, whichever comes first.
262            while (actualMoveAmountWithinWord < expectedMoveAmount && cursorPos < mCodePointSize) {
263                actualMoveAmountWithinWord += Character.charCount(codePoints[cursorPos]);
264                ++cursorPos;
265            }
266        } else {
267            // Moving the cursor backward for the expected amount or until the start of the word
268            // has been reached, whichever comes first.
269            while (actualMoveAmountWithinWord > expectedMoveAmount && cursorPos > 0) {
270                --cursorPos;
271                actualMoveAmountWithinWord -= Character.charCount(codePoints[cursorPos]);
272            }
273        }
274        // If the actual and expected amounts differ, we crossed the start or the end of the word
275        // so the result would not be inside the composing word.
276        if (actualMoveAmountWithinWord != expectedMoveAmount) return false;
277        mCursorPositionWithinWord = cursorPos;
278        return true;
279    }
280
281    public void setBatchInputPointers(final InputPointers batchPointers) {
282        mInputPointers.set(batchPointers);
283        mIsBatchMode = true;
284    }
285
286    public void setBatchInputWord(final String word) {
287        reset();
288        mIsBatchMode = true;
289        final int length = word.length();
290        for (int i = 0; i < length; i = Character.offsetByCodePoints(word, i, 1)) {
291            final int codePoint = Character.codePointAt(word, i);
292            // We don't want to override the batch input points that are held in mInputPointers
293            // (See {@link #add(int,int,int)}).
294            processEvent(Event.createEventForCodePointFromUnknownSource(codePoint));
295        }
296    }
297
298    /**
299     * Set the currently composing word to the one passed as an argument.
300     * This will register NOT_A_COORDINATE for X and Ys, and use the passed keyboard for proximity.
301     * @param codePoints the code points to set as the composing word.
302     * @param coordinates the x, y coordinates of the key in the CoordinateUtils format
303     */
304    public void setComposingWord(final int[] codePoints, final int[] coordinates) {
305        reset();
306        final int length = codePoints.length;
307        for (int i = 0; i < length; ++i) {
308            processEvent(Event.createEventForCodePointFromAlreadyTypedText(codePoints[i],
309                    CoordinateUtils.xFromArray(coordinates, i),
310                    CoordinateUtils.yFromArray(coordinates, i)));
311        }
312        mIsResumed = true;
313    }
314
315    /**
316     * Returns the word as it was typed, without any correction applied.
317     * @return the word that was typed so far. Never returns null.
318     */
319    public String getTypedWord() {
320        return mTypedWordCache.toString();
321    }
322
323    /**
324     * Whether this composer is composing or about to compose a word in which only the first letter
325     * is a capital.
326     *
327     * If we do have a composing word, we just return whether the word has indeed only its first
328     * character capitalized. If we don't, then we return a value based on the capitalized mode,
329     * which tell us what is likely to happen for the next composing word.
330     *
331     * @return capitalization preference
332     */
333    public boolean isOrWillBeOnlyFirstCharCapitalized() {
334        return isComposingWord() ? mIsOnlyFirstCharCapitalized
335                : (CAPS_MODE_OFF != mCapitalizedMode);
336    }
337
338    /**
339     * Whether or not all of the user typed chars are upper case
340     * @return true if all user typed chars are upper case, false otherwise
341     */
342    public boolean isAllUpperCase() {
343        if (size() <= 1) {
344            return mCapitalizedMode == CAPS_MODE_AUTO_SHIFT_LOCKED
345                    || mCapitalizedMode == CAPS_MODE_MANUAL_SHIFT_LOCKED;
346        } else {
347            return mCapsCount == size();
348        }
349    }
350
351    public boolean wasShiftedNoLock() {
352        return mCapitalizedMode == CAPS_MODE_AUTO_SHIFTED
353                || mCapitalizedMode == CAPS_MODE_MANUAL_SHIFTED;
354    }
355
356    /**
357     * Returns true if more than one character is upper case, otherwise returns false.
358     */
359    public boolean isMostlyCaps() {
360        return mCapsCount > 1;
361    }
362
363    /**
364     * Returns true if we have digits in the composing word.
365     */
366    public boolean hasDigits() {
367        return mDigitsCount > 0;
368    }
369
370    /**
371     * Saves the caps mode at the start of composing.
372     *
373     * WordComposer needs to know about the caps mode for several reasons. The first is, we need
374     * to know after the fact what the reason was, to register the correct form into the user
375     * history dictionary: if the word was automatically capitalized, we should insert it in
376     * all-lower case but if it's a manual pressing of shift, then it should be inserted as is.
377     * Also, batch input needs to know about the current caps mode to display correctly
378     * capitalized suggestions.
379     * @param mode the mode at the time of start
380     */
381    public void setCapitalizedModeAtStartComposingTime(final int mode) {
382        mCapitalizedMode = mode;
383    }
384
385    /**
386     * Before fetching suggestions, we don't necessarily know about the capitalized mode yet.
387     *
388     * If we don't have a composing word yet, we take a note of this mode so that we can then
389     * supply this information to the suggestion process. If we have a composing word, then
390     * the previous mode has priority over this.
391     * @param mode the mode just before fetching suggestions
392     */
393    public void adviseCapitalizedModeBeforeFetchingSuggestions(final int mode) {
394        if (!isComposingWord()) {
395            mCapitalizedMode = mode;
396        }
397    }
398
399    /**
400     * Returns whether the word was automatically capitalized.
401     * @return whether the word was automatically capitalized
402     */
403    public boolean wasAutoCapitalized() {
404        return mCapitalizedMode == CAPS_MODE_AUTO_SHIFT_LOCKED
405                || mCapitalizedMode == CAPS_MODE_AUTO_SHIFTED;
406    }
407
408    /**
409     * Sets the auto-correction for this word.
410     */
411    public void setAutoCorrection(final String correction) {
412        mAutoCorrection = correction;
413    }
414
415    /**
416     * @return the auto-correction for this word, or null if none.
417     */
418    public String getAutoCorrectionOrNull() {
419        return mAutoCorrection;
420    }
421
422    /**
423     * @return whether we started composing this word by resuming suggestion on an existing string
424     */
425    public boolean isResumed() {
426        return mIsResumed;
427    }
428
429    // `type' should be one of the LastComposedWord.COMMIT_TYPE_* constants above.
430    // committedWord should contain suggestion spans if applicable.
431    public LastComposedWord commitWord(final int type, final CharSequence committedWord,
432            final String separatorString, final PrevWordsInfo prevWordsInfo) {
433        // Note: currently, we come here whenever we commit a word. If it's a MANUAL_PICK
434        // or a DECIDED_WORD we may cancel the commit later; otherwise, we should deactivate
435        // the last composed word to ensure this does not happen.
436        final LastComposedWord lastComposedWord = new LastComposedWord(mEvents,
437                mInputPointers, mTypedWordCache.toString(), committedWord, separatorString,
438                prevWordsInfo, mCapitalizedMode);
439        mInputPointers.reset();
440        if (type != LastComposedWord.COMMIT_TYPE_DECIDED_WORD
441                && type != LastComposedWord.COMMIT_TYPE_MANUAL_PICK) {
442            lastComposedWord.deactivate();
443        }
444        mCapsCount = 0;
445        mDigitsCount = 0;
446        mIsBatchMode = false;
447        mCombinerChain.reset();
448        mEvents.clear();
449        mCodePointSize = 0;
450        mIsOnlyFirstCharCapitalized = false;
451        mCapitalizedMode = CAPS_MODE_OFF;
452        refreshTypedWordCache();
453        mAutoCorrection = null;
454        mCursorPositionWithinWord = 0;
455        mIsResumed = false;
456        mRejectedBatchModeSuggestion = null;
457        return lastComposedWord;
458    }
459
460    public void resumeSuggestionOnLastComposedWord(final LastComposedWord lastComposedWord) {
461        mEvents.clear();
462        Collections.copy(mEvents, lastComposedWord.mEvents);
463        mInputPointers.set(lastComposedWord.mInputPointers);
464        mCombinerChain.reset();
465        refreshTypedWordCache();
466        mCapitalizedMode = lastComposedWord.mCapitalizedMode;
467        mAutoCorrection = null; // This will be filled by the next call to updateSuggestion.
468        mCursorPositionWithinWord = mCodePointSize;
469        mRejectedBatchModeSuggestion = null;
470        mIsResumed = true;
471    }
472
473    public boolean isBatchMode() {
474        return mIsBatchMode;
475    }
476
477    public void setRejectedBatchModeSuggestion(final String rejectedSuggestion) {
478        mRejectedBatchModeSuggestion = rejectedSuggestion;
479    }
480
481    public String getRejectedBatchModeSuggestion() {
482        return mRejectedBatchModeSuggestion;
483    }
484}
485