Example usage for android.view.inputmethod ExtractedTextRequest ExtractedTextRequest

List of usage examples for android.view.inputmethod ExtractedTextRequest ExtractedTextRequest

Introduction

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

Prototype

ExtractedTextRequest

Source Link

Usage

From source file:Main.java

private static int getCursorPosition(InputConnection connection) {
    ExtractedText extracted = connection.getExtractedText(new ExtractedTextRequest(), 0);
    if (extracted == null) {
        return -1;
    }/*from  ww w  . j a v  a2 s.c  om*/
    return extracted.startOffset + extracted.selectionStart;
}

From source file:com.googlecode.eyesfree.brailleback.BrailleIME.java

@Override
public void onStartInput(EditorInfo attribute, boolean restarting) {
    super.onStartInput(attribute, restarting);
    LogUtils.log(this, Log.VERBOSE,
            "onStartInput: inputType: %x, imeOption: %x, " + ", label: %s, hint: %s, package: %s, ",
            attribute.inputType, attribute.imeOptions, attribute.label, attribute.hintText,
            attribute.packageName);/*from  ww w. j  a va  2s .  c  o m*/
    InputConnection ic = getCurrentInputConnection();
    if (ic != null) {
        ExtractedTextRequest req = new ExtractedTextRequest();
        req.token = ++mExtractedTextToken;
        req.hintMaxChars = MAX_REQUEST_CHARS;
        mExtractedText = getCurrentInputConnection().getExtractedText(req,
                InputConnection.GET_EXTRACTED_TEXT_MONITOR);
    } else {
        mExtractedText = null;
    }
    updateCurrentText();
    updateDisplay();

    Host host = getHost();
    if (host != null) {
        host.onStartInput(attribute, restarting);
    }
}

From source file:org.kde.kdeconnect.Plugins.RemoteKeyboardPlugin.RemoteKeyboardPlugin.java

private boolean handleSpecialKey(int key, boolean shift, boolean ctrl, boolean alt) {
    int keyEvent = specialKeyMap.get(key, 0);
    if (keyEvent == 0)
        return false;
    InputConnection inputConn = RemoteKeyboardService.instance.getCurrentInputConnection();
    //        Log.d("RemoteKeyboardPlugin", "Handling special key " + key + " translated to " + keyEvent + " shift=" + shift + " ctrl=" + ctrl + " alt=" + alt);

    // special sequences:
    if (ctrl && (keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT)) {
        // Ctrl + right -> next word
        ExtractedText extractedText = inputConn.getExtractedText(new ExtractedTextRequest(), 0);
        int pos = getCharPos(extractedText, ' ', keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT);
        if (pos == -1)
            pos = currentTextLength(extractedText);
        else/* w w w .jav  a 2s. c o m*/
            pos++;
        int startPos = pos;
        int endPos = pos;
        if (shift) { // Shift -> select word (otherwise jump)
            Pair<Integer, Integer> sel = currentSelection(extractedText);
            int cursor = currentCursorPos(extractedText);
            //                Log.d("RemoteKeyboardPlugin", "Selection (to right): " + sel.first + " / " + sel.second + " cursor: " + cursor);
            startPos = cursor;
            if (sel.first < cursor || // active selection from left to right -> grow
                    sel.first > sel.second) // active selection from right to left -> shrink
                startPos = sel.first;
        }
        inputConn.setSelection(startPos, endPos);
    } else if (ctrl && keyEvent == KeyEvent.KEYCODE_DPAD_LEFT) {
        // Ctrl + left -> previous word
        ExtractedText extractedText = inputConn.getExtractedText(new ExtractedTextRequest(), 0);
        int pos = getCharPos(extractedText, ' ', keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT);
        if (pos == -1)
            pos = 0;
        else
            pos++;
        int startPos = pos;
        int endPos = pos;
        if (shift) {
            Pair<Integer, Integer> sel = currentSelection(extractedText);
            int cursor = currentCursorPos(extractedText);
            //                Log.d("RemoteKeyboardPlugin", "Selection (to left): " + sel.first + " / " + sel.second + " cursor: " + cursor);
            startPos = cursor;
            if (cursor < sel.first || // active selection from right to left -> grow
                    sel.first < sel.second) // active selection from right to left -> shrink
                startPos = sel.first;
        }
        inputConn.setSelection(startPos, endPos);
    } else if (shift && (keyEvent == KeyEvent.KEYCODE_DPAD_LEFT || keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT
            || keyEvent == KeyEvent.KEYCODE_DPAD_UP || keyEvent == KeyEvent.KEYCODE_DPAD_DOWN
            || keyEvent == KeyEvent.KEYCODE_MOVE_HOME || keyEvent == KeyEvent.KEYCODE_MOVE_END)) {
        // Shift + up/down/left/right/home/end
        long now = SystemClock.uptimeMillis();
        inputConn.sendKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0));
        inputConn.sendKeyEvent(
                new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keyEvent, 0, KeyEvent.META_SHIFT_LEFT_ON));
        inputConn.sendKeyEvent(
                new KeyEvent(now, now, KeyEvent.ACTION_UP, keyEvent, 0, KeyEvent.META_SHIFT_LEFT_ON));
        inputConn.sendKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0));
    } else if (keyEvent == KeyEvent.KEYCODE_NUMPAD_ENTER || keyEvent == KeyEvent.KEYCODE_ENTER) {
        // Enter key
        EditorInfo editorInfo = RemoteKeyboardService.instance.getCurrentInputEditorInfo();
        //            Log.d("RemoteKeyboardPlugin", "Enter: " + editorInfo.imeOptions);
        if (editorInfo != null
                && (((editorInfo.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) == 0) || ctrl)) { // Ctrl+Return overrides IME_FLAG_NO_ENTER_ACTION (FIXME: make configurable?)
            // check for special DONE/GO/etc actions first:
            int[] actions = { EditorInfo.IME_ACTION_GO, EditorInfo.IME_ACTION_NEXT, EditorInfo.IME_ACTION_SEND,
                    EditorInfo.IME_ACTION_SEARCH, EditorInfo.IME_ACTION_DONE }; // note: DONE should be last or we might hide the ime instead of "go"
            for (int i = 0; i < actions.length; i++) {
                if ((editorInfo.imeOptions & actions[i]) == actions[i]) {
                    //                        Log.d("RemoteKeyboardPlugin", "Enter-action: " + actions[i]);
                    inputConn.performEditorAction(actions[i]);
                    return true;
                }
            }
        } else {
            // else: fall back to regular Enter-event:
            //                Log.d("RemoteKeyboardPlugin", "Enter: normal keypress");
            inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyEvent));
            inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyEvent));
        }
    } else {
        // default handling:
        inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyEvent));
        inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyEvent));
    }

    return true;
}

From source file:com.volosyukivan.WiFiInputMethod.java

String getText() {
    String text = "";
    try {/*w  ww .  j a  v a  2 s  .co  m*/
        InputConnection conn = getCurrentInputConnection();
        ExtractedTextRequest req = new ExtractedTextRequest();
        req.hintMaxChars = 1000000;
        req.hintMaxLines = 10000;
        req.flags = 0;
        req.token = 1;
        text = conn.getExtractedText(req, 0).text.toString();
    } catch (Throwable t) {
    }
    return text;
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * Deal with the editor reporting movement of its cursor.
 *///from  ww  w . j a va2 s .com
@Override
public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd,
        int candidatesStart, int candidatesEnd) {

    // Log.i("onUpdateSelection", "Cursor Moved");
    // If the current selection in the text view changes, we should clear whatever candidate text we have.
    if (mComposing.length() > 0 && (newSelStart != candidatesEnd || newSelEnd != candidatesEnd)) {
        mComposing.setLength(0);
        updateCandidates();
        if (ic != null) {
            ic.finishComposingText();
        }
    }

    ExtractedText alltext = ic.getExtractedText(new ExtractedTextRequest(), 0);

    //special case, there is nothing in the editor (been deleted)
    if (alltext == null)
        return;
    //special case - the text in the editor has all been deleted but the ic is still active
    if (newSelStart == 0 && alltext.text.length() == 0) {
        coreEngine.resetCoreString();
        updateCandidates();
        return;
    }
    try {
        if (newSelEnd - newSelStart == 0 && newSelEnd < alltext.text.length() - 1) //only if cursor movement, not actual selection, and we are not at the end of the text
        {
            //Log.i("Selection Update", "Old: "+oldSelStart+","+oldSelEnd+"...New: "+newSelStart+","+newSelEnd);

            WordDetails w = findWord(newSelStart, alltext.text); //find the current word

            //Log.i("Selection Update", "WordStart, End = "+w.wordStart+","+w.wordEnd);
            if (w.wordStart >= 0 && w.wordEnd >= 0 && w.wordStart < w.wordEnd) {

                w.word = alltext.text.toString().substring(w.wordStart, w.wordEnd);
                //Log.i("Selection Update","\nCurrent Word: ["+w.word+"]");

                //check if current word has been autocorrected
                //Log.i("Selection Update","Original word was "+autocorrected_words.get(w.word));
                replacemode = true;
                //ic.setComposingRegion(w.wordStart, w.wordEnd); //mark this as composing - any key input will erase the word

                if (autocorrected_words.containsKey(w.word)) //a word that was autocorrected or highlighted as a mistake
                {
                    //Log.i("Selection Update","Original word was "+autocorrected_words.get(w.word));
                    updateCandidatesWithSpellChecker(autocorrected_words.get(w.word));
                    //show candidates
                } else //not a mistake word, so just use adaptxt for suggestions
                {
                    //Log.i("Selection Update","Not a mistake Word");
                    coreEngine.resetCoreString();
                    coreEngine.insertText(w.word);
                    updateCandidates();
                }

            }

        } else {
            //Log.i("Selection Update", "Old: "+oldSelStart+","+oldSelEnd+"...New: "+newSelStart+","+newSelEnd);
            replacemode = false;
            if (newSelEnd == alltext.text.length() && newSelEnd - oldSelEnd > 2) {
                //Log.i("Selection Update","At sentence end");
                ic.finishComposingText();
                coreEngine.resetCoreString();
                updateCandidates();

            }
        }
    } catch (Exception e) {
        //Log.i("onUpdateSelection", "Failed to get extracted text");
    }

    super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd);

}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * Helper function to commit any text being composed in the editor
 * @param inputConnection our current connection with the editor
 * @param isWordSeparator /*  w  w  w. jav  a  2s  .  c om*/
 */
private void commitTyped(InputConnection inputConnection, boolean isWordSeparator) {
    if (mComposing.length() > 0) {

        //do some spell-checking
        mComposingTemp = mComposing.toString();
        extr = ic.getExtractedText(new ExtractedTextRequest(), 0);

        WordDetails w = findWord(extr.selectionStart, extr.text);
        if (w.wordStart >= 0 && w.wordEnd >= 0 && w.wordStart < w.wordEnd) {
            w.word = extr.text.toString().substring(w.wordStart, extr.selectionStart);
            System.out.println("Cursor Position = " + extr.selectionStart + " Word=" + w.word);
            if (w != null && mComposingTemp != null) {
                if (w.word.length() != mComposingTemp.length()) {
                    mComposingTemp = w.word;
                    if (captureData)
                        ic.setComposingRegion(w.wordStart, extr.selectionStart);
                }
            }

        }

        if (captureData) // don't want to be spell-checking on urls, emails, passwords
        {
            if (mScs != null) //get some suggestions
            {
                //Log.i("CommitTyped", "About to spellcheck "+mComposingTemp);                 
                mScs.getSuggestions(new TextInfo(mComposingTemp), 5);

            } else //handle spelling for Samsung devices
            {
                //Log.e("CommitTyped", "mScs NULL");
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                String lang = prefs.getString("available_dicts", "el");
                XmlResourceParser p;
                if (lang.equals("en"))
                    p = getResources().getXml(R.xml.qwerty);
                else
                    p = getResources().getXml(R.xml.greekqwerty);

                SpellForSamsung sp = new SpellForSamsung(getAssets(), p,
                        getFilesDir() + File.separator + "data", lang, 5);
                SuggestionsInfo si[] = new SuggestionsInfo[1];
                si[0] = sp.spell(mComposingTemp);
                onGetSuggestions(si);
            }
        } else {
            //Log.i("CommitTyped", "Will not spellcheck in an inappropriate field, mComposing = "+mComposingTemp);
            inputConnection.commitText(mComposingTemp, mComposingTemp.length());
        }

    }
    mComposing.setLength(0);
    updateCandidates();

}

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

private void checkReCorrectionOnStart() {
    if (mReCorrectionEnabled && isPredictionOn()) {
        // First get the cursor position. This is required by
        // setOldSuggestions(), so that
        // it can pass the correct range to setComposingRegion(). At this
        // point, we don't
        // have valid values for mLastSelectionStart/Stop because
        // onUpdateSelection() has
        // not been called yet.
        InputConnection ic = getCurrentInputConnection();
        if (ic == null)
            return;
        ExtractedTextRequest etr = new ExtractedTextRequest();
        etr.token = 0; // anything is fine here
        ExtractedText et = ic.getExtractedText(etr, 0);
        if (et == null)
            return;

        mLastSelectionStart = et.startOffset + et.selectionStart;
        mLastSelectionEnd = et.startOffset + et.selectionEnd;

        // Then look for possible corrections in a delayed fashion
        if (!TextUtils.isEmpty(et.text) && isCursorTouchingWord()) {
            postUpdateOldSuggestions();//from   w  w w .j  a va2  s  . co m
        }
    }
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * Manages actual input into the editor. Here we:
 * implement our injection algorithm as required
 * store data relating to the key press//from  w  w w .j av a 2s. c  o  m
 * initiate any spell checking as required
 */
public void onKey(int primaryCode, int[] keyCodes) {

    // touches all done, add the chars to the event and then the event to the session       
    currentEvent.keyCode = primaryCode;

    if (errorInjection && primaryCode >= 32) {
        //give a n% chance of the key being modified
        Random r = new Random();
        int res = r.nextInt(100);
        if (res <= errorInjectionThreshold) //%n chance of key being modified
        {
            //Log.i("OnKey", "Will modify");
            try {
                //for each combination in the model, find the eucleidian distance and the replacement freq
                JSONObject targetObj = suspectReplacementDistribution
                        .getJSONObject(Integer.toString(primaryCode));
                Iterator<?> keys = targetObj.keys();
                ArrayList<Character> list = new ArrayList();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    int freq = targetObj.getInt(key);
                    //if the frequency is 0, add the suspect as a replacement candidate
                    double dist = keyModel.distance2(primaryCode, Integer.parseInt(key));

                    if (dist > 0) {
                        if (dist > 2.0) //fix it so that only nearby keys have a chance of being elected
                            dist = 100;
                        //add to the list of candidates as many times as required if specific freq>0;
                        int sfreq = (int) Math.round(freq / dist);
                        //Log.i("Test", "Freq/Dist to "+key+": "+freq+"/"+dist+" final prob: "+sfreq);

                        if (sfreq == 0) //add the suspect as a replacement candidate
                        {
                            list.add(Character.toChars(primaryCode)[0]);
                        } else //add the other replacement candidates as required
                        {
                            for (int x = 0; x < targetObj.getInt(key); x++) {
                                list.add(Character.toChars(Integer.parseInt(key))[0]);

                            }
                        }
                    }
                }
                //Log.i("OnKey", "Replace list size: "+list.size());

                Random x = new Random();
                int sel = x.nextInt(list.size());

                //if the replacement eventually happens
                if ((int) list.get(sel) != primaryCode) {

                    if (errorInjectionSound) {
                        final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
                        tg.startTone(ToneGenerator.TONE_CDMA_SOFT_ERROR_LITE);
                    }
                    //primaryCode = (int)list.get(sel);

                    //Log.w("OnKey", "Replace "+Character.toChars(primaryCode)[0]+" with "+list.get(sel));
                    errorMap.put(mComposing.length(), (char) (int) list.get(sel)); //put in our current position and the replacement
                    //nInjections++;      
                } else
                    Log.i("OnKey", "Replacement will not happen, same key selected");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            //Log.i("OnKey", "Will not modify, r="+res);
        }
    }
    //switch adaptxt language if necessary
    if (coreEngine != null) {
        switch (mInputView.currentKeyboard) {
        case KeyboardViews.QWERTY_EL:
            coreEngine.activateLanguageKeymap(131092, null);
            coreEngine.setDictionaryPriority(131092, 0);
            break;
        case KeyboardViews.QWERTY_EN:
            coreEngine.activateLanguageKeymap(131081, null);
            coreEngine.setDictionaryPriority(131092, 1);
            break;
        }
    }

    //get the full inputted text
    extr = ic.getExtractedText(new ExtractedTextRequest(), 0);

    if (currentEvent != null && captureData == true) {

        //Log.i("OnKey", "OK to capture data!");
        currentEvent.user = userid;

        if (primaryCode > 0)
            currentEvent.keyChar = (char) primaryCode;

        //handle the booleans
        if (currentSession.events.get(currentSession.events.size() - 1).keyChar == ' ') //space
        {
            currentEvent.followsSpace = true;
        }

        if (currentEvent.keyCode == Keyboard.KEYCODE_DELETE) {
            System.out.println("Backspace Pressed!");

            //if a delete is pressed after another delete
            //and its cursor position is not -1 from the previous delete
            //we must commit the previous deletion as a suspect character.
            if (currentSession.events.get(currentSession.events.size() - 1).keyCode == Keyboard.KEYCODE_DELETE
                    && extr.selectionStart != lastDeletedPos - 1) {
                currentSession.suspects.add(lastDeleted);
                //System.out.println("Suspect = "+lastDeleted);
            }

            //get all the text before the backspace press and the current cursor position
            if (extr.selectionStart > 0) {
                lastDeleted = extr.text.charAt(extr.selectionStart - 1);
                lastDeletedPos = extr.selectionStart;
                //System.out.println("Deleted = "+lastDeleted+"\nCursor Position = "+extr.selectionStart);
            }
        }

        //if the current key is NOT a backspace but the previous one was
        if (currentEvent.keyCode != Keyboard.KEYCODE_DELETE && currentSession.events
                .get(currentSession.events.size() - 1).keyCode == Keyboard.KEYCODE_DELETE) {
            currentSession.suspects.add(lastDeleted);
            //System.out.println("Suspect = "+lastDeleted);

        }

    }

    //do the handling     
    if (isWordSeparator(primaryCode)) {
        // Handle separator
        //System.out.println("Detected a word separator \""+primaryCode+"\"");
        if (primaryCode != 32) {
            shouldInsertSpace = false;
            if (extr.text.length() > 0) {
                //Log.i("On Key ", "last letter after separator was ["+extr.text.charAt(extr.selectionStart-1)+"]");
                //check if the previous char was a space, if so delete it.
                if (extr.text.charAt(extr.selectionStart - 1) == ' ' && !isSpecialSeparator(primaryCode)) //detecting if the current char is not part of a smiley face
                {
                    onKey(-5, null);
                }
            }
        }

        //clear the touch history
        clearDots();

        //ensure spell checker is using correct language          
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        Editor ed = prefs.edit();
        if (captureData) {
            if (mInputView.currentLang == 1) //english
            {
                ed.putString("available_dicts", "en");
                ed.commit();
                if (mScs != null)
                    mScs.close();
                String lang = prefs.getString("available_dicts", "jam");
                Log.i("OnKey", "Spellcheck lang set to " + lang);
                Locale english = new Locale("en", "GB");
                mScs = tsm.newSpellCheckerSession(null, english, this, false);
                if (mScs == null)
                    Log.e("OnKey", "Failed to obtain spell-checker session");
            } else {
                ed.putString("available_dicts", "el");
                ed.commit();
                if (mScs != null)
                    mScs.close();
                String lang = prefs.getString("available_dicts", "jam");
                Log.i("OnKey", "Spellcheck lang set to " + lang);
                Locale greek = new Locale("el", "GR");
                mScs = tsm.newSpellCheckerSession(null, greek, this, false);
                if (mScs == null)
                    Log.e("OnKey", "Failed to obtain spell-checker session");
            }
        }

        //handle space for Adaptxt
        if (Character.isSpaceChar(primaryCode)) {
            if (coreEngine != null) {
                //Log.i("Handle Character", "Space pressed");
                coreEngine.resetCoreString();
                //Log.i("Space Pressed", "Word is "+mComposing+" ");
                coreEngine.insertText(mComposing.toString() + " ");
                updateCandidates();
            }
        }

        if (!firstWordSet && mComposing.length() > 1) {
            if (captureData)
                currentSession.firstWord = mComposing.toString();
            else
                currentSession.firstWord = "$$$$";

            firstWordSet = true;
            //System.out.println("First Word\""+mComposing.toString()+"\"");
        }

        //effect any injections as required
        if (mComposing.length() > 0) {
            //commitTyped(getCurrentInputConnection());
            //check the errormap for any replacements 
            if (errorMap.size() > 0) {

                //restrict the errormap to the 25% of word length cap

                int replacementstodelete = errorMap.size() - (int) Math.round(mComposing.length() * 0.25); //total replacements - those to keep
                if (replacementstodelete < 0)
                    replacementstodelete = 0;
                //allow at least one
                if (errorMap.size() == replacementstodelete)
                    replacementstodelete = errorMap.size() - 1;

                if (replacementstodelete > 0) {
                    List<Integer> keys = new ArrayList<Integer>(errorMap.keySet());

                    for (int z = 0; z < replacementstodelete; z++) {
                        Random random = new Random();
                        int listposition = random.nextInt(keys.size());
                        int randomKey = keys.get(listposition);
                        //remove this from the error map and the list
                        errorMap.remove(randomKey);
                        keys.remove(listposition);

                    }
                }

                //effect the injections
                String oldmComposing = mComposing.toString();
                Iterator it = errorMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pair = (Map.Entry) it.next();
                    mComposing.replace((Integer) pair.getKey(), (Integer) pair.getKey() + 1,
                            "" + (Character) pair.getValue());
                    //it.remove(); // avoids a ConcurrentModificationException
                }
                nInjections += errorMap.size();
                currentSession.nInjections = nInjections;
                //Log.i("Injections", "Will replace "+oldmComposing+" with "+mComposing+", nInjections="+nInjections);
                errorMap.clear();
            }

            wordSeparatorKeyCode = primaryCode;
            if (captureData)
                commitTyped(ic, isWordSeparator(primaryCode));
            else {
                if (primaryCode != Keyboard.KEYCODE_DONE && primaryCode != 10) //done and go/enter
                    handleCharacter(primaryCode, keyCodes);
                else
                    sendKey(primaryCode);
                commitTyped(ic);
            }
        } else {
            sendKey(primaryCode);
        }

        updateShiftKeyState(getCurrentInputEditorInfo());

    } else if (primaryCode == Keyboard.KEYCODE_DELETE) {
        if (errorMap.get(mComposing.length() - 1) != null) {
            //Log.i("Injection", "Delete from map pos="+(mComposing.length()-1)+", char="+errorMap.get(mComposing.length()-1));
            errorMap.remove(mComposing.length() - 1);
        }

        handleBackspace();
    } else if (primaryCode == Keyboard.KEYCODE_SHIFT) {
        handleShift();
    } else if (primaryCode == Keyboard.KEYCODE_CANCEL) { //keyboard hiding button
        //override this for settings activity
        //handleClose();
        Intent intent = new Intent(this, LoggingIMESettings.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        return;
    } else if (primaryCode == LatinKeyboardView.KEYCODE_OPTIONS) {
        // Show a menu or somethin'
    } else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE && mInputView != null) {
        //Keyboard current = mInputView.getKeyboard();

        if (mInputView.currentKeyboard == KeyboardViews.SYMBOLS
                || mInputView.currentKeyboard == KeyboardViews.SYMBOLS_SHIFTED) {
            //mInputView.currentKeyboard = KeyboardViews.QWERTY_EN;
            mInputView.currentKeyboard = lastKeyboardView;
        } else { //about to change to symbols
            lastKeyboardView = mInputView.currentKeyboard; //keep track of where we came from
            mInputView.currentKeyboard = KeyboardViews.SYMBOLS;
        }
        mInputView.switchKeyboard();
        if (mInputView.currentKeyboard == KeyboardViews.SYMBOLS) {
            mInputView.getKeyboard().setShifted(false);
        }
    } else {
        handleCharacter(primaryCode, keyCodes);
    }
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * Handles the manual selection of suggestions from the suggestion bar
 * @param index the position of the suggestion in the suggestion list
 *//*www  .  java2s.  c  o m*/
public void pickSuggestionManually(int index) {
    if (mCompletionOn && mCompletions != null && index >= 0 && index < mCompletions.length) {
        CompletionInfo ci = mCompletions[index];
        ic.commitCompletion(ci);
        if (mCandidateView != null) {
            mCandidateView.clear();
        }
        updateShiftKeyState(getCurrentInputEditorInfo());
    } else if (mComposing.length() >= 0) {

        String picked;
        if (!replacemode)
            picked = suggestions.get(index) + " ";
        else
            picked = suggestions.get(index);

        //Log.i("Suggestion picked 2", picked);

        //ic.commitText(picked, picked.length());

        getCurrentInputEditorInfo();

        //colour the text according to user preferences
        SpannableString text = new SpannableString(picked);
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        if (sharedPrefs.getBoolean("suggestion_highlight", false))
            text.setSpan(new BackgroundColorSpan(suggestion), 0, picked.length() - 1,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        currentSession.nSuggestionsPicked++;

        if (replacemode) {
            replacemode = false;
            //remove from list of autocorrected words.
            //Log.i("PickSuggestion", "Removed "+autocorrected_words.remove(text.toString()));

            //find the current word
            extr = ic.getExtractedText(new ExtractedTextRequest(), 0);
            WordDetails w = findWord(extr.selectionStart, extr.text);
            //Log.i("FindWord", w.word+", "+w.wordStart+" - "+w.wordEnd);
            ic.setComposingRegion(w.wordStart, w.wordEnd);
            text.setSpan(null, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            /*
            //clear any spans       
            BackgroundColorSpan[] spans=(new SpannableString(extr.text.toString())).getSpans(w.wordStart, w.wordEnd, BackgroundColorSpan.class);
            for(int i=0; i<spans.length; i++){
              text.removeSpan(spans[i]);
            }*/

            //commit the update
            ic.commitText(text, 1);

        } else
            ic.commitText(text, picked.length());

        coreEngine.resetCoreString();
        coreEngine.insertText(picked);
        mComposing.setLength(0);
        updateCandidates();
    }
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * handle keyboard orientation being changed
 *///from w  ww .  j  a v a  2s .c  o m
@Override
public void onConfigurationChanged(Configuration newConfig) {
    /*
    Log.i("Configuration Changed", "Now in mode: "+newConfig.orientation);
    Log.i("Configuration Changed", "FullScreen mode: "+isFullscreenMode());
    Log.i("Configuration Changed", "ExtractView shown: "+isExtractViewShown());
    */
    //get what's input so far
    try {
        ExtractedTextRequest req = new ExtractedTextRequest();
        req.token = 0;
        req.flags = InputConnection.GET_TEXT_WITH_STYLES;
        extractedText = ic.getExtractedText(req, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
    super.onConfigurationChanged(newConfig);

}