Example usage for android.view.inputmethod InputConnection getTextAfterCursor

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

Introduction

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

Prototype

CharSequence getTextAfterCursor(int n, int flags);

Source Link

Document

Get n characters of text after the current cursor position.

Usage

From source file:Main.java

/**
 * Returns the selected text between the selStart and selEnd positions.
 *///from w w  w  . j  av a 2  s. c  o m
private static CharSequence getSelectedText(InputConnection ic, int selStart, int selEnd) {
    // Use reflection, for backward compatibility
    CharSequence result = null;
    if (!sMethodsInitialized) {
        initializeMethodsForReflection();
    }
    if (sMethodGetSelectedText != null) {
        try {
            result = (CharSequence) sMethodGetSelectedText.invoke(ic, 0);
            return result;
        } catch (InvocationTargetException exc) {
            // Ignore
        } catch (IllegalArgumentException e) {
            // Ignore
        } catch (IllegalAccessException e) {
            // Ignore
        }
    }
    // Reflection didn't work, try it the poor way, by moving the cursor to the start,
    // getting the text after the cursor and moving the text back to selected mode.
    // TODO: Verify that this works properly in conjunction with 
    // LatinIME#onUpdateSelection
    ic.setSelection(selStart, selEnd);
    result = ic.getTextAfterCursor(selEnd - selStart, 0);
    ic.setSelection(selStart, selEnd);
    return result;
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

private boolean isCursorTouchingWord() {
    InputConnection ic = getCurrentInputConnection();
    if (ic == null)
        return false;

    CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
    // It is not exactly clear to me why, but sometimes, although I request
    // 1 character, I get
    // the entire text. This causes me to incorrectly detect restart
    // suggestions...
    if (!TextUtils.isEmpty(toLeft) && toLeft.length() == 1 && !isWordSeparator(toLeft.charAt(0))) {
        return true;
    }/*ww w .  j  av  a 2  s.co m*/

    CharSequence toRight = ic.getTextAfterCursor(1, 0);
    return (!TextUtils.isEmpty(toRight)) && (toRight.length() == 1) && (!isWordSeparator(toRight.charAt(0)));
}

From source file:org.distantshoresmedia.keyboard.LatinIME.java

private boolean isCursorTouchingWord() {
    InputConnection ic = getCurrentInputConnection();
    if (ic == null)
        return false;
    CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
    CharSequence toRight = ic.getTextAfterCursor(1, 0);
    if (!TextUtils.isEmpty(toLeft) && !isWordSeparator(toLeft.charAt(0))
            && !isSuggestedPunctuation(toLeft.charAt(0))) {
        return true;
    }//ww  w  . ja v a2s . c  o  m
    if (!TextUtils.isEmpty(toRight) && !isWordSeparator(toRight.charAt(0))
            && !isSuggestedPunctuation(toRight.charAt(0))) {
        return true;
    }
    return false;
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

public void performRestartWordSuggestion(final InputConnection ic) {
    // I assume ASK DOES NOT predict at this moment!

    // 2) predicting and moved outside the word - abort predicting, update
    // shift state
    // 2.1) to a new word - restart predicting on the new word
    // 2.2) to no word land - nothing else

    // this means that the new cursor position is outside the candidates
    // underline/*  w  w  w  . jav a2 s .c  om*/
    // this can be either because the cursor is really outside the
    // previously underlined (suggested)
    // or nothing was suggested.
    // in this case, we would like to reset the prediction and restart
    // if the user clicked inside a different word
    // restart required?
    if (canRestartWordSuggestion()) {// 2.1
        ic.beginBatchEdit();// don't want any events till I finish handling
        // this touch
        abortCorrectionAndResetPredictionState(false);

        // locating the word
        CharSequence toLeft = "";
        CharSequence toRight = "";
        while (true) {
            CharSequence newToLeft = ic.getTextBeforeCursor(toLeft.length() + 1, 0);
            if (TextUtils.isEmpty(newToLeft) || isWordSeparator(newToLeft.charAt(0))
                    || newToLeft.length() == toLeft.length()) {
                break;
            }
            toLeft = newToLeft;
        }
        while (true) {
            CharSequence newToRight = ic.getTextAfterCursor(toRight.length() + 1, 0);
            if (TextUtils.isEmpty(newToRight) || isWordSeparator(newToRight.charAt(newToRight.length() - 1))
                    || newToRight.length() == toRight.length()) {
                break;
            }
            toRight = newToRight;
        }
        CharSequence word = toLeft.toString() + toRight.toString();
        Logger.d(TAG, "Starting new prediction on word '%s'.", word);
        mUndoCommitCursorPosition = UNDO_COMMIT_NONE;
        mWord.reset();

        final int[] tempNearByKeys = new int[1];

        for (int index = 0; index < word.length(); index++) {
            final char c = word.charAt(index);
            if (index == 0)
                mWord.setFirstCharCapitalized(Character.isUpperCase(c));

            tempNearByKeys[0] = c;
            mWord.add(c, tempNearByKeys);

            TextEntryState.typedCharacter(c, false);
        }
        ic.deleteSurroundingText(toLeft.length(), toRight.length());
        ic.setComposingText(word, 1);
        // repositioning the cursor
        if (toRight.length() > 0) {
            final int cursorPosition = getCursorPosition(ic) - toRight.length();
            Logger.d(TAG, "Repositioning the cursor inside the word to position %d", cursorPosition);
            ic.setSelection(cursorPosition, cursorPosition);
        }

        mWord.setCursorPosition(toLeft.length());
        ic.endBatchEdit();
        postUpdateSuggestions();
    } else {
        Logger.d(TAG, "performRestartWordSuggestion canRestartWordSuggestion == false");
    }
}

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

private void onFunctionKey(final int primaryCode, final Keyboard.Key key, final int multiTapIndex,
        final int[] nearByKeyCodes, final boolean fromUI) {
    if (BuildConfig.DEBUG)
        Logger.d(TAG, "onFunctionKey %d", primaryCode);

    final InputConnection ic = getCurrentInputConnection();

    switch (primaryCode) {
    case KeyCodes.DELETE:
        if (ic == null)// if we don't want to do anything, lets check null first.
            break;
        // we do backword if the shift is pressed while pressing
        // backspace (like in a PC)
        if (mAskPrefs.useBackword() && mShiftKeyState.isPressed() && !mShiftKeyState.isLocked()) {
            handleBackWord(ic);/*from   www. j a v  a 2 s. com*/
        } else {
            handleDeleteLastCharacter(false);
        }
        break;
    case KeyCodes.SHIFT:
        if (fromUI) {
            handleShift();
        } else {
            //not from UI (user not actually pressed that button)
            onPress(primaryCode);
            onRelease(primaryCode);
        }
        break;
    case KeyCodes.SHIFT_LOCK:
        mShiftKeyState.toggleLocked();
        handleShift();
        break;
    case KeyCodes.DELETE_WORD:
        if (ic == null)// if we don't want to do anything, lets check
            // null first.
            break;
        handleBackWord(ic);
        break;
    case KeyCodes.CLEAR_INPUT:
        if (ic != null) {
            ic.beginBatchEdit();
            abortCorrectionAndResetPredictionState(false);
            ic.deleteSurroundingText(Integer.MAX_VALUE, Integer.MAX_VALUE);
            ic.endBatchEdit();
        }
        break;
    case KeyCodes.CTRL:
        if (fromUI) {
            handleControl();
        } else {
            //not from UI (user not actually pressed that button)
            onPress(primaryCode);
            onRelease(primaryCode);
        }
        break;
    case KeyCodes.CTRL_LOCK:
        mControlKeyState.toggleLocked();
        handleControl();
        break;
    case KeyCodes.ARROW_LEFT:
    case KeyCodes.ARROW_RIGHT:
        final int keyEventKeyCode = primaryCode == KeyCodes.ARROW_LEFT ? KeyEvent.KEYCODE_DPAD_LEFT
                : KeyEvent.KEYCODE_DPAD_RIGHT;
        if (!handleSelectionExpending(keyEventKeyCode, ic, mGlobalSelectionStartPosition,
                mGlobalCursorPosition)) {
            sendDownUpKeyEvents(keyEventKeyCode);
        }
        break;
    case KeyCodes.ARROW_UP:
        sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_UP);
        break;
    case KeyCodes.ARROW_DOWN:
        sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_DOWN);
        break;
    case KeyCodes.MOVE_HOME:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            sendDownUpKeyEvents(0x0000007a/*API 11:KeyEvent.KEYCODE_MOVE_HOME*/);
        } else {
            if (ic != null) {
                CharSequence textBefore = ic.getTextBeforeCursor(1024, 0);
                if (!TextUtils.isEmpty(textBefore)) {
                    int newPosition = textBefore.length() - 1;
                    while (newPosition > 0) {
                        char chatAt = textBefore.charAt(newPosition - 1);
                        if (chatAt == '\n' || chatAt == '\r') {
                            break;
                        }
                        newPosition--;
                    }
                    if (newPosition < 0)
                        newPosition = 0;
                    ic.setSelection(newPosition, newPosition);
                }
            }
        }
        break;
    case KeyCodes.MOVE_END:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            //API 11: KeyEvent.KEYCODE_MOVE_END
            sendDownUpKeyEvents(0x0000007b);
        } else {
            if (ic != null) {
                CharSequence textAfter = ic.getTextAfterCursor(1024, 0);
                if (!TextUtils.isEmpty(textAfter)) {
                    int newPosition = 1;
                    while (newPosition < textAfter.length()) {
                        char chatAt = textAfter.charAt(newPosition);
                        if (chatAt == '\n' || chatAt == '\r') {
                            break;
                        }
                        newPosition++;
                    }
                    if (newPosition > textAfter.length())
                        newPosition = textAfter.length();
                    try {
                        CharSequence textBefore = ic.getTextBeforeCursor(Integer.MAX_VALUE, 0);
                        if (!TextUtils.isEmpty(textBefore)) {
                            newPosition = newPosition + textBefore.length();
                        }
                        ic.setSelection(newPosition, newPosition);
                    } catch (Throwable e/*I'm using Integer.MAX_VALUE, it's scary.*/) {
                        Logger.w(TAG, "Failed to getTextBeforeCursor.", e);
                    }
                }
            }
        }
        break;
    case KeyCodes.VOICE_INPUT:
        if (mVoiceRecognitionTrigger.isInstalled()) {
            mVoiceRecognitionTrigger
                    .startVoiceRecognition(getCurrentAlphabetKeyboard().getDefaultDictionaryLocale());
        } else {
            Intent voiceInputNotInstalledIntent = new Intent(getApplicationContext(),
                    VoiceInputNotInstalledActivity.class);
            voiceInputNotInstalledIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(voiceInputNotInstalledIntent);
        }
        break;
    case KeyCodes.CANCEL:
        handleClose();
        break;
    case KeyCodes.SETTINGS:
        showOptionsMenu();
        break;
    case KeyCodes.SPLIT_LAYOUT:
    case KeyCodes.MERGE_LAYOUT:
    case KeyCodes.COMPACT_LAYOUT_TO_RIGHT:
    case KeyCodes.COMPACT_LAYOUT_TO_LEFT:
        if (getInputView() != null) {
            mKeyboardInCondensedMode = CondenseType.fromKeyCode(primaryCode);
            setKeyboardForView(getCurrentKeyboard());
        }
        break;
    case KeyCodes.DOMAIN:
        onText(key, mAskPrefs.getDomainText());
        break;
    case KeyCodes.QUICK_TEXT:
        onQuickTextRequested(key);
        break;
    case KeyCodes.QUICK_TEXT_POPUP:
        onQuickTextKeyboardRequested(key);
        break;
    case KeyCodes.MODE_SYMOBLS:
        nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.Symbols);
        break;
    case KeyCodes.MODE_ALPHABET:
        if (getKeyboardSwitcher().shouldPopupForLanguageSwitch()) {
            showLanguageSelectionDialog();
        } else {
            nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.Alphabet);
        }
        break;
    case KeyCodes.UTILITY_KEYBOARD:
        getInputView().openUtilityKeyboard();
        break;
    case KeyCodes.MODE_ALPHABET_POPUP:
        showLanguageSelectionDialog();
        break;
    case KeyCodes.ALT:
        nextAlterKeyboard(getCurrentInputEditorInfo());
        break;
    case KeyCodes.KEYBOARD_CYCLE:
        nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.Any);
        break;
    case KeyCodes.KEYBOARD_REVERSE_CYCLE:
        nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.PreviousAny);
        break;
    case KeyCodes.KEYBOARD_CYCLE_INSIDE_MODE:
        nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.AnyInsideMode);
        break;
    case KeyCodes.KEYBOARD_MODE_CHANGE:
        nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.OtherMode);
        break;
    case KeyCodes.CLIPBOARD_COPY:
    case KeyCodes.CLIPBOARD_PASTE:
    case KeyCodes.CLIPBOARD_CUT:
    case KeyCodes.CLIPBOARD_SELECT_ALL:
    case KeyCodes.CLIPBOARD_PASTE_POPUP:
    case KeyCodes.CLIPBOARD_SELECT:
        handleClipboardOperation(key, primaryCode, ic);
        //not allowing undo on-text in clipboard paste operations.
        if (primaryCode == KeyCodes.CLIPBOARD_PASTE)
            mCommittedWord = "";
        break;
    default:
        if (BuildConfig.DEBUG) {
            //this should not happen! We should handle ALL function keys.
            throw new RuntimeException("UNHANDLED FUNCTION KEY! primary code " + primaryCode);
        } else {
            Logger.w(TAG, "UNHANDLED FUNCTION KEY! primary code %d. Ignoring.", primaryCode);
        }
    }
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

private void onFunctionKey(final int primaryCode, final Key key, final int multiTapIndex,
        final int[] nearByKeyCodes, final boolean fromUI) {
    if (BuildConfig.DEBUG)
        Logger.d(TAG, "onFunctionKey %d", primaryCode);

    final InputConnection ic = getCurrentInputConnection();

    switch (primaryCode) {
    case KeyCodes.DELETE:
        if (ic == null)// if we don't want to do anything, lets check null first.
            break;
        // we do backword if the shift is pressed while pressing
        // backspace (like in a PC)
        if (mAskPrefs.useBackword() && mShiftKeyState.isPressed() && !mShiftKeyState.isLocked()) {
            handleBackWord(ic);/* ww w  .j  av  a2  s.  com*/
        } else {
            handleDeleteLastCharacter(false);
        }
        break;
    case KeyCodes.SHIFT:
        if (fromUI) {
            handleShift();
        } else {
            //not from UI (user not actually pressed that button)
            onPress(primaryCode);
            onRelease(primaryCode);
        }
        break;
    case KeyCodes.SHIFT_LOCK:
        mShiftKeyState.toggleLocked();
        handleShift();
        break;
    case KeyCodes.DELETE_WORD:
        if (ic == null)// if we don't want to do anything, lets check
            // null first.
            break;
        handleBackWord(ic);
        break;
    case KeyCodes.CLEAR_INPUT:
        if (ic != null) {
            ic.beginBatchEdit();
            abortCorrectionAndResetPredictionState(false);
            ic.deleteSurroundingText(Integer.MAX_VALUE, Integer.MAX_VALUE);
            ic.endBatchEdit();
        }
        break;
    case KeyCodes.CTRL:
        if (fromUI) {
            handleControl();
        } else {
            //not from UI (user not actually pressed that button)
            onPress(primaryCode);
            onRelease(primaryCode);
        }
        break;
    case KeyCodes.CTRL_LOCK:
        mControlKeyState.toggleLocked();
        handleControl();
        break;
    case KeyCodes.ARROW_LEFT:
    case KeyCodes.ARROW_RIGHT:
        final int keyEventKeyCode = primaryCode == KeyCodes.ARROW_LEFT ? KeyEvent.KEYCODE_DPAD_LEFT
                : KeyEvent.KEYCODE_DPAD_RIGHT;
        if (!handleSelectionExpending(keyEventKeyCode, ic, mGlobalSelectionStartPosition,
                mGlobalCursorPosition)) {
            sendDownUpKeyEvents(keyEventKeyCode);
        }
        break;
    case KeyCodes.ARROW_UP:
        sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_UP);
        break;
    case KeyCodes.ARROW_DOWN:
        sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_DOWN);
        break;
    case KeyCodes.MOVE_HOME:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            sendDownUpKeyEvents(0x0000007a/*API 11:KeyEvent.KEYCODE_MOVE_HOME*/);
        } else {
            if (ic != null) {
                CharSequence textBefore = ic.getTextBeforeCursor(1024, 0);
                if (!TextUtils.isEmpty(textBefore)) {
                    int newPosition = textBefore.length() - 1;
                    while (newPosition > 0) {
                        char chatAt = textBefore.charAt(newPosition - 1);
                        if (chatAt == '\n' || chatAt == '\r') {
                            break;
                        }
                        newPosition--;
                    }
                    if (newPosition < 0)
                        newPosition = 0;
                    ic.setSelection(newPosition, newPosition);
                }
            }
        }
        break;
    case KeyCodes.MOVE_END:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            //API 11: KeyEvent.KEYCODE_MOVE_END
            sendDownUpKeyEvents(0x0000007b);
        } else {
            if (ic != null) {
                CharSequence textAfter = ic.getTextAfterCursor(1024, 0);
                if (!TextUtils.isEmpty(textAfter)) {
                    int newPosition = 1;
                    while (newPosition < textAfter.length()) {
                        char chatAt = textAfter.charAt(newPosition);
                        if (chatAt == '\n' || chatAt == '\r') {
                            break;
                        }
                        newPosition++;
                    }
                    if (newPosition > textAfter.length())
                        newPosition = textAfter.length();
                    try {
                        CharSequence textBefore = ic.getTextBeforeCursor(Integer.MAX_VALUE, 0);
                        if (!TextUtils.isEmpty(textBefore)) {
                            newPosition = newPosition + textBefore.length();
                        }
                        ic.setSelection(newPosition, newPosition);
                    } catch (Throwable e/*I'm using Integer.MAX_VALUE, it's scary.*/) {
                        Logger.w(TAG, "Failed to getTextBeforeCursor.", e);
                    }
                }
            }
        }
        break;
    case KeyCodes.VOICE_INPUT:
        if (mVoiceRecognitionTrigger.isInstalled()) {
            mVoiceRecognitionTrigger
                    .startVoiceRecognition(getCurrentAlphabetKeyboard().getDefaultDictionaryLocale());
        } else {
            Intent voiceInputNotInstalledIntent = new Intent(getApplicationContext(),
                    VoiceInputNotInstalledActivity.class);
            voiceInputNotInstalledIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(voiceInputNotInstalledIntent);
        }
        break;
    case KeyCodes.CANCEL:
        hideWindow();
        break;
    case KeyCodes.SETTINGS:
        showOptionsMenu();
        break;
    case KeyCodes.SPLIT_LAYOUT:
    case KeyCodes.MERGE_LAYOUT:
    case KeyCodes.COMPACT_LAYOUT_TO_RIGHT:
    case KeyCodes.COMPACT_LAYOUT_TO_LEFT:
        if (getInputView() != null) {
            mKeyboardInCondensedMode = CondenseType.fromKeyCode(primaryCode);
            setKeyboardForView(getCurrentKeyboard());
        }
        break;
    case KeyCodes.DOMAIN:
        onText(key, mAskPrefs.getDomainText());
        break;
    case KeyCodes.QUICK_TEXT:
        onQuickTextRequested(key);
        break;
    case KeyCodes.QUICK_TEXT_POPUP:
        onQuickTextKeyboardRequested(key);
        break;
    case KeyCodes.MODE_SYMOBLS:
        nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Symbols);
        break;
    case KeyCodes.MODE_ALPHABET:
        if (getKeyboardSwitcher().shouldPopupForLanguageSwitch()) {
            showLanguageSelectionDialog();
        } else {
            nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Alphabet);
        }
        break;
    case KeyCodes.UTILITY_KEYBOARD:
        getInputView().openUtilityKeyboard();
        break;
    case KeyCodes.MODE_ALPHABET_POPUP:
        showLanguageSelectionDialog();
        break;
    case KeyCodes.ALT:
        nextAlterKeyboard(getCurrentInputEditorInfo());
        break;
    case KeyCodes.KEYBOARD_CYCLE:
        nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Any);
        break;
    case KeyCodes.KEYBOARD_REVERSE_CYCLE:
        nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.PreviousAny);
        break;
    case KeyCodes.KEYBOARD_CYCLE_INSIDE_MODE:
        nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.AnyInsideMode);
        break;
    case KeyCodes.KEYBOARD_MODE_CHANGE:
        nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.OtherMode);
        break;
    case KeyCodes.CLIPBOARD_COPY:
    case KeyCodes.CLIPBOARD_PASTE:
    case KeyCodes.CLIPBOARD_CUT:
    case KeyCodes.CLIPBOARD_SELECT_ALL:
    case KeyCodes.CLIPBOARD_PASTE_POPUP:
    case KeyCodes.CLIPBOARD_SELECT:
        handleClipboardOperation(key, primaryCode, ic);
        //not allowing undo on-text in clipboard paste operations.
        if (primaryCode == KeyCodes.CLIPBOARD_PASTE)
            mCommittedWord = "";
        break;
    default:
        if (BuildConfig.DEBUG) {
            //this should not happen! We should handle ALL function keys.
            throw new RuntimeException("UNHANDLED FUNCTION KEY! primary code " + primaryCode);
        } else {
            Logger.w(TAG, "UNHANDLED FUNCTION KEY! primary code %d. Ignoring.", primaryCode);
        }
    }
}