Example usage for android.view.inputmethod InputConnection beginBatchEdit

List of usage examples for android.view.inputmethod InputConnection beginBatchEdit

Introduction

In this page you can find the example usage for android.view.inputmethod InputConnection beginBatchEdit.

Prototype

boolean beginBatchEdit();

Source Link

Document

Tell the editor that you are starting a batch of editor operations.

Usage

From source file:net.zhdev.ctrlvkeyboard.CtrlVKeyboard.java

/**
 * Inserts text in the current focused text editor if possible and if it is a valid one.
 *
 * @param text          the text to be inserted
 * @param clearBefore   whether the text editor should be cleared before inserting the text
 * @param endWithAction whether the IME action should be performed at the end
 * @return {@code true} if the text was inserted and the actions performed, {@code false}
 * otherwise//from www  .  j  a v a 2  s  . com
 */
private boolean type(String text, boolean clearBefore, boolean endWithAction) {
    boolean result = false;

    if (text == null) {
        text = "";
    }

    EditorInfo info = getCurrentInputEditorInfo();

    if (info != null) {
        // If the view accepts text as input
        if ((info.inputType & EditorInfo.TYPE_MASK_CLASS) != EditorInfo.TYPE_NULL) {
            InputConnection ic = getCurrentInputConnection();

            if (ic != null) {
                boolean enterShouldHaveAction = true;
                ic.beginBatchEdit();
                if (endWithAction) {
                    enterShouldHaveAction = (info.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) == 0;
                    if (!enterShouldHaveAction) {
                        text += "\n";
                    }
                }
                if (clearBefore) {
                    ic.deleteSurroundingText(Integer.MAX_VALUE, Integer.MAX_VALUE);
                }
                ic.commitText(text, 1);
                result = ic.endBatchEdit();

                if (result && endWithAction && enterShouldHaveAction) {
                    result = ic.performEditorAction(info.imeOptions & EditorInfo.IME_MASK_ACTION);
                }
            }
        }
    }
    return result;
}

From source file:com.volosyukivan.WiFiInputMethod.java

boolean setText(String text) {
    // FIXME: need feedback if the input was lost
    InputConnection conn = getCurrentInputConnection();
    if (conn == null) {
        //      Debug.d("connection closed");
        return false;
    }/*from www .j a  v  a 2 s .  c  o  m*/
    conn.beginBatchEdit();
    // FIXME: hack
    conn.deleteSurroundingText(100000, 100000);
    conn.commitText(text, text.length());
    conn.endBatchEdit();
    return true;
}

From source file:research.sg.edu.edapp.kb.KbSoftKeyboard.java

public void onText(CharSequence text) {
    InputConnection ic = getCurrentInputConnection();
    if (ic == null)
        return;//from  w ww . ja  v a2s  .c  o  m
    ic.beginBatchEdit();
    if (mComposing.length() > 0) {
        commitTyped(ic);
    }
    ic.commitText(text, 0);
    ic.endBatchEdit();
    updateShiftKeyState(getCurrentInputEditorInfo());
}

From source file:android.support.text.emoji.EmojiProcessor.java

/**
 * Handles deleteSurroundingText commands from {@link InputConnection} and tries to delete an
 * {@link EmojiSpan} from an {@link Editable}. Returns {@code true} if an {@link EmojiSpan} is
 * deleted.//  w  ww.j  a v  a2  s.c om
 * <p/>
 * If there is a selection where selection start is not equal to selection end, does not
 * delete.
 *
 * @param inputConnection InputConnection instance
 * @param editable TextView.Editable instance
 * @param beforeLength the number of characters before the cursor to be deleted
 * @param afterLength the number of characters after the cursor to be deleted
 * @param inCodePoints {@code true} if length parameters are in codepoints
 *
 * @return {@code true} if an {@link EmojiSpan} is deleted
 */
static boolean handleDeleteSurroundingText(@NonNull final InputConnection inputConnection,
        @NonNull final Editable editable, @IntRange(from = 0) final int beforeLength,
        @IntRange(from = 0) final int afterLength, final boolean inCodePoints) {
    //noinspection ConstantConditions
    if (editable == null || inputConnection == null) {
        return false;
    }

    if (beforeLength < 0 || afterLength < 0) {
        return false;
    }

    final int selectionStart = Selection.getSelectionStart(editable);
    final int selectionEnd = Selection.getSelectionEnd(editable);

    if (hasInvalidSelection(selectionStart, selectionEnd)) {
        return false;
    }

    int start;
    int end;
    if (inCodePoints) {
        // go backwards in terms of codepoints
        start = CodepointIndexFinder.findIndexBackward(editable, selectionStart, Math.max(beforeLength, 0));
        end = CodepointIndexFinder.findIndexForward(editable, selectionEnd, Math.max(afterLength, 0));

        if (start == CodepointIndexFinder.INVALID_INDEX || end == CodepointIndexFinder.INVALID_INDEX) {
            return false;
        }
    } else {
        start = Math.max(selectionStart - beforeLength, 0);
        end = Math.min(selectionEnd + afterLength, editable.length());
    }

    final EmojiSpan[] spans = editable.getSpans(start, end, EmojiSpan.class);
    if (spans != null && spans.length > 0) {
        final int length = spans.length;
        for (int index = 0; index < length; index++) {
            final EmojiSpan span = spans[index];
            int spanStart = editable.getSpanStart(span);
            int spanEnd = editable.getSpanEnd(span);
            start = Math.min(spanStart, start);
            end = Math.max(spanEnd, end);
        }

        start = Math.max(start, 0);
        end = Math.min(end, editable.length());

        inputConnection.beginBatchEdit();
        editable.delete(start, end);
        inputConnection.endBatchEdit();
        return true;
    }

    return false;
}

From source file:com.yek.keyboard.anysoftkeyboard.AnySoftKeyboard.java

public void onText(Keyboard.Key key, CharSequence text) {
    Logger.d(TAG, "onText: '%s'", text);
    InputConnection ic = getCurrentInputConnection();
    if (ic == null)
        return;//w  w  w  .jav a  2s.c om
    ic.beginBatchEdit();

    abortCorrectionAndResetPredictionState(false);
    ic.commitText(text, 1);

    mJustAddedAutoSpace = false;
    mCommittedWord = text;
    mUndoCommitCursorPosition = UNDO_COMMIT_WAITING_TO_RECORD_POSITION;

    TextEntryState.acceptedDefault(text);
    ic.endBatchEdit();

    setSuggestions(mSuggest.getNextSuggestions(mCommittedWord, false), false, false, false);
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

public void onMultiTapStarted() {
    final InputConnection ic = getCurrentInputConnection();
    if (ic != null)
        ic.beginBatchEdit();
    handleDeleteLastCharacter(true);/*from  w ww.j a  v  a  2 s .  c o  m*/
    if (getInputView() != null)
        getInputView().setShifted(mLastCharacterWasShifted);
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

public void onText(Key key, CharSequence text) {
    Logger.d(TAG, "onText: '%s'", text);
    InputConnection ic = getCurrentInputConnection();
    if (ic == null)
        return;/*from w  w w. j a v a 2  s .  c  o  m*/
    ic.beginBatchEdit();

    abortCorrectionAndResetPredictionState(false);
    ic.commitText(text, 1);

    mJustAddedAutoSpace = false;
    mCommittedWord = text;
    mUndoCommitCursorPosition = UNDO_COMMIT_WAITING_TO_RECORD_POSITION;

    TextEntryState.acceptedDefault(text);
    ic.endBatchEdit();

    setSuggestions(mSuggest.getNextSuggestions(mCommittedWord, false), false, false, false);
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

public void revertLastWord() {
    final int length = mCommittedWord.length() + (mJustAddedAutoSpace ? 1 : 0);
    if (length > 0) {
        mAutoCorrectOn = false;/*from www  .j  ava 2s.c  o m*/
        //note: typedWord may be empty
        final InputConnection ic = getCurrentInputConnection();
        mUndoCommitCursorPosition = UNDO_COMMIT_NONE;
        ic.beginBatchEdit();
        ic.deleteSurroundingText(length, 0);
        final CharSequence typedWord = mWord.getTypedWord();
        ic.setComposingText(typedWord/* mComposing */, 1);
        TextEntryState.backspace();
        ic.endBatchEdit();
        performUpdateSuggestions();
        if (mJustAutoAddedWord) {
            removeFromUserDictionary(typedWord.toString());
        }
        getInputView().revertPopTextOutOfKey();
    } else {
        sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
    }
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

public void pickSuggestionManually(int index, CharSequence suggestion) {
    final String typedWord = mWord.getTypedWord().toString();

    if (mWord.isAtTagsSearchState()) {
        if (index == 0) {
            //this is a special case for tags-searcher
            //since we append a magnifying glass to the suggestions, the "suggestion"
            //value is not a valid output suggestion
            suggestion = typedWord;/*from  w  w  w  . jav  a 2s  .  c o  m*/
        } else {
            //regular emoji. Storing in history.
            List<QuickKeyHistoryRecords.HistoryKey> keys = QuickKeyHistoryRecords.load(getSharedPrefs());
            QuickKeyHistoryRecords.store(getSharedPrefs(), keys,
                    new QuickKeyHistoryRecords.HistoryKey(suggestion.toString(), suggestion.toString()));
        }
    }

    final InputConnection ic = getCurrentInputConnection();
    if (ic != null) {
        ic.beginBatchEdit();
    }

    TextEntryState.acceptedSuggestion(typedWord, suggestion);

    try {
        if (mCompletionOn && mCompletions != null && index >= 0 && index < mCompletions.length) {
            CompletionInfo ci = mCompletions[index];
            if (ic != null) {
                ic.commitCompletion(ci);
            }
            mCommittedWord = suggestion;
            if (mCandidateView != null) {
                mCandidateView.clear();
            }
            return;
        }
        commitWordToInput(suggestion,
                false/*user physically picked a word from the suggestions strip. this is not a fix*/);

        TextEntryState.acceptedSuggestion(mWord.getTypedWord(), suggestion);
        // Follow it with a space
        if (mAutoSpace && (index == 0 || !mWord.isAtTagsSearchState())) {
            sendKeyChar((char) KeyCodes.SPACE);
            mJustAddedAutoSpace = true;
            setSpaceTimeStamp(true);
            TextEntryState.typedCharacter(' ', true);
        }
        // Add the word to the auto dictionary if it's not a known word
        mJustAutoAddedWord = false;

        if (!mWord.isAtTagsSearchState()) {
            if (index == 0) {
                mJustAutoAddedWord = checkAddToDictionaryWithAutoDictionary(mWord,
                        AutoDictionary.AdditionType.Picked);
                if (mJustAutoAddedWord)
                    TextEntryState.acceptedSuggestionAddedToDictionary();
            }

            final boolean showingAddToDictionaryHint = (!mJustAutoAddedWord) && index == 0
                    && (mQuickFixes || mShowSuggestions) && (!mSuggest.isValidWord(suggestion))// this is for the case that the word was auto-added upon picking
                    && (!mSuggest.isValidWord(
                            suggestion.toString().toLowerCase(getCurrentAlphabetKeyboard().getLocale())));

            if (showingAddToDictionaryHint) {
                if (mCandidateView != null)
                    mCandidateView.showAddToDictionaryHint(suggestion);
            } else if (!TextUtils.isEmpty(mCommittedWord) && !mJustAutoAddedWord) {
                //showing next-words if:
                //showingAddToDictionaryHint == false, we most likely do not have a next-word suggestion! The committed word is not in the dictionary
                //mJustAutoAddedWord == false, we most likely do not have a next-word suggestion for a newly added word.
                setSuggestions(mSuggest.getNextSuggestions(mCommittedWord, mWord.isAllUpperCase()), false,
                        false, false);
                mWord.setFirstCharCapitalized(false);
            }
        }
    } finally {
        if (ic != null) {
            ic.endBatchEdit();
        }
    }
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

private void handleSeparator(int primaryCode) {
    // Issue 146: Right to left languages require reversed parenthesis
    if (!getCurrentAlphabetKeyboard().isLeftToRightLanguage()) {
        if (primaryCode == (int) ')')
            primaryCode = (int) '(';
        else if (primaryCode == (int) '(')
            primaryCode = (int) ')';
    }/*from   w  ww.  ja  v  a 2  s .  com*/
    mExpectingSelectionUpdateBy = SystemClock.uptimeMillis() + MAX_TIME_TO_EXPECT_SELECTION_UPDATE;
    //will not show next-word suggestion in case of a new line or if the separator is a sentence separator.
    boolean isEndOfSentence = (primaryCode == KeyCodes.ENTER || mSentenceSeparators.get(primaryCode));

    // Should dismiss the "Touch again to save" message when handling
    // separator
    if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
        postUpdateSuggestions();
    }

    // Handle separator
    InputConnection ic = getCurrentInputConnection();
    if (ic != null) {
        ic.beginBatchEdit();
    }
    // this is a special case, when the user presses a separator WHILE
    // inside the predicted word.
    // in this case, I will want to just dump the separator.
    final boolean separatorInsideWord = (mWord.cursorPosition() < mWord.length());
    if (TextEntryState.isPredicting() && !separatorInsideWord) {
        //ACTION does not invoke default picking. See https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/198
        pickDefaultSuggestion(mAutoCorrectOn && primaryCode != KeyCodes.ENTER);
        // Picked the suggestion by a space/punctuation character: we will treat it
        // as "added an auto space".
        mJustAddedAutoSpace = true;
    } else if (separatorInsideWord) {
        // when putting a separator in the middle of a word, there is no
        // need to do correction, or keep knowledge
        abortCorrectionAndResetPredictionState(false);
    }

    if (mJustAddedAutoSpace && primaryCode == KeyCodes.ENTER) {
        removeTrailingSpace();
        mJustAddedAutoSpace = false;
    }

    boolean handledOutputToInputConnection = false;

    if (ic != null) {
        if (primaryCode == KeyCodes.SPACE) {
            if (mAskPrefs.isDoubleSpaceChangesToPeriod()) {
                if ((SystemClock.uptimeMillis()
                        - mLastSpaceTimeStamp) < ((long) mAskPrefs.getMultiTapTimeout())) {
                    //current text in the input-box should be something like "word "
                    //the user pressed on space again. So we want to change the text in the input-box
                    //into "word "->"word. "
                    ic.deleteSurroundingText(1, 0);
                    ic.commitText(". ", 1);
                    mJustAddedAutoSpace = true;
                    isEndOfSentence = true;
                    handledOutputToInputConnection = true;
                }
            }
        } else if (mJustAddedAutoSpace && mLastSpaceTimeStamp != NEVER_TIME_STAMP/*meaning last key was SPACE*/
                && mAskPrefs.shouldSwapPunctuationAndSpace() && primaryCode != KeyCodes.ENTER
                && isSentenceSeparator(primaryCode)) {
            //current text in the input-box should be something like "word "
            //the user pressed a punctuation (say ","). So we want to change the text in the input-box
            //into "word "->"word, "
            ic.deleteSurroundingText(1, 0);
            ic.commitText(((char) primaryCode) + " ", 1);
            mJustAddedAutoSpace = true;
            handledOutputToInputConnection = true;
        }
    }

    if (!handledOutputToInputConnection) {
        sendKeyChar((char) primaryCode);
    }
    TextEntryState.typedCharacter((char) primaryCode, true);

    if (ic != null) {
        ic.endBatchEdit();
    }

    if (isEndOfSentence) {
        mSuggest.resetNextWordSentence();
        clearSuggestions();
    } else if (!TextUtils.isEmpty(mCommittedWord)) {
        setSuggestions(mSuggest.getNextSuggestions(mCommittedWord, mWord.isAllUpperCase()), false, false,
                false);
        mWord.setFirstCharCapitalized(false);
    }
}