Search in sources :

Example 6 with SuggestedWords

use of com.android.inputmethod.latin.SuggestedWords in project android_packages_inputmethods_LatinIME by CyanogenMod.

the class InputLogic method commitChosenWord.

/**
     * Commits the chosen word to the text field and saves it for later retrieval.
     *
     * @param settingsValues the current values of the settings.
     * @param chosenWord the word we want to commit.
     * @param commitType the type of the commit, as one of LastComposedWord.COMMIT_TYPE_*
     * @param separatorString the separator that's causing the commit, or NOT_A_SEPARATOR if none.
     */
private void commitChosenWord(final SettingsValues settingsValues, final String chosenWord, final int commitType, final String separatorString) {
    long startTimeMillis = 0;
    if (DebugFlags.DEBUG_ENABLED) {
        startTimeMillis = System.currentTimeMillis();
        Log.d(TAG, "commitChosenWord() : [" + chosenWord + "]");
    }
    final SuggestedWords suggestedWords = mSuggestedWords;
    // TODO: Locale should be determined based on context and the text given.
    final Locale locale = getDictionaryFacilitatorLocale();
    final CharSequence chosenWordWithSuggestions = chosenWord;
    //                suggestedWords, locale);
    if (DebugFlags.DEBUG_ENABLED) {
        long runTimeMillis = System.currentTimeMillis() - startTimeMillis;
        Log.d(TAG, "commitChosenWord() : " + runTimeMillis + " ms to run " + "SuggestionSpanUtils.getTextWithSuggestionSpan()");
        startTimeMillis = System.currentTimeMillis();
    }
    // When we are composing word, get n-gram context from the 2nd previous word because the
    // 1st previous word is the word to be committed. Otherwise get n-gram context from the 1st
    // previous word.
    final NgramContext ngramContext = mConnection.getNgramContextFromNthPreviousWord(settingsValues.mSpacingAndPunctuations, mWordComposer.isComposingWord() ? 2 : 1);
    if (DebugFlags.DEBUG_ENABLED) {
        long runTimeMillis = System.currentTimeMillis() - startTimeMillis;
        Log.d(TAG, "commitChosenWord() : " + runTimeMillis + " ms to run " + "Connection.getNgramContextFromNthPreviousWord()");
        Log.d(TAG, "commitChosenWord() : NgramContext = " + ngramContext);
        startTimeMillis = System.currentTimeMillis();
    }
    mConnection.commitText(chosenWordWithSuggestions, 1);
    if (DebugFlags.DEBUG_ENABLED) {
        long runTimeMillis = System.currentTimeMillis() - startTimeMillis;
        Log.d(TAG, "commitChosenWord() : " + runTimeMillis + " ms to run " + "Connection.commitText");
        startTimeMillis = System.currentTimeMillis();
    }
    // Add the word to the user history dictionary
    performAdditionToUserHistoryDictionary(settingsValues, chosenWord, ngramContext);
    if (DebugFlags.DEBUG_ENABLED) {
        long runTimeMillis = System.currentTimeMillis() - startTimeMillis;
        Log.d(TAG, "commitChosenWord() : " + runTimeMillis + " ms to run " + "performAdditionToUserHistoryDictionary()");
        startTimeMillis = System.currentTimeMillis();
    }
    // TODO: figure out here if this is an auto-correct or if the best word is actually
    // what user typed. Note: currently this is done much later in
    // LastComposedWord#didCommitTypedWord by string equality of the remembered
    // strings.
    mLastComposedWord = mWordComposer.commitWord(commitType, chosenWordWithSuggestions, separatorString, ngramContext);
    if (DebugFlags.DEBUG_ENABLED) {
        long runTimeMillis = System.currentTimeMillis() - startTimeMillis;
        Log.d(TAG, "commitChosenWord() : " + runTimeMillis + " ms to run " + "WordComposer.commitWord()");
        startTimeMillis = System.currentTimeMillis();
    }
}
Also used : Locale(java.util.Locale) SuggestedWords(com.android.inputmethod.latin.SuggestedWords) NgramContext(com.android.inputmethod.latin.NgramContext)

Example 7 with SuggestedWords

use of com.android.inputmethod.latin.SuggestedWords in project android_packages_inputmethods_LatinIME by CyanogenMod.

the class InputLogic method onPickSuggestionManually.

/**
     * A suggestion was picked from the suggestion strip.
     * @param settingsValues the current values of the settings.
     * @param suggestionInfo the suggestion info.
     * @param keyboardShiftState the shift state of the keyboard, as returned by
     *     {@link com.android.inputmethod.keyboard.KeyboardSwitcher#getKeyboardShiftMode()}
     * @return the complete transaction object
     */
// Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener}
// interface
public InputTransaction onPickSuggestionManually(final SettingsValues settingsValues, final SuggestedWordInfo suggestionInfo, final int keyboardShiftState, final int currentKeyboardScriptId, final LatinIME.UIHandler handler) {
    final SuggestedWords suggestedWords = mSuggestedWords;
    final String suggestion = suggestionInfo.mWord;
    // If this is a punctuation picked from the suggestion strip, pass it to onCodeInput
    if (suggestion.length() == 1 && suggestedWords.isPunctuationSuggestions()) {
        // We still want to log a suggestion click.
        StatsUtils.onPickSuggestionManually(mSuggestedWords, suggestionInfo, mDictionaryFacilitator);
        // Word separators are suggested before the user inputs something.
        // Rely on onCodeInput to do the complicated swapping/stripping logic consistently.
        final Event event = Event.createPunctuationSuggestionPickedEvent(suggestionInfo);
        return onCodeInput(settingsValues, event, keyboardShiftState, currentKeyboardScriptId, handler);
    }
    final Event event = Event.createSuggestionPickedEvent(suggestionInfo);
    final InputTransaction inputTransaction = new InputTransaction(settingsValues, event, SystemClock.uptimeMillis(), mSpaceState, keyboardShiftState);
    // Manual pick affects the contents of the editor, so we take note of this. It's important
    // for the sequence of language switching.
    inputTransaction.setDidAffectContents();
    mConnection.beginBatchEdit();
    if (SpaceState.PHANTOM == mSpaceState && suggestion.length() > 0 && // the current batch input text and there is no need for a phantom space.
    !mWordComposer.isBatchMode()) {
        final int firstChar = Character.codePointAt(suggestion, 0);
        if (!settingsValues.isWordSeparator(firstChar) || settingsValues.isUsuallyPrecededBySpace(firstChar)) {
            insertAutomaticSpaceIfOptionsAndTextAllow(settingsValues);
        }
    }
    // the risk of calling commitCompletion twice because we don't know how the app will react.
    if (suggestionInfo.isKindOf(SuggestedWordInfo.KIND_APP_DEFINED)) {
        mSuggestedWords = SuggestedWords.getEmptyInstance();
        mSuggestionStripViewAccessor.setNeutralSuggestionStrip();
        inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW);
        resetComposingState(true);
        mConnection.commitCompletion(suggestionInfo.mApplicationSpecifiedCompletionInfo);
        mConnection.endBatchEdit();
        return inputTransaction;
    }
    commitChosenWord(settingsValues, suggestion, LastComposedWord.COMMIT_TYPE_MANUAL_PICK, LastComposedWord.NOT_A_SEPARATOR);
    mConnection.endBatchEdit();
    // Don't allow cancellation of manual pick
    mLastComposedWord.deactivate();
    // Space state must be updated before calling updateShiftState
    mSpaceState = SpaceState.PHANTOM;
    inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW);
    // If we're not showing the "Touch again to save", then update the suggestion strip.
    // That's going to be predictions (or punctuation suggestions), so INPUT_STYLE_NONE.
    handler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_NONE);
    StatsUtils.onPickSuggestionManually(mSuggestedWords, suggestionInfo, mDictionaryFacilitator);
    StatsUtils.onWordCommitSuggestionPickedManually(suggestionInfo.mWord, mWordComposer.isBatchMode());
    return inputTransaction;
}
Also used : InputTransaction(com.android.inputmethod.event.InputTransaction) SuggestedWords(com.android.inputmethod.latin.SuggestedWords) KeyEvent(android.view.KeyEvent) Event(com.android.inputmethod.event.Event) SpannableString(android.text.SpannableString)

Example 8 with SuggestedWords

use of com.android.inputmethod.latin.SuggestedWords in project android_packages_inputmethods_LatinIME by CyanogenMod.

the class InputLogic method restartSuggestionsOnWordTouchedByCursor.

/**
     * Check if the cursor is touching a word. If so, restart suggestions on this word, else
     * do nothing.
     *
     * @param settingsValues the current values of the settings.
     * @param forStartInput whether we're doing this in answer to starting the input (as opposed
     *   to a cursor move, for example). In ICS, there is a platform bug that we need to work
     *   around only when we come here at input start time.
     */
public void restartSuggestionsOnWordTouchedByCursor(final SettingsValues settingsValues, final boolean forStartInput, // TODO: remove this argument, put it into settingsValues
final int currentKeyboardScriptId) {
    // TODO: remove this.
    if (settingsValues.isBrokenByRecorrection() || // how to segment them yet.
    !settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces || // If no suggestions are requested, don't try restarting suggestions.
    !settingsValues.needsToLookupSuggestions() || // that the app moves the cursor on its own accord during a batch input.
    mInputLogicHandler.isInBatchInput() || // If the cursor is not touching a word, or if there is a selection, return right away.
    mConnection.hasSelection() || // If we don't know the cursor location, return.
    mConnection.getExpectedSelectionStart() < 0) {
        mSuggestionStripViewAccessor.setNeutralSuggestionStrip();
        return;
    }
    final int expectedCursorPosition = mConnection.getExpectedSelectionStart();
    if (!mConnection.isCursorTouchingWord(settingsValues.mSpacingAndPunctuations, true)) {
        // Show predictions.
        mWordComposer.setCapitalizedModeAtStartComposingTime(WordComposer.CAPS_MODE_OFF);
        mLatinIME.mHandler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_RECORRECTION);
        return;
    }
    final TextRange range = mConnection.getWordRangeAtCursor(settingsValues.mSpacingAndPunctuations, currentKeyboardScriptId);
    // Happens if we don't have an input connection at all
    if (null == range)
        return;
    if (range.length() <= 0) {
        // Race condition, or touching a word in a non-supported script.
        mLatinIME.setNeutralSuggestionStrip();
        return;
    }
    // If there are links, we don't resume suggestions. Making
    if (range.mHasUrlSpans)
        return;
    // edits to a linkified text through batch commands would ruin the URL spans, and unless
    // we take very complicated steps to preserve the whole link, we can't do things right so
    // we just do not resume because it's safer.
    final int numberOfCharsInWordBeforeCursor = range.getNumberOfCharsInWordBeforeCursor();
    if (numberOfCharsInWordBeforeCursor > expectedCursorPosition)
        return;
    final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<>();
    final String typedWordString = range.mWord.toString();
    final SuggestedWordInfo typedWordInfo = new SuggestedWordInfo(typedWordString, "", /* prevWordsContext */
    SuggestedWords.MAX_SUGGESTIONS + 1, SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED, SuggestedWordInfo.NOT_AN_INDEX, /* indexOfTouchPointOfSecondWord */
    SuggestedWordInfo.NOT_A_CONFIDENCE);
    suggestions.add(typedWordInfo);
    if (!isResumableWord(settingsValues, typedWordString)) {
        mSuggestionStripViewAccessor.setNeutralSuggestionStrip();
        return;
    }
    int i = 0;
    for (final SuggestionSpan span : range.getSuggestionSpansAtWord()) {
        for (final String s : span.getSuggestions()) {
            ++i;
            if (!TextUtils.equals(s, typedWordString)) {
                suggestions.add(new SuggestedWordInfo(s, "", /* prevWordsContext */
                SuggestedWords.MAX_SUGGESTIONS - i, SuggestedWordInfo.KIND_RESUMED, Dictionary.DICTIONARY_RESUMED, SuggestedWordInfo.NOT_AN_INDEX, /* indexOfTouchPointOfSecondWord */
                SuggestedWordInfo.NOT_A_CONFIDENCE));
            }
        }
    }
    final int[] codePoints = StringUtils.toCodePointArray(typedWordString);
    mWordComposer.setComposingWord(codePoints, mLatinIME.getCoordinatesForCurrentKeyboard(codePoints));
    mWordComposer.setCursorPositionWithinWord(typedWordString.codePointCount(0, numberOfCharsInWordBeforeCursor));
    if (forStartInput) {
        mConnection.maybeMoveTheCursorAroundAndRestoreToWorkaroundABug();
    }
    mConnection.setComposingRegion(expectedCursorPosition - numberOfCharsInWordBeforeCursor, expectedCursorPosition + range.getNumberOfCharsInWordAfterCursor());
    if (suggestions.size() <= 1) {
        // If there weren't any suggestion spans on this word, suggestions#size() will be 1
        // if shouldIncludeResumedWordInSuggestions is true, 0 otherwise. In this case, we
        // have no useful suggestions, so we will try to compute some for it instead.
        mInputLogicHandler.getSuggestedWords(Suggest.SESSION_ID_TYPING, SuggestedWords.NOT_A_SEQUENCE_NUMBER, new OnGetSuggestedWordsCallback() {

            @Override
            public void onGetSuggestedWords(final SuggestedWords suggestedWords) {
                doShowSuggestionsAndClearAutoCorrectionIndicator(suggestedWords);
            }
        });
    } else {
        // We found suggestion spans in the word. We'll create the SuggestedWords out of
        // them, and make willAutoCorrect false. We make typedWordValid false, because the
        // color of the word in the suggestion strip changes according to this parameter,
        // and false gives the correct color.
        final SuggestedWords suggestedWords = new SuggestedWords(suggestions, null, /* rawSuggestions */
        typedWordInfo, false, /* typedWordValid */
        false, /* willAutoCorrect */
        false, /* isObsoleteSuggestions */
        SuggestedWords.INPUT_STYLE_RECORRECTION, SuggestedWords.NOT_A_SEQUENCE_NUMBER);
        doShowSuggestionsAndClearAutoCorrectionIndicator(suggestedWords);
    }
}
Also used : OnGetSuggestedWordsCallback(com.android.inputmethod.latin.Suggest.OnGetSuggestedWordsCallback) SuggestedWordInfo(com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo) ArrayList(java.util.ArrayList) SuggestedWords(com.android.inputmethod.latin.SuggestedWords) TextRange(com.android.inputmethod.latin.utils.TextRange) SpannableString(android.text.SpannableString) SuggestionSpan(android.text.style.SuggestionSpan)

Example 9 with SuggestedWords

use of com.android.inputmethod.latin.SuggestedWords in project android_packages_inputmethods_LatinIME by CyanogenMod.

the class InputLogicHandler method showGestureSuggestionsWithPreviewVisuals.

void showGestureSuggestionsWithPreviewVisuals(final SuggestedWords suggestedWordsForBatchInput, final boolean isTailBatchInput) {
    final SuggestedWords suggestedWordsToShowSuggestions;
    // no matter what thread updateBatchInput was originally called on.
    if (suggestedWordsForBatchInput.isEmpty()) {
        // Use old suggestions if we don't have any new ones.
        // Previous suggestions are found in InputLogic#mSuggestedWords.
        // Since these are the most recent ones and we just recomputed
        // new ones to update them, then the previous ones are there.
        suggestedWordsToShowSuggestions = mInputLogic.mSuggestedWords;
    } else {
        suggestedWordsToShowSuggestions = suggestedWordsForBatchInput;
    }
    mLatinIME.mHandler.showGesturePreviewAndSuggestionStrip(suggestedWordsToShowSuggestions, isTailBatchInput);
    if (isTailBatchInput) {
        mInBatchInput = false;
        // The following call schedules onEndBatchInputInternal
        // to be called on the UI thread.
        mLatinIME.mHandler.showTailBatchInputResult(suggestedWordsToShowSuggestions);
    }
}
Also used : SuggestedWords(com.android.inputmethod.latin.SuggestedWords)

Example 10 with SuggestedWords

use of com.android.inputmethod.latin.SuggestedWords in project android_packages_inputmethods_LatinIME by CyanogenMod.

the class InputLogicHandler method updateBatchInput.

/**
     * Fetch suggestions corresponding to an update of a batch input.
     * @param batchPointers the updated pointers, including the part that was passed last time.
     * @param sequenceNumber the sequence number associated with this batch input.
     * @param isTailBatchInput true if this is the end of a batch input, false if it's an update.
     */
// This method can be called from any thread and will see to it that the correct threads
// are used for parts that require it. This method will send a message to the Non-UI handler
// thread to pull suggestions, and get the inlined callback to get called on the Non-UI
// handler thread. If this is the end of a batch input, the callback will then proceed to
// send a message to the UI handler in LatinIME so that showing suggestions can be done on
// the UI thread.
private void updateBatchInput(final InputPointers batchPointers, final int sequenceNumber, final boolean isTailBatchInput) {
    synchronized (mLock) {
        if (!mInBatchInput) {
            // Batch input has ended or canceled while the message was being delivered.
            return;
        }
        mInputLogic.mWordComposer.setBatchInputPointers(batchPointers);
        final OnGetSuggestedWordsCallback callback = new OnGetSuggestedWordsCallback() {

            @Override
            public void onGetSuggestedWords(final SuggestedWords suggestedWords) {
                showGestureSuggestionsWithPreviewVisuals(suggestedWords, isTailBatchInput);
            }
        };
        getSuggestedWords(isTailBatchInput ? SuggestedWords.INPUT_STYLE_TAIL_BATCH : SuggestedWords.INPUT_STYLE_UPDATE_BATCH, sequenceNumber, callback);
    }
}
Also used : OnGetSuggestedWordsCallback(com.android.inputmethod.latin.Suggest.OnGetSuggestedWordsCallback) SuggestedWords(com.android.inputmethod.latin.SuggestedWords)

Aggregations

SuggestedWords (com.android.inputmethod.latin.SuggestedWords)10 SuggestedWordInfo (com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo)4 SpannableString (android.text.SpannableString)3 OnGetSuggestedWordsCallback (com.android.inputmethod.latin.Suggest.OnGetSuggestedWordsCallback)3 ArrayList (java.util.ArrayList)2 Locale (java.util.Locale)2 SuggestionSpan (android.text.style.SuggestionSpan)1 KeyEvent (android.view.KeyEvent)1 Event (com.android.inputmethod.event.Event)1 InputTransaction (com.android.inputmethod.event.InputTransaction)1 Keyboard (com.android.inputmethod.keyboard.Keyboard)1 NgramContext (com.android.inputmethod.latin.NgramContext)1 MoreSuggestionKey (com.android.inputmethod.latin.suggestions.MoreSuggestions.MoreSuggestionKey)1 AsyncResultHolder (com.android.inputmethod.latin.utils.AsyncResultHolder)1 TextRange (com.android.inputmethod.latin.utils.TextRange)1