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:org.distantshoresmedia.keyboard.LatinIME.java

private void doubleSpace() {
    // if (!mAutoPunctuate) return;
    if (mCorrectionMode == Suggest.CORRECTION_NONE)
        return;//from   w w  w  . j  a  v a 2s  .c  om
    final InputConnection ic = getCurrentInputConnection();
    if (ic == null)
        return;
    CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
    if (lastThree != null && lastThree.length() == 3 && Character.isLetterOrDigit(lastThree.charAt(0))
            && lastThree.charAt(1) == ASCII_SPACE && lastThree.charAt(2) == ASCII_SPACE) {
        ic.beginBatchEdit();
        ic.deleteSurroundingText(2, 0);
        ic.commitText(". ", 1);
        ic.endBatchEdit();
        updateShiftKeyState(getCurrentInputEditorInfo());
        mJustAddedAutoSpace = true;
    }
}

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

public void onText(CharSequence text) {
    //mDeadAccentBuffer.clear();  // FIXME
    InputConnection ic = getCurrentInputConnection();
    if (ic == null)
        return;/*  w w  w .  j  a  v  a2  s .  co m*/
    if (mPredicting && text.length() == 1) {
        // If adding a single letter, treat it as a regular keystroke so
        // that completion works as expected.
        int c = text.charAt(0);
        if (!isWordSeparator(c)) {
            int[] codes = { c };
            handleCharacter(c, codes);
            return;
        }
    }
    abortCorrection(false);
    ic.beginBatchEdit();
    if (mPredicting) {
        commitTyped(ic, true);
    }
    maybeRemovePreviousPeriod(text);
    ic.commitText(text, 1);
    ic.endBatchEdit();
    updateShiftKeyState(getCurrentInputEditorInfo());
    mKeyboardSwitcher.onKey(0); // dummy key code.
    mJustRevertedSeparator = null;
    mJustAddedAutoSpace = false;
    mEnteredText = text;
}

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);//ww  w .j a v a2s.  c  o m
        } 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);//from www  .j  a  v a 2 s. co m
        } 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);
        }
    }
}

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

@Override
public boolean onKeyDown(final int keyEventKeyCode, @NonNull KeyEvent event) {
    InputConnection ic = getCurrentInputConnection();
    if (handleSelectionExpending(keyEventKeyCode, ic, mGlobalSelectionStartPosition, mGlobalCursorPosition))
        return true;
    final boolean shouldTranslateSpecialKeys = isInputViewShown();

    //greater than zero means it is a physical keyboard.
    //we also want to hide the view if it's a glyph (for example, not physical volume-up key)
    if (event.getDeviceId() > 0 && event.isPrintingKey())
        onPhysicalKeyboardKeyPressed();//from   ww w .  j  a  va  2s  .c  o  m

    mHardKeyboardAction.initializeAction(event, mMetaState);

    switch (keyEventKeyCode) {
    /****
     * SPECIAL translated HW keys If you add new keys here, do not forget
     * to add to the
     */
    case KeyEvent.KEYCODE_CAMERA:
        if (shouldTranslateSpecialKeys && mAskPrefs.useCameraKeyForBackspaceBackword()) {
            handleBackWord(getCurrentInputConnection());
            return true;
        }
        // DO NOT DELAY CAMERA KEY with unneeded checks in default mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_FOCUS:
        if (shouldTranslateSpecialKeys && mAskPrefs.useCameraKeyForBackspaceBackword()) {
            handleDeleteLastCharacter(false);
            return true;
        }
        // DO NOT DELAY FOCUS KEY with unneeded checks in default mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (shouldTranslateSpecialKeys && mAskPrefs.useVolumeKeyForLeftRight()) {
            sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
            return true;
        }
        // DO NOT DELAY VOLUME UP KEY with unneeded checks in default
        // mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (shouldTranslateSpecialKeys && mAskPrefs.useVolumeKeyForLeftRight()) {
            sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_RIGHT);
            return true;
        }
        // DO NOT DELAY VOLUME DOWN KEY with unneeded checks in default
        // mark
        return super.onKeyDown(keyEventKeyCode, event);
    /****
     * END of SPECIAL translated HW keys code section
     */
    case KeyEvent.KEYCODE_BACK:
        if (event.getRepeatCount() == 0 && getInputView() != null) {
            if (getInputView().handleBack()) {
                // consuming the meta keys
                if (ic != null) {
                    // translated, so we also take care of the metakeys
                    ic.clearMetaKeyStates(Integer.MAX_VALUE);
                }
                mMetaState = 0;
                return true;
            }
        }
        break;
    case 0x000000cc:// API 14: KeyEvent.KEYCODE_LANGUAGE_SWITCH
        switchToNextPhysicalKeyboard(ic);
        return true;
    case KeyEvent.KEYCODE_SHIFT_LEFT:
    case KeyEvent.KEYCODE_SHIFT_RIGHT:
        if (event.isAltPressed() && Workarounds.isAltSpaceLangSwitchNotPossible()) {
            switchToNextPhysicalKeyboard(ic);
            return true;
        }
        // NOTE: letting it fall-through to the other meta-keys
    case KeyEvent.KEYCODE_ALT_LEFT:
    case KeyEvent.KEYCODE_ALT_RIGHT:
    case KeyEvent.KEYCODE_SYM:
        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown before handle"));
        mMetaState = MyMetaKeyKeyListener.handleKeyDown(mMetaState, keyEventKeyCode, event);
        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after handle"));
        break;
    case KeyEvent.KEYCODE_SPACE:
        if ((event.isAltPressed() && !Workarounds.isAltSpaceLangSwitchNotPossible())
                || event.isShiftPressed()) {
            switchToNextPhysicalKeyboard(ic);
            return true;
        }
        // NOTE:
        // letting it fall through to the "default"
    default:

        // Fix issue 185, check if we should process key repeat
        if (!mAskPrefs.getUseRepeatingKeys() && event.getRepeatCount() > 0)
            return true;

        AnyKeyboard.HardKeyboardTranslator keyTranslator = (AnyKeyboard.HardKeyboardTranslator) getCurrentAlphabetKeyboard();
        if (getKeyboardSwitcher().isCurrentKeyboardPhysical() && keyTranslator != null) {
            // sometimes, the physical keyboard will delete input, and then add some.
            // we'll try to make it nice.
            if (ic != null)
                ic.beginBatchEdit();
            try {
                // issue 393, backword on the hw keyboard!
                if (mAskPrefs.useBackword() && keyEventKeyCode == KeyEvent.KEYCODE_DEL
                        && event.isShiftPressed()) {
                    handleBackWord(ic);
                    return true;
                } else {
                    // http://article.gmane.org/gmane.comp.handhelds.openmoko.android-freerunner/629
                    keyTranslator.translatePhysicalCharacter(mHardKeyboardAction, this);

                    if (mHardKeyboardAction.getKeyCodeWasChanged()) {
                        final int translatedChar = mHardKeyboardAction.getKeyCode();
                        // typing my own.
                        onKey(translatedChar, null, -1, new int[] { translatedChar }, true/*faking from UI*/);
                        // my handling we are at a regular key press, so we'll update
                        // our meta-state member
                        mMetaState = MyMetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
                        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after adjust - translated"));
                        return true;
                    }
                }
            } finally {
                if (ic != null)
                    ic.endBatchEdit();
            }
        }
        if (event.isPrintingKey()) {
            // we are at a regular key press, so we'll update our
            // meta-state
            // member
            mMetaState = MyMetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
            Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after adjust"));
        }
    }
    return super.onKeyDown(keyEventKeyCode, event);
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

@Override
public boolean onKeyDown(final int keyEventKeyCode, @NonNull KeyEvent event) {
    InputConnection ic = getCurrentInputConnection();
    if (handleSelectionExpending(keyEventKeyCode, ic, mGlobalSelectionStartPosition, mGlobalCursorPosition))
        return true;
    final boolean shouldTranslateSpecialKeys = isInputViewShown();

    //greater than zero means it is a physical keyboard.
    //we also want to hide the view if it's a glyph (for example, not physical volume-up key)
    if (event.getDeviceId() > 0 && event.isPrintingKey())
        onPhysicalKeyboardKeyPressed();/*www  . j ava 2 s. co  m*/

    mHardKeyboardAction.initializeAction(event, mMetaState);

    switch (keyEventKeyCode) {
    /****
     * SPECIAL translated HW keys If you add new keys here, do not forget
     * to add to the
     */
    case KeyEvent.KEYCODE_CAMERA:
        if (shouldTranslateSpecialKeys && mAskPrefs.useCameraKeyForBackspaceBackword()) {
            handleBackWord(getCurrentInputConnection());
            return true;
        }
        // DO NOT DELAY CAMERA KEY with unneeded checks in default mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_FOCUS:
        if (shouldTranslateSpecialKeys && mAskPrefs.useCameraKeyForBackspaceBackword()) {
            handleDeleteLastCharacter(false);
            return true;
        }
        // DO NOT DELAY FOCUS KEY with unneeded checks in default mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (shouldTranslateSpecialKeys && mAskPrefs.useVolumeKeyForLeftRight()) {
            sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
            return true;
        }
        // DO NOT DELAY VOLUME UP KEY with unneeded checks in default
        // mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (shouldTranslateSpecialKeys && mAskPrefs.useVolumeKeyForLeftRight()) {
            sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_RIGHT);
            return true;
        }
        // DO NOT DELAY VOLUME DOWN KEY with unneeded checks in default
        // mark
        return super.onKeyDown(keyEventKeyCode, event);
    /****
     * END of SPECIAL translated HW keys code section
     */
    case KeyEvent.KEYCODE_BACK:
        if (event.getRepeatCount() == 0 && getInputView() != null) {
            if (getInputView().handleBack()) {
                // consuming the meta keys
                if (ic != null) {
                    // translated, so we also take care of the metakeys
                    ic.clearMetaKeyStates(Integer.MAX_VALUE);
                }
                mMetaState = 0;
                return true;
            }
        }
        break;
    case 0x000000cc:// API 14: KeyEvent.KEYCODE_LANGUAGE_SWITCH
        switchToNextPhysicalKeyboard(ic);
        return true;
    case KeyEvent.KEYCODE_SHIFT_LEFT:
    case KeyEvent.KEYCODE_SHIFT_RIGHT:
        if (event.isAltPressed() && Workarounds.isAltSpaceLangSwitchNotPossible()) {
            switchToNextPhysicalKeyboard(ic);
            return true;
        }
        // NOTE: letting it fall-through to the other meta-keys
    case KeyEvent.KEYCODE_ALT_LEFT:
    case KeyEvent.KEYCODE_ALT_RIGHT:
    case KeyEvent.KEYCODE_SYM:
        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown before handle"));
        mMetaState = MyMetaKeyKeyListener.handleKeyDown(mMetaState, keyEventKeyCode, event);
        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after handle"));
        break;
    case KeyEvent.KEYCODE_SPACE:
        if ((event.isAltPressed() && !Workarounds.isAltSpaceLangSwitchNotPossible())
                || event.isShiftPressed()) {
            switchToNextPhysicalKeyboard(ic);
            return true;
        }
        // NOTE:
        // letting it fall through to the "default"
    default:

        // Fix issue 185, check if we should process key repeat
        if (!mAskPrefs.getUseRepeatingKeys() && event.getRepeatCount() > 0)
            return true;

        HardKeyboardTranslator keyTranslator = (HardKeyboardTranslator) getCurrentAlphabetKeyboard();
        if (getKeyboardSwitcher().isCurrentKeyboardPhysical() && keyTranslator != null) {
            // sometimes, the physical keyboard will delete input, and then add some.
            // we'll try to make it nice.
            if (ic != null)
                ic.beginBatchEdit();
            try {
                // issue 393, backword on the hw keyboard!
                if (mAskPrefs.useBackword() && keyEventKeyCode == KeyEvent.KEYCODE_DEL
                        && event.isShiftPressed()) {
                    handleBackWord(ic);
                    return true;
                } else {
                    // http://article.gmane.org/gmane.comp.handhelds.openmoko.android-freerunner/629
                    keyTranslator.translatePhysicalCharacter(mHardKeyboardAction, this);

                    if (mHardKeyboardAction.getKeyCodeWasChanged()) {
                        final int translatedChar = mHardKeyboardAction.getKeyCode();
                        // typing my own.
                        onKey(translatedChar, null, -1, new int[] { translatedChar }, true/*faking from UI*/);
                        // my handling we are at a regular key press, so we'll update
                        // our meta-state member
                        mMetaState = MyMetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
                        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after adjust - translated"));
                        return true;
                    }
                }
            } finally {
                if (ic != null)
                    ic.endBatchEdit();
            }
        }
        if (event.isPrintingKey()) {
            // we are at a regular key press, so we'll update our
            // meta-state
            // member
            mMetaState = MyMetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
            Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after adjust"));
        }
    }
    return super.onKeyDown(keyEventKeyCode, event);
}