InputLogic.java revision ebc150903951d641b2c7291bb4e834a737eb39fc
168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)/* 268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * Copyright (C) 2013 The Android Open Source Project 368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * 468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * Licensed under the Apache License, Version 2.0 (the "License"); 568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * you may not use this file except in compliance with the License. 668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * You may obtain a copy of the License at 768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * 868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * http://www.apache.org/licenses/LICENSE-2.0 968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * 1068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * Unless required by applicable law or agreed to in writing, software 1168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * distributed under the License is distributed on an "AS IS" BASIS, 1268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * See the License for the specific language governing permissions and 1468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * limitations under the License. 1568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) */ 1668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 1768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)package com.android.inputmethod.latin.inputlogic; 1868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 1968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)import android.graphics.Color; 204e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import android.os.SystemClock; 2168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)import android.text.SpannableString; 2268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)import android.text.TextUtils; 2368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)import android.text.style.SuggestionSpan; 2468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)import android.util.Log; 2568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)import android.view.KeyCharacterMap; 2668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)import android.view.KeyEvent; 2768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)import android.view.inputmethod.CorrectionInfo; 2868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)import android.view.inputmethod.EditorInfo; 2968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 304e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.compat.SuggestionSpanUtils; 314e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.event.Event; 324e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.event.InputTransaction; 334e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.keyboard.KeyboardSwitcher; 344e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.keyboard.ProximityInfo; 354e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.Constants; 364e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.Dictionary; 374e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.DictionaryFacilitator; 384e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.InputPointers; 394e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.LastComposedWord; 404e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.LatinIME; 414e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.PrevWordsInfo; 424e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.RichInputConnection; 434e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.Suggest; 444e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.Suggest.OnGetSuggestedWordsCallback; 454e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.SuggestedWords; 464e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; 474e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.WordComposer; 484e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.define.DebugFlags; 494e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.settings.SettingsValues; 504e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.settings.SettingsValuesForSuggestion; 514e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.settings.SpacingAndPunctuations; 524e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.suggestions.SuggestionStripViewAccessor; 534e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.utils.AsyncResultHolder; 544e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.utils.InputTypeUtils; 554e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.utils.RecapitalizeStatus; 564e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.utils.StringUtils; 574e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import com.android.inputmethod.latin.utils.TextRange; 584e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 594e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import java.util.ArrayList; 604e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import java.util.TreeSet; 614e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)import java.util.concurrent.TimeUnit; 624e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 634e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)/** 641e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) * This class manages the input logic. 651e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) */ 661e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)public final class InputLogic { 671e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) private static final String TAG = InputLogic.class.getSimpleName(); 685c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu 694e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // TODO : Remove this member when we can. 704e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) private final LatinIME mLatinIME; 714e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) private final SuggestionStripViewAccessor mSuggestionStripViewAccessor; 7268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 7368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Never null. 7468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) private InputLogicHandler mInputLogicHandler = InputLogicHandler.NULL_HANDLER; 7568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 7668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // TODO : make all these fields private as soon as possible. 7768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Current space state of the input method. This can be any of the above constants. 7868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) private int mSpaceState; 794e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // Never null 8068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public SuggestedWords mSuggestedWords = SuggestedWords.EMPTY; 8168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public final Suggest mSuggest; 8268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) private final DictionaryFacilitator mDictionaryFacilitator; 834e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 8468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public LastComposedWord mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 8568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // This has package visibility so it can be accessed from InputLogicHandler. 8668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) /* package */ final WordComposer mWordComposer; 8768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public final RichInputConnection mConnection; 884e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) private final RecapitalizeStatus mRecapitalizeStatus = new RecapitalizeStatus(); 894e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 904e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) private int mDeleteCount; 914e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) private long mLastKeyTime; 924e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) public final TreeSet<Long> mCurrentlyPressedHardwareKeys = new TreeSet<>(); 934e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 944e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // Keeps track of most recently inserted text (multi-character key) for reverting 9568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) private String mEnteredText; 961e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) 971e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) // TODO: This boolean is persistent state and causes large side effects at unexpected times. 9868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Find a way to remove it for readability. 991e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) private boolean mIsAutoCorrectionIndicatorOn; 1001e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) private long mDoubleSpacePeriodCountdownStart; 1011e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) 10268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) /** 1031e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) * Create a new instance of the input logic. 1041e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) * @param latinIME the instance of the parent LatinIME. We should remove this when we can. 1051e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) * @param suggestionStripViewAccessor an object to access the suggestion strip view. 1060f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) * @param dictionaryFacilitator facilitator for getting suggestions and updating user history 1071e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) * dictionary. 1081e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) */ 1091e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) public InputLogic(final LatinIME latinIME, 1104e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final SuggestionStripViewAccessor suggestionStripViewAccessor, 1111e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) final DictionaryFacilitator dictionaryFacilitator) { 1121e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) mLatinIME = latinIME; 1131e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) mSuggestionStripViewAccessor = suggestionStripViewAccessor; 1141e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) mWordComposer = new WordComposer(); 1151e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) mConnection = new RichInputConnection(latinIME); 1165c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu mInputLogicHandler = InputLogicHandler.NULL_HANDLER; 1175c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu mSuggest = new Suggest(dictionaryFacilitator); 1185c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu mDictionaryFacilitator = dictionaryFacilitator; 1195c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu } 1201e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) 1211e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) /** 1221e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) * Initializes the input logic for input in an editor. 1230f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) * 1241e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) * Call this when input starts or restarts in some editor (typically, in onStartInputView). 1250f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) * 1264e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param combiningSpec the combining spec string for this subtype 1274e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) */ 1284e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) public void startInput(final String combiningSpec) { 1294e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mEnteredText = null; 1301e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) mWordComposer.restartCombining(combiningSpec); 1311e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) resetComposingState(true /* alsoResetLastComposedWord */); 1324e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mDeleteCount = 0; 1334e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mSpaceState = SpaceState.NONE; 13468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mRecapitalizeStatus.disable(); // Do not perform recapitalize until the cursor is moved once 1354e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mCurrentlyPressedHardwareKeys.clear(); 1364e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mSuggestedWords = SuggestedWords.EMPTY; 13768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // In some cases (namely, after rotation of the device) editorInfo.initialSelStart is lying 13868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // so we try using some heuristics to find out about these and fix them. 1394e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.tryFixLyingCursorPosition(); 1404e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) cancelDoubleSpacePeriodCountdown(); 1414e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (InputLogicHandler.NULL_HANDLER == mInputLogicHandler) { 14268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mInputLogicHandler = new InputLogicHandler(mLatinIME, this); 1434e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } else { 1444e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mInputLogicHandler.reset(); 1454e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 14668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 14768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 14868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) /** 14968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * Call this when the subtype changes. 1504e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param combiningSpec the spec string for the combining rules 1514e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) */ 1524e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) public void onSubtypeChanged(final String combiningSpec) { 1534e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) finishInput(); 15468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) startInput(combiningSpec); 15568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 15668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 15768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) /** 1584e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * Call this when the orientation changes. 1594e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param settingsValues the current values of the settings. 1604e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) */ 1614e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) public void onOrientationChange(final SettingsValues settingsValues) { 1624e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // If !isComposingWord, #commitTyped() is a no-op, but still, it's better to avoid 1634e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // the useless IPC of {begin,end}BatchEdit. 1640f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) if (mWordComposer.isComposingWord()) { 1654e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.beginBatchEdit(); 1664e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // If we had a composition in progress, we need to commit the word so that the 1674e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // suggestionsSpan will be added. This will allow resuming on the same suggestions 1681e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) // after rotation is finished. 1691e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) commitTyped(settingsValues, LastComposedWord.NOT_A_SEPARATOR); 17068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mConnection.endBatchEdit(); 1714e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 1724e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 17368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 1748bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles) /** 1754e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * Clean up the input logic after input is finished. 1764e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) */ 1774e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) public void finishInput() { 17868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) if (mWordComposer.isComposingWord()) { 1794e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.finishComposingText(); 1804e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 1814e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) resetComposingState(true /* alsoResetLastComposedWord */); 1824e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mInputLogicHandler.reset(); 18368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 18468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 18568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Normally this class just gets out of scope after the process ends, but in unit tests, we 18668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // create several instances of LatinIME in the same process, which results in several 18768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // instances of InputLogic. This cleans up the associated handler so that tests don't leak 18868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // handlers. 18968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public void recycle() { 19068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final InputLogicHandler inputLogicHandler = mInputLogicHandler; 19168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mInputLogicHandler = InputLogicHandler.NULL_HANDLER; 1920f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) inputLogicHandler.destroy(); 1934e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mDictionaryFacilitator.closeDictionaries(); 1944e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 1954e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 1964e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) /** 1974e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * React to a string input. 1981e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) * 1991e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) * This is triggered by keys that input many characters at once, like the ".com" key or 2004e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * some additional keys for example. 2014e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * 2024e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param settingsValues the current values of the settings. 2034e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param event the input event containing the data. 2044e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @return the complete transaction object 2054e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) */ 2064e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) public InputTransaction onTextInput(final SettingsValues settingsValues, final Event event, 2074e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final int keyboardShiftMode, 2084e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // TODO: remove this argument 2094e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final LatinIME.UIHandler handler) { 2104e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final String rawText = event.getTextToCommit().toString(); 2114e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final InputTransaction inputTransaction = new InputTransaction(settingsValues, event, 2124e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) SystemClock.uptimeMillis(), mSpaceState, 2134e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) getActualCapsMode(settingsValues, keyboardShiftMode)); 2144e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.beginBatchEdit(); 2154e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (mWordComposer.isComposingWord()) { 2164e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) commitCurrentAutoCorrection(settingsValues, rawText, handler); 2174e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } else { 2184e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) resetComposingState(true /* alsoResetLastComposedWord */); 2194e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 2204e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) handler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_TYPING); 22168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final String text = performSpecificTldProcessingOnTextInput(rawText); 2221e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) if (SpaceState.PHANTOM == mSpaceState) { 2231e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) promotePhantomSpace(settingsValues); 22468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 22568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mConnection.commitText(text, 1); 22668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mConnection.endBatchEdit(); 22768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Space state must be updated before calling updateShiftState 22868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mSpaceState = SpaceState.NONE; 22968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mEnteredText = text; 23068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) inputTransaction.setDidAffectContents(); 2314e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 2324e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) return inputTransaction; 2334e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 2344e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 2354e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) /** 2364e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * Determines whether "Touch again to save" should be shown or not. 2374e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param suggestionInfo the suggested word chosen by the user. 2384e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @return {@code true} if we should show the "Touch again to save" hint. 2394e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) */ 24068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) private boolean shouldShowAddToDictionaryHint(final SuggestedWordInfo suggestionInfo) { 2410f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) // We should show the "Touch again to save" hint if the user pressed the first entry 2420f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) // AND it's in none of our current dictionaries (main, user or otherwise). 2434e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) return (suggestionInfo.isKindOf(SuggestedWordInfo.KIND_TYPED) 24468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) || suggestionInfo.isKindOf(SuggestedWordInfo.KIND_OOV_CORRECTION)) 24568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) && !mDictionaryFacilitator.isValidWord(suggestionInfo.mWord, true /* ignoreCase */) 24668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) && mDictionaryFacilitator.isUserDictionaryEnabled(); 24768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 24868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 2494e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) /** 2504e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * A suggestion was picked from the suggestion strip. 2514e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param settingsValues the current values of the settings. 2524e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param suggestionInfo the suggestion info. 2534e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param keyboardShiftState the shift state of the keyboard, as returned by 2544e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * {@link com.android.inputmethod.keyboard.KeyboardSwitcher#getKeyboardShiftMode()} 25568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * @return the complete transaction object 25668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) */ 25768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener} 25868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // interface 2595d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) public InputTransaction onPickSuggestionManually(final SettingsValues settingsValues, 26068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final SuggestedWordInfo suggestionInfo, final int keyboardShiftState, 26168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // TODO: remove these arguments 26268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final int currentKeyboardScriptId, final LatinIME.UIHandler handler) { 26368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final SuggestedWords suggestedWords = mSuggestedWords; 26468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final String suggestion = suggestionInfo.mWord; 26568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // If this is a punctuation picked from the suggestion strip, pass it to onCodeInput 26668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) if (suggestion.length() == 1 && suggestedWords.isPunctuationSuggestions()) { 26768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Word separators are suggested before the user inputs something. 26868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Rely on onCodeInput to do the complicated swapping/stripping logic consistently. 26968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final Event event = Event.createPunctuationSuggestionPickedEvent(suggestionInfo); 27068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) return onCodeInput(settingsValues, event, keyboardShiftState, 27168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) currentKeyboardScriptId, handler); 2724e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 2734e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 2744e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final Event event = Event.createSuggestionPickedEvent(suggestionInfo); 2754e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final InputTransaction inputTransaction = new InputTransaction(settingsValues, 2764e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) event, SystemClock.uptimeMillis(), mSpaceState, keyboardShiftState); 2774e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // Manual pick affects the contents of the editor, so we take note of this. It's important 2785c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu // for the sequence of language switching. 2795c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu inputTransaction.setDidAffectContents(); 2804e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.beginBatchEdit(); 2814e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (SpaceState.PHANTOM == mSpaceState && suggestion.length() > 0 28268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // In the batch input mode, a manually picked suggested word should just replace 28368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // the current batch input text and there is no need for a phantom space. 2844e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) && !mWordComposer.isBatchMode()) { 2854e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final int firstChar = Character.codePointAt(suggestion, 0); 2864e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (!settingsValues.isWordSeparator(firstChar) 2874e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) || settingsValues.isUsuallyPrecededBySpace(firstChar)) { 2881e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) promotePhantomSpace(settingsValues); 2891e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) } 2904e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 2914e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 2920f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) // TODO: We should not need the following branch. We should be able to take the same 2934e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // code path as for other kinds, use commitChosenWord, and do everything normally. We will 2944e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // however need to reset the suggestion strip right away, because we know we can't take 2954e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // the risk of calling commitCompletion twice because we don't know how the app will react. 2964e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (suggestionInfo.isKindOf(SuggestedWordInfo.KIND_APP_DEFINED)) { 2974e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mSuggestedWords = SuggestedWords.EMPTY; 2984e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 2994e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 3004e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) resetComposingState(true /* alsoResetLastComposedWord */); 3014e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.commitCompletion(suggestionInfo.mApplicationSpecifiedCompletionInfo); 3024e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.endBatchEdit(); 3034e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) return inputTransaction; 3044e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 3054e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 3064e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) commitChosenWord(settingsValues, suggestion, 3074e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) LastComposedWord.COMMIT_TYPE_MANUAL_PICK, LastComposedWord.NOT_A_SEPARATOR); 3084e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.endBatchEdit(); 3094e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // Don't allow cancellation of manual pick 3104e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mLastComposedWord.deactivate(); 3111e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) // Space state must be updated before calling updateShiftState 3121e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) mSpaceState = SpaceState.PHANTOM; 3131e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 3144e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 3154e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (shouldShowAddToDictionaryHint(suggestionInfo)) { 3164e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mSuggestionStripViewAccessor.showAddToDictionaryHint(suggestion); 3174e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } else { 31868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // If we're not showing the "Touch again to save", then update the suggestion strip. 31968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // That's going to be predictions (or punctuation suggestions), so INPUT_STYLE_NONE. 32068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) handler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_NONE); 32168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 3224e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) return inputTransaction; 3234e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 32468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 3254e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) /** 3264e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * Consider an update to the cursor position. Evaluate whether this update has happened as 3274e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * part of normal typing or whether it was an explicit cursor move by the user. In any case, 3284e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * do the necessary adjustments. 3294e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param oldSelStart old selection start 33068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * @param oldSelEnd old selection end 33168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * @param newSelStart new selection start 33268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * @param newSelEnd new selection end 33368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * @return whether the cursor has moved as a result of user interaction. 33468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) */ 33568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public boolean onUpdateSelection(final int oldSelStart, final int oldSelEnd, 33668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final int newSelStart, final int newSelEnd) { 33768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) if (mConnection.isBelatedExpectedUpdate(oldSelStart, newSelStart, oldSelEnd, newSelEnd)) { 33868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) return false; 33968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 3404e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // TODO: the following is probably better done in resetEntireInputState(). 3414e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // it should only happen when the cursor moved, and the very purpose of the 34268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // test below is to narrow down whether this happened or not. Likewise with 3434e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // the call to updateShiftState. 3444e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // We set this to NONE because after a cursor move, we don't want the space 3454e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // state-related special processing to kick in. 3464e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mSpaceState = SpaceState.NONE; 3474e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 3484e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final boolean selectionChangedOrSafeToReset = 34968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) oldSelStart != newSelStart || oldSelEnd != newSelEnd // selection changed 35068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) || !mWordComposer.isComposingWord(); // safe to reset 35168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final boolean hasOrHadSelection = (oldSelStart != oldSelEnd || newSelStart != newSelEnd); 3524e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final int moveAmount = newSelStart - oldSelStart; 35368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // As an added small gift from the framework, it happens upon rotation when there 3544e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // is a selection that we get a wrong cursor position delivered to startInput() that 35568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // does not get reflected in the oldSel{Start,End} parameters to the next call to 3564e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // onUpdateSelection. In this case, we may have set a composition, and when we're here 3574e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // we realize we shouldn't have. In theory, in this case, selectionChangedOrSafeToReset 35868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // should be true, but that is if the framework had taken that wrong cursor position 35968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // into account, which means we have to reset the entire composing state whenever there 36068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // is or was a selection regardless of whether it changed or not. 36168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) if (hasOrHadSelection || (selectionChangedOrSafeToReset 36268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) && !mWordComposer.moveCursorByAndReturnIfInsideComposingWord(moveAmount))) { 3634e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // If we are composing a word and moving the cursor, we would want to set a 3644e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // suggestion span for recorrection to work correctly. Unfortunately, that 3654e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // would involve the keyboard committing some new text, which would move the 36668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // cursor back to where it was. Latin IME could then fix the position of the cursor 36768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // again, but the asynchronous nature of the calls results in this wreaking havoc 36868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // with selection on double tap and the like. 36968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Another option would be to send suggestions each time we set the composing 3704e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // text, but that is probably too expensive to do, so we decided to leave things 3714e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // as is. 3724e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // Also, we're posting a resume suggestions message, and this will update the 3734e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // suggestions strip in a few milliseconds, so if we cleared the suggestion strip here 37468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // we'd have the suggestion strip noticeably janky. To avoid that, we don't clear 37568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // it here, which means we'll keep outdated suggestions for a split second but the 3764e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // visual result is better. 3774e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) resetEntireInputState(newSelStart, newSelEnd, false /* clearSuggestionStrip */); 3784e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } else { 3794e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // resetEntireInputState calls resetCachesUponCursorMove, but forcing the 3804e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // composition to end. But in all cases where we don't reset the entire input 3814e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // state, we still want to tell the rich input connection about the new cursor 3824e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // position so that it can update its caches. 38368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mConnection.resetCachesUponCursorMoveAndReturnSuccess( 38468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) newSelStart, newSelEnd, false /* shouldFinishComposition */); 38568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 3860f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) 38768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // The cursor has been moved : we now accept to perform recapitalization 38868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mRecapitalizeStatus.enable(); 38968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // We moved the cursor. If we are touching a word, we need to resume suggestion. 39068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mLatinIME.mHandler.postResumeSuggestions(false /* shouldIncludeResumedWordInSuggestions */, 39168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) true /* shouldDelay */); 39268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Stop the last recapitalization, if started. 39368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mRecapitalizeStatus.stop(); 39468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) return true; 39568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 3961e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) 39768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) /** 39868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * React to a code input. It may be a code point to insert, or a symbolic value that influences 39968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * the keyboard behavior. 4004e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * 4014e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * Typically, this is called whenever a key is pressed on the software keyboard. This is not 4024e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * the entry point for gesture input; see the onBatchInput* family of functions for this. 4034e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * 4044e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * @param settingsValues the current settings values. 40568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * @param event the event to handle. 40668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * @param keyboardShiftMode the current shift mode of the keyboard, as returned by 40768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * {@link com.android.inputmethod.keyboard.KeyboardSwitcher#getKeyboardShiftMode()} 40868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * @return the complete transaction object 40968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) */ 41068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public InputTransaction onCodeInput(final SettingsValues settingsValues, final Event event, 4114e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final int keyboardShiftMode, 4124e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // TODO: remove these arguments 4134e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final int currentKeyboardScriptId, final LatinIME.UIHandler handler) { 4144e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final Event processedEvent = mWordComposer.processEvent(event); 4154e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final InputTransaction inputTransaction = new InputTransaction(settingsValues, 4164e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) processedEvent, SystemClock.uptimeMillis(), mSpaceState, 4174e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) getActualCapsMode(settingsValues, keyboardShiftMode)); 4184e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (processedEvent.mKeyCode != Constants.CODE_DELETE 4194e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) || inputTransaction.mTimestamp > mLastKeyTime + Constants.LONG_PRESS_MILLISECONDS) { 4204e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mDeleteCount = 0; 4214e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 4224e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mLastKeyTime = inputTransaction.mTimestamp; 4234e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.beginBatchEdit(); 4244e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (!mWordComposer.isComposingWord()) { 4254e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // TODO: is this useful? It doesn't look like it should be done here, but rather after 4264e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // a word is committed. 4274e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mIsAutoCorrectionIndicatorOn = false; 4284e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 4294e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 4304e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // TODO: Consolidate the double-space period timer, mLastKeyTime, and the space state. 4314e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (processedEvent.mCodePoint != Constants.CODE_SPACE) { 4324e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) cancelDoubleSpacePeriodCountdown(); 4334e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 4344e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 4354e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) Event currentEvent = processedEvent; 4364e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) while (null != currentEvent) { 43768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) if (currentEvent.isConsumed()) { 43868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) handleConsumedEvent(currentEvent, inputTransaction); 43968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } else if (currentEvent.isFunctionalKeyEvent()) { 44068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) handleFunctionalEvent(currentEvent, inputTransaction, currentKeyboardScriptId, 4414e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) handler); 4424e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } else { 4434e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) handleNonFunctionalEvent(currentEvent, inputTransaction, handler); 44468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 44568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) currentEvent = currentEvent.mNextEvent; 44668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 44768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) if (!inputTransaction.didAutoCorrect() && processedEvent.mKeyCode != Constants.CODE_SHIFT 4484e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) && processedEvent.mKeyCode != Constants.CODE_CAPSLOCK 4494e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) && processedEvent.mKeyCode != Constants.CODE_SWITCH_ALPHA_SYMBOL) 4504e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mLastComposedWord.deactivate(); 4514e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (Constants.CODE_DELETE != processedEvent.mKeyCode) { 4524e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mEnteredText = null; 4534e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 4544e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.endBatchEdit(); 45568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) return inputTransaction; 45668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 45768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 45868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public void onStartBatchInput(final SettingsValues settingsValues, 45968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // TODO: remove these arguments 4600f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) final KeyboardSwitcher keyboardSwitcher, final LatinIME.UIHandler handler) { 46168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mInputLogicHandler.onStartBatchInput(); 46268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) handler.showGesturePreviewAndSuggestionStrip( 4634e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) SuggestedWords.EMPTY, false /* dismissGestureFloatingPreviewText */); 46468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) handler.cancelUpdateSuggestionStrip(); 4654e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) ++mAutoCommitSequenceNumber; 4664e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.beginBatchEdit(); 46768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) if (mWordComposer.isComposingWord()) { 4680f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 4690f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) // If we are in the middle of a recorrection, we need to commit the recorrection 4700f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) // first so that we can insert the batch input at the current cursor position. 4714e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) resetEntireInputState(mConnection.getExpectedSelectionStart(), 4720f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 4730f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) } else if (mWordComposer.isSingleLetter()) { 4744e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // We auto-correct the previous (typed, not gestured) string iff it's one character 47568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // long. The reason for this is, even in the middle of gesture typing, you'll still 47668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // tap one-letter words and you want them auto-corrected (typically, "i" in English 47768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // should become "I"). However for any longer word, we assume that the reason for 4784e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // tapping probably is that the word you intend to type is not in the dictionary, 4794e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // so we do not attempt to correct, on the assumption that if that was a dictionary 48068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // word, the user would probably have gestured instead. 4814e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) commitCurrentAutoCorrection(settingsValues, LastComposedWord.NOT_A_SEPARATOR, 4824e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) handler); 48368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } else { 48468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) commitTyped(settingsValues, LastComposedWord.NOT_A_SEPARATOR); 4854e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 48668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 4874e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 4884e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (Character.isLetterOrDigit(codePointBeforeCursor) 4894e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) || settingsValues.isUsuallyFollowedBySpace(codePointBeforeCursor)) { 4904e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final boolean autoShiftHasBeenOverriden = keyboardSwitcher.getKeyboardShiftMode() != 4914e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) getCurrentAutoCapsState(settingsValues); 49268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mSpaceState = SpaceState.PHANTOM; 49368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) if (!autoShiftHasBeenOverriden) { 49468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // When we change the space state, we need to update the shift state of the 49568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // keyboard unless it has been overridden manually. This is happening for example 4964e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // after typing some letters and a period, then gesturing; the keyboard is not in 4974e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // caps mode yet, but since a gesture is starting, it should go in caps mode, 4984e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // unless the user explictly said it should not. 4994e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) keyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(settingsValues), 5004e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) getCurrentRecapitalizeState()); 50168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 50268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 50368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mConnection.endBatchEdit(); 5044e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mWordComposer.setCapitalizedModeAtStartComposingTime( 50568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) getActualCapsMode(settingsValues, keyboardSwitcher.getKeyboardShiftMode())); 5064e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 5074e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 5084e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) /* The sequence number member is only used in onUpdateBatchInput. It is increased each time 5094e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * auto-commit happens. The reason we need this is, when auto-commit happens we trim the 5104e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * input pointers that are held in a singleton, and to know how much to trim we rely on the 5114e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * results of the suggestion process that is held in mSuggestedWords. 5124e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) * However, the suggestion process is asynchronous, and sometimes we may enter the 51368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) * onUpdateBatchInput method twice without having recomputed suggestions yet, or having 5140f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) * received new suggestions generated from not-yet-trimmed input pointers. In this case, the 5150f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) * mIndexOfTouchPointOfSecondWords member will be out of date, and we must not use it lest we 5160f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) * remove an unrelated number of pointers (possibly even more than are left in the input 5170f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) * pointers, leading to a crash). 5180f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) * To avoid that, we increase the sequence number each time we auto-commit and trim the 5190f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) * input pointers, and we do not use any suggested words that have been generated with an 5200f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) * earlier sequence number. 52168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) */ 52268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) private int mAutoCommitSequenceNumber = 1; 52368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public void onUpdateBatchInput(final SettingsValues settingsValues, 52468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final InputPointers batchPointers, 52568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // TODO: remove these arguments 52668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) final KeyboardSwitcher keyboardSwitcher) { 5274e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (settingsValues.mPhraseGestureEnabled) { 5284e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final SuggestedWordInfo candidate = mSuggestedWords.getAutoCommitCandidate(); 5294e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // If these suggested words have been generated with out of date input pointers, then 5304e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // we skip auto-commit (see comments above on the mSequenceNumber member). 5314e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (null != candidate 5324e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) && mSuggestedWords.mSequenceNumber >= mAutoCommitSequenceNumber) { 5334e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (candidate.mSourceDict.shouldAutoCommit(candidate)) { 5344e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final String[] commitParts = candidate.mWord.split(Constants.WORD_SEPARATOR, 2); 5354e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) batchPointers.shift(candidate.mIndexOfTouchPointOfSecondWord); 5364e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) promotePhantomSpace(settingsValues); 5374e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mConnection.commitText(commitParts[0], 0); 5384e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) mSpaceState = SpaceState.PHANTOM; 5394e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) keyboardSwitcher.requestUpdatingShiftState( 54068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) getCurrentAutoCapsState(settingsValues), getCurrentRecapitalizeState()); 54168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode( 54268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) settingsValues, keyboardSwitcher.getKeyboardShiftMode())); 54368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) ++mAutoCommitSequenceNumber; 54468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 5454e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 54668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 54768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mInputLogicHandler.onUpdateBatchInput(batchPointers, mAutoCommitSequenceNumber); 54868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 54968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 55068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public void onEndBatchInput(final InputPointers batchPointers) { 55168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mInputLogicHandler.updateTailBatchInput(batchPointers, mAutoCommitSequenceNumber); 55268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) ++mAutoCommitSequenceNumber; 55368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 55468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 55568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // TODO: remove this argument 55668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public void onCancelBatchInput(final LatinIME.UIHandler handler) { 55768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) mInputLogicHandler.onCancelBatchInput(); 55868043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) handler.showGesturePreviewAndSuggestionStrip( 55968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) SuggestedWords.EMPTY, true /* dismissGestureFloatingPreviewText */); 56068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) } 56168043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) 56268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // TODO: on the long term, this method should become private, but it will be difficult. 56368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) // Especially, how do we deal with InputMethodService.onDisplayCompletions? 56468043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) public void setSuggestedWords(final SuggestedWords suggestedWords) { 56568043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles) if (SuggestedWords.EMPTY != suggestedWords) { 5664e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) final String autoCorrection; 5674e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (suggestedWords.mWillAutoCorrect) { 5684e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) autoCorrection = suggestedWords.getWord(SuggestedWords.INDEX_OF_AUTO_CORRECTION); 5694e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } else { 5704e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // We can't use suggestedWords.getWord(SuggestedWords.INDEX_OF_TYPED_WORD) 5714e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // because it may differ from mWordComposer.mTypedWord. 5724e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) autoCorrection = suggestedWords.mTypedWord; 5730f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) } 5740f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) mWordComposer.setAutoCorrection(autoCorrection); 5750f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) } 5760f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles) mSuggestedWords = suggestedWords; 577 final boolean newAutoCorrectionIndicator = suggestedWords.mWillAutoCorrect; 578 // Put a blue underline to a word in TextView which will be auto-corrected. 579 if (mIsAutoCorrectionIndicatorOn != newAutoCorrectionIndicator 580 && mWordComposer.isComposingWord()) { 581 mIsAutoCorrectionIndicatorOn = newAutoCorrectionIndicator; 582 final CharSequence textWithUnderline = 583 getTextWithUnderline(mWordComposer.getTypedWord()); 584 // TODO: when called from an updateSuggestionStrip() call that results from a posted 585 // message, this is called outside any batch edit. Potentially, this may result in some 586 // janky flickering of the screen, although the display speed makes it unlikely in 587 // the practice. 588 mConnection.setComposingText(textWithUnderline, 1); 589 } 590 } 591 592 /** 593 * Handle a consumed event. 594 * 595 * Consumed events represent events that have already been consumed, typically by the 596 * combining chain. 597 * 598 * @param event The event to handle. 599 * @param inputTransaction The transaction in progress. 600 */ 601 private void handleConsumedEvent(final Event event, final InputTransaction inputTransaction) { 602 // A consumed event may have text to commit and an update to the composing state, so 603 // we evaluate both. With some combiners, it's possible than an event contains both 604 // and we enter both of the following if clauses. 605 final CharSequence textToCommit = event.getTextToCommit(); 606 if (!TextUtils.isEmpty(textToCommit)) { 607 mConnection.commitText(textToCommit, 1); 608 inputTransaction.setDidAffectContents(); 609 } 610 if (mWordComposer.isComposingWord()) { 611 mConnection.setComposingText(mWordComposer.getTypedWord(), 1); 612 inputTransaction.setDidAffectContents(); 613 inputTransaction.setRequiresUpdateSuggestions(); 614 } 615 } 616 617 /** 618 * Handle a functional key event. 619 * 620 * A functional event is a special key, like delete, shift, emoji, or the settings key. 621 * Non-special keys are those that generate a single code point. 622 * This includes all letters, digits, punctuation, separators, emoji. It excludes keys that 623 * manage keyboard-related stuff like shift, language switch, settings, layout switch, or 624 * any key that results in multiple code points like the ".com" key. 625 * 626 * @param event The event to handle. 627 * @param inputTransaction The transaction in progress. 628 */ 629 private void handleFunctionalEvent(final Event event, final InputTransaction inputTransaction, 630 // TODO: remove these arguments 631 final int currentKeyboardScriptId, final LatinIME.UIHandler handler) { 632 switch (event.mKeyCode) { 633 case Constants.CODE_DELETE: 634 handleBackspaceEvent(event, inputTransaction, currentKeyboardScriptId); 635 // Backspace is a functional key, but it affects the contents of the editor. 636 inputTransaction.setDidAffectContents(); 637 break; 638 case Constants.CODE_SHIFT: 639 performRecapitalization(inputTransaction.mSettingsValues); 640 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 641 if (mSuggestedWords.mIsPrediction) { 642 inputTransaction.setRequiresUpdateSuggestions(); 643 } 644 break; 645 case Constants.CODE_CAPSLOCK: 646 // Note: Changing keyboard to shift lock state is handled in 647 // {@link KeyboardSwitcher#onCodeInput(int)}. 648 break; 649 case Constants.CODE_SYMBOL_SHIFT: 650 // Note: Calling back to the keyboard on the symbol Shift key is handled in 651 // {@link #onPressKey(int,int,boolean)} and {@link #onReleaseKey(int,boolean)}. 652 break; 653 case Constants.CODE_SWITCH_ALPHA_SYMBOL: 654 // Note: Calling back to the keyboard on symbol key is handled in 655 // {@link #onPressKey(int,int,boolean)} and {@link #onReleaseKey(int,boolean)}. 656 break; 657 case Constants.CODE_SETTINGS: 658 onSettingsKeyPressed(); 659 break; 660 case Constants.CODE_SHORTCUT: 661 // We need to switch to the shortcut IME. This is handled by LatinIME since the 662 // input logic has no business with IME switching. 663 break; 664 case Constants.CODE_ACTION_NEXT: 665 performEditorAction(EditorInfo.IME_ACTION_NEXT); 666 break; 667 case Constants.CODE_ACTION_PREVIOUS: 668 performEditorAction(EditorInfo.IME_ACTION_PREVIOUS); 669 break; 670 case Constants.CODE_LANGUAGE_SWITCH: 671 handleLanguageSwitchKey(); 672 break; 673 case Constants.CODE_EMOJI: 674 // Note: Switching emoji keyboard is being handled in 675 // {@link KeyboardState#onCodeInput(int,int)}. 676 break; 677 case Constants.CODE_ALPHA_FROM_EMOJI: 678 // Note: Switching back from Emoji keyboard to the main keyboard is being 679 // handled in {@link KeyboardState#onCodeInput(int,int)}. 680 break; 681 case Constants.CODE_SHIFT_ENTER: 682 // TODO: remove this object 683 final Event tmpEvent = Event.createSoftwareKeypressEvent(Constants.CODE_ENTER, 684 event.mKeyCode, event.mX, event.mY, event.isKeyRepeat()); 685 handleNonSpecialCharacterEvent(tmpEvent, inputTransaction, handler); 686 // Shift + Enter is treated as a functional key but it results in adding a new 687 // line, so that does affect the contents of the editor. 688 inputTransaction.setDidAffectContents(); 689 break; 690 default: 691 throw new RuntimeException("Unknown key code : " + event.mKeyCode); 692 } 693 } 694 695 /** 696 * Handle an event that is not a functional event. 697 * 698 * These events are generally events that cause input, but in some cases they may do other 699 * things like trigger an editor action. 700 * 701 * @param event The event to handle. 702 * @param inputTransaction The transaction in progress. 703 */ 704 private void handleNonFunctionalEvent(final Event event, 705 final InputTransaction inputTransaction, 706 // TODO: remove this argument 707 final LatinIME.UIHandler handler) { 708 inputTransaction.setDidAffectContents(); 709 switch (event.mCodePoint) { 710 case Constants.CODE_ENTER: 711 final EditorInfo editorInfo = getCurrentInputEditorInfo(); 712 final int imeOptionsActionId = 713 InputTypeUtils.getImeOptionsActionIdFromEditorInfo(editorInfo); 714 if (InputTypeUtils.IME_ACTION_CUSTOM_LABEL == imeOptionsActionId) { 715 // Either we have an actionLabel and we should performEditorAction with 716 // actionId regardless of its value. 717 performEditorAction(editorInfo.actionId); 718 } else if (EditorInfo.IME_ACTION_NONE != imeOptionsActionId) { 719 // We didn't have an actionLabel, but we had another action to execute. 720 // EditorInfo.IME_ACTION_NONE explicitly means no action. In contrast, 721 // EditorInfo.IME_ACTION_UNSPECIFIED is the default value for an action, so it 722 // means there should be an action and the app didn't bother to set a specific 723 // code for it - presumably it only handles one. It does not have to be treated 724 // in any specific way: anything that is not IME_ACTION_NONE should be sent to 725 // performEditorAction. 726 performEditorAction(imeOptionsActionId); 727 } else { 728 // No action label, and the action from imeOptions is NONE: this is a regular 729 // enter key that should input a carriage return. 730 handleNonSpecialCharacterEvent(event, inputTransaction, handler); 731 } 732 break; 733 default: 734 handleNonSpecialCharacterEvent(event, inputTransaction, handler); 735 break; 736 } 737 } 738 739 /** 740 * Handle inputting a code point to the editor. 741 * 742 * Non-special keys are those that generate a single code point. 743 * This includes all letters, digits, punctuation, separators, emoji. It excludes keys that 744 * manage keyboard-related stuff like shift, language switch, settings, layout switch, or 745 * any key that results in multiple code points like the ".com" key. 746 * 747 * @param event The event to handle. 748 * @param inputTransaction The transaction in progress. 749 */ 750 private void handleNonSpecialCharacterEvent(final Event event, 751 final InputTransaction inputTransaction, 752 // TODO: remove this argument 753 final LatinIME.UIHandler handler) { 754 final int codePoint = event.mCodePoint; 755 mSpaceState = SpaceState.NONE; 756 if (inputTransaction.mSettingsValues.isWordSeparator(codePoint) 757 || Character.getType(codePoint) == Character.OTHER_SYMBOL) { 758 handleSeparatorEvent(event, inputTransaction, handler); 759 } else { 760 if (SpaceState.PHANTOM == inputTransaction.mSpaceState) { 761 if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 762 // If we are in the middle of a recorrection, we need to commit the recorrection 763 // first so that we can insert the character at the current cursor position. 764 resetEntireInputState(mConnection.getExpectedSelectionStart(), 765 mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 766 } else { 767 commitTyped(inputTransaction.mSettingsValues, LastComposedWord.NOT_A_SEPARATOR); 768 } 769 } 770 handleNonSeparatorEvent(event, inputTransaction.mSettingsValues, inputTransaction); 771 } 772 } 773 774 /** 775 * Handle a non-separator. 776 * @param event The event to handle. 777 * @param settingsValues The current settings values. 778 * @param inputTransaction The transaction in progress. 779 */ 780 private void handleNonSeparatorEvent(final Event event, final SettingsValues settingsValues, 781 final InputTransaction inputTransaction) { 782 final int codePoint = event.mCodePoint; 783 // TODO: refactor this method to stop flipping isComposingWord around all the time, and 784 // make it shorter (possibly cut into several pieces). Also factor 785 // handleNonSpecialCharacterEvent which has the same name as other handle* methods but is 786 // not the same. 787 boolean isComposingWord = mWordComposer.isComposingWord(); 788 789 // TODO: remove isWordConnector() and use isUsuallyFollowedBySpace() instead. 790 // See onStartBatchInput() to see how to do it. 791 if (SpaceState.PHANTOM == inputTransaction.mSpaceState 792 && !settingsValues.isWordConnector(codePoint)) { 793 if (isComposingWord) { 794 // Sanity check 795 throw new RuntimeException("Should not be composing here"); 796 } 797 promotePhantomSpace(settingsValues); 798 } 799 800 if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 801 // If we are in the middle of a recorrection, we need to commit the recorrection 802 // first so that we can insert the character at the current cursor position. 803 resetEntireInputState(mConnection.getExpectedSelectionStart(), 804 mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 805 isComposingWord = false; 806 } 807 // We want to find out whether to start composing a new word with this character. If so, 808 // we need to reset the composing state and switch isComposingWord. The order of the 809 // tests is important for good performance. 810 // We only start composing if we're not already composing. 811 if (!isComposingWord 812 // We only start composing if this is a word code point. Essentially that means it's a 813 // a letter or a word connector. 814 && settingsValues.isWordCodePoint(codePoint) 815 // We never go into composing state if suggestions are not requested. 816 && settingsValues.needsToLookupSuggestions() && 817 // In languages with spaces, we only start composing a word when we are not already 818 // touching a word. In languages without spaces, the above conditions are sufficient. 819 (!mConnection.isCursorTouchingWord(settingsValues.mSpacingAndPunctuations) 820 || !settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces)) { 821 // Reset entirely the composing state anyway, then start composing a new word unless 822 // the character is a word connector. The idea here is, word connectors are not 823 // separators and they should be treated as normal characters, except in the first 824 // position where they should not start composing a word. 825 isComposingWord = !settingsValues.mSpacingAndPunctuations.isWordConnector(codePoint); 826 // Here we don't need to reset the last composed word. It will be reset 827 // when we commit this one, if we ever do; if on the other hand we backspace 828 // it entirely and resume suggestions on the previous word, we'd like to still 829 // have touch coordinates for it. 830 resetComposingState(false /* alsoResetLastComposedWord */); 831 } 832 if (isComposingWord) { 833 mWordComposer.applyProcessedEvent(event); 834 // If it's the first letter, make note of auto-caps state 835 if (mWordComposer.isSingleLetter()) { 836 mWordComposer.setCapitalizedModeAtStartComposingTime(inputTransaction.mShiftState); 837 } 838 mConnection.setComposingText(getTextWithUnderline( 839 mWordComposer.getTypedWord()), 1); 840 } else { 841 final boolean swapWeakSpace = tryStripSpaceAndReturnWhetherShouldSwapInstead(event, 842 inputTransaction); 843 844 if (swapWeakSpace && trySwapSwapperAndSpace(event, inputTransaction)) { 845 mSpaceState = SpaceState.WEAK; 846 } else { 847 sendKeyCodePoint(settingsValues, codePoint); 848 } 849 // In case the "add to dictionary" hint was still displayed. 850 mSuggestionStripViewAccessor.dismissAddToDictionaryHint(); 851 } 852 inputTransaction.setRequiresUpdateSuggestions(); 853 } 854 855 /** 856 * Handle input of a separator code point. 857 * @param event The event to handle. 858 * @param inputTransaction The transaction in progress. 859 */ 860 private void handleSeparatorEvent(final Event event, final InputTransaction inputTransaction, 861 // TODO: remove this argument 862 final LatinIME.UIHandler handler) { 863 final int codePoint = event.mCodePoint; 864 final SettingsValues settingsValues = inputTransaction.mSettingsValues; 865 final boolean wasComposingWord = mWordComposer.isComposingWord(); 866 // We avoid sending spaces in languages without spaces if we were composing. 867 final boolean shouldAvoidSendingCode = Constants.CODE_SPACE == codePoint 868 && !settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces 869 && wasComposingWord; 870 if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 871 // If we are in the middle of a recorrection, we need to commit the recorrection 872 // first so that we can insert the separator at the current cursor position. 873 resetEntireInputState(mConnection.getExpectedSelectionStart(), 874 mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 875 } 876 // isComposingWord() may have changed since we stored wasComposing 877 if (mWordComposer.isComposingWord()) { 878 if (settingsValues.mAutoCorrectionEnabledPerUserSettings) { 879 final String separator = shouldAvoidSendingCode ? LastComposedWord.NOT_A_SEPARATOR 880 : StringUtils.newSingleCodePointString(codePoint); 881 commitCurrentAutoCorrection(settingsValues, separator, handler); 882 inputTransaction.setDidAutoCorrect(); 883 } else { 884 commitTyped(settingsValues, 885 StringUtils.newSingleCodePointString(codePoint)); 886 } 887 } 888 889 final boolean swapWeakSpace = tryStripSpaceAndReturnWhetherShouldSwapInstead(event, 890 inputTransaction); 891 892 final boolean isInsideDoubleQuoteOrAfterDigit = Constants.CODE_DOUBLE_QUOTE == codePoint 893 && mConnection.isInsideDoubleQuoteOrAfterDigit(); 894 895 final boolean needsPrecedingSpace; 896 if (SpaceState.PHANTOM != inputTransaction.mSpaceState) { 897 needsPrecedingSpace = false; 898 } else if (Constants.CODE_DOUBLE_QUOTE == codePoint) { 899 // Double quotes behave like they are usually preceded by space iff we are 900 // not inside a double quote or after a digit. 901 needsPrecedingSpace = !isInsideDoubleQuoteOrAfterDigit; 902 } else if (settingsValues.mSpacingAndPunctuations.isClusteringSymbol(codePoint) 903 && settingsValues.mSpacingAndPunctuations.isClusteringSymbol( 904 mConnection.getCodePointBeforeCursor())) { 905 needsPrecedingSpace = false; 906 } else { 907 needsPrecedingSpace = settingsValues.isUsuallyPrecededBySpace(codePoint); 908 } 909 910 if (needsPrecedingSpace) { 911 promotePhantomSpace(settingsValues); 912 } 913 914 if (tryPerformDoubleSpacePeriod(event, inputTransaction)) { 915 mSpaceState = SpaceState.DOUBLE; 916 inputTransaction.setRequiresUpdateSuggestions(); 917 } else if (swapWeakSpace && trySwapSwapperAndSpace(event, inputTransaction)) { 918 mSpaceState = SpaceState.SWAP_PUNCTUATION; 919 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 920 } else if (Constants.CODE_SPACE == codePoint) { 921 if (!mSuggestedWords.isPunctuationSuggestions()) { 922 mSpaceState = SpaceState.WEAK; 923 } 924 925 startDoubleSpacePeriodCountdown(inputTransaction); 926 if (wasComposingWord || mSuggestedWords.isEmpty()) { 927 inputTransaction.setRequiresUpdateSuggestions(); 928 } 929 930 if (!shouldAvoidSendingCode) { 931 sendKeyCodePoint(settingsValues, codePoint); 932 } 933 } else { 934 if ((SpaceState.PHANTOM == inputTransaction.mSpaceState 935 && settingsValues.isUsuallyFollowedBySpace(codePoint)) 936 || (Constants.CODE_DOUBLE_QUOTE == codePoint 937 && isInsideDoubleQuoteOrAfterDigit)) { 938 // If we are in phantom space state, and the user presses a separator, we want to 939 // stay in phantom space state so that the next keypress has a chance to add the 940 // space. For example, if I type "Good dat", pick "day" from the suggestion strip 941 // then insert a comma and go on to typing the next word, I want the space to be 942 // inserted automatically before the next word, the same way it is when I don't 943 // input the comma. A double quote behaves like it's usually followed by space if 944 // we're inside a double quote. 945 // The case is a little different if the separator is a space stripper. Such a 946 // separator does not normally need a space on the right (that's the difference 947 // between swappers and strippers), so we should not stay in phantom space state if 948 // the separator is a stripper. Hence the additional test above. 949 mSpaceState = SpaceState.PHANTOM; 950 } 951 952 sendKeyCodePoint(settingsValues, codePoint); 953 954 // Set punctuation right away. onUpdateSelection will fire but tests whether it is 955 // already displayed or not, so it's okay. 956 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 957 } 958 959 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 960 } 961 962 /** 963 * Handle a press on the backspace key. 964 * @param event The event to handle. 965 * @param inputTransaction The transaction in progress. 966 */ 967 private void handleBackspaceEvent(final Event event, final InputTransaction inputTransaction, 968 // TODO: remove this argument, put it into settingsValues 969 final int currentKeyboardScriptId) { 970 mSpaceState = SpaceState.NONE; 971 mDeleteCount++; 972 973 // In many cases after backspace, we need to update the shift state. Normally we need 974 // to do this right away to avoid the shift state being out of date in case the user types 975 // backspace then some other character very fast. However, in the case of backspace key 976 // repeat, this can lead to flashiness when the cursor flies over positions where the 977 // shift state should be updated, so if this is a key repeat, we update after a small delay. 978 // Then again, even in the case of a key repeat, if the cursor is at start of text, it 979 // can't go any further back, so we can update right away even if it's a key repeat. 980 final int shiftUpdateKind = 981 event.isKeyRepeat() && mConnection.getExpectedSelectionStart() > 0 982 ? InputTransaction.SHIFT_UPDATE_LATER : InputTransaction.SHIFT_UPDATE_NOW; 983 inputTransaction.requireShiftUpdate(shiftUpdateKind); 984 985 if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 986 // If we are in the middle of a recorrection, we need to commit the recorrection 987 // first so that we can remove the character at the current cursor position. 988 resetEntireInputState(mConnection.getExpectedSelectionStart(), 989 mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 990 // When we exit this if-clause, mWordComposer.isComposingWord() will return false. 991 } 992 if (mWordComposer.isComposingWord()) { 993 if (mWordComposer.isBatchMode()) { 994 final String rejectedSuggestion = mWordComposer.getTypedWord(); 995 mWordComposer.reset(); 996 mWordComposer.setRejectedBatchModeSuggestion(rejectedSuggestion); 997 if (!TextUtils.isEmpty(rejectedSuggestion)) { 998 mDictionaryFacilitator.removeWordFromPersonalizedDicts(rejectedSuggestion); 999 } 1000 } else { 1001 mWordComposer.applyProcessedEvent(event); 1002 } 1003 if (mWordComposer.isComposingWord()) { 1004 mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); 1005 } else { 1006 mConnection.commitText("", 1); 1007 } 1008 inputTransaction.setRequiresUpdateSuggestions(); 1009 } else { 1010 if (mLastComposedWord.canRevertCommit()) { 1011 revertCommit(inputTransaction); 1012 return; 1013 } 1014 if (mEnteredText != null && mConnection.sameAsTextBeforeCursor(mEnteredText)) { 1015 // Cancel multi-character input: remove the text we just entered. 1016 // This is triggered on backspace after a key that inputs multiple characters, 1017 // like the smiley key or the .com key. 1018 mConnection.deleteSurroundingText(mEnteredText.length(), 0); 1019 mEnteredText = null; 1020 // If we have mEnteredText, then we know that mHasUncommittedTypedChars == false. 1021 // In addition we know that spaceState is false, and that we should not be 1022 // reverting any autocorrect at this point. So we can safely return. 1023 return; 1024 } 1025 if (SpaceState.DOUBLE == inputTransaction.mSpaceState) { 1026 cancelDoubleSpacePeriodCountdown(); 1027 if (mConnection.revertDoubleSpacePeriod()) { 1028 // No need to reset mSpaceState, it has already be done (that's why we 1029 // receive it as a parameter) 1030 inputTransaction.setRequiresUpdateSuggestions(); 1031 mWordComposer.setCapitalizedModeAtStartComposingTime( 1032 WordComposer.CAPS_MODE_OFF); 1033 return; 1034 } 1035 } else if (SpaceState.SWAP_PUNCTUATION == inputTransaction.mSpaceState) { 1036 if (mConnection.revertSwapPunctuation()) { 1037 // Likewise 1038 return; 1039 } 1040 } 1041 1042 // No cancelling of commit/double space/swap: we have a regular backspace. 1043 // We should backspace one char and restart suggestion if at the end of a word. 1044 if (mConnection.hasSelection()) { 1045 // If there is a selection, remove it. 1046 final int numCharsDeleted = mConnection.getExpectedSelectionEnd() 1047 - mConnection.getExpectedSelectionStart(); 1048 mConnection.setSelection(mConnection.getExpectedSelectionEnd(), 1049 mConnection.getExpectedSelectionEnd()); 1050 mConnection.deleteSurroundingText(numCharsDeleted, 0); 1051 } else { 1052 // There is no selection, just delete one character. 1053 if (Constants.NOT_A_CURSOR_POSITION == mConnection.getExpectedSelectionEnd()) { 1054 // This should never happen. 1055 Log.e(TAG, "Backspace when we don't know the selection position"); 1056 } 1057 if (inputTransaction.mSettingsValues.isBeforeJellyBean() || 1058 inputTransaction.mSettingsValues.mInputAttributes.isTypeNull()) { 1059 // There are two possible reasons to send a key event: either the field has 1060 // type TYPE_NULL, in which case the keyboard should send events, or we are 1061 // running in backward compatibility mode. Before Jelly bean, the keyboard 1062 // would simulate a hardware keyboard event on pressing enter or delete. This 1063 // is bad for many reasons (there are race conditions with commits) but some 1064 // applications are relying on this behavior so we continue to support it for 1065 // older apps, so we retain this behavior if the app has target SDK < JellyBean. 1066 sendDownUpKeyEvent(KeyEvent.KEYCODE_DEL); 1067 if (mDeleteCount > Constants.DELETE_ACCELERATE_AT) { 1068 sendDownUpKeyEvent(KeyEvent.KEYCODE_DEL); 1069 } 1070 } else { 1071 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 1072 if (codePointBeforeCursor == Constants.NOT_A_CODE) { 1073 // HACK for backward compatibility with broken apps that haven't realized 1074 // yet that hardware keyboards are not the only way of inputting text. 1075 // Nothing to delete before the cursor. We should not do anything, but many 1076 // broken apps expect something to happen in this case so that they can 1077 // catch it and have their broken interface react. If you need the keyboard 1078 // to do this, you're doing it wrong -- please fix your app. 1079 mConnection.deleteSurroundingText(1, 0); 1080 return; 1081 } 1082 final int lengthToDelete = 1083 Character.isSupplementaryCodePoint(codePointBeforeCursor) ? 2 : 1; 1084 mConnection.deleteSurroundingText(lengthToDelete, 0); 1085 if (mDeleteCount > Constants.DELETE_ACCELERATE_AT) { 1086 final int codePointBeforeCursorToDeleteAgain = 1087 mConnection.getCodePointBeforeCursor(); 1088 if (codePointBeforeCursorToDeleteAgain != Constants.NOT_A_CODE) { 1089 final int lengthToDeleteAgain = Character.isSupplementaryCodePoint( 1090 codePointBeforeCursorToDeleteAgain) ? 2 : 1; 1091 mConnection.deleteSurroundingText(lengthToDeleteAgain, 0); 1092 } 1093 } 1094 } 1095 } 1096 if (inputTransaction.mSettingsValues 1097 .isSuggestionsEnabledPerUserSettings() 1098 && inputTransaction.mSettingsValues.mSpacingAndPunctuations 1099 .mCurrentLanguageHasSpaces 1100 && !mConnection.isCursorFollowedByWordCharacter( 1101 inputTransaction.mSettingsValues.mSpacingAndPunctuations)) { 1102 restartSuggestionsOnWordTouchedByCursor(inputTransaction.mSettingsValues, 1103 true /* shouldIncludeResumedWordInSuggestions */, currentKeyboardScriptId); 1104 } 1105 } 1106 } 1107 1108 /** 1109 * Handle a press on the language switch key (the "globe key") 1110 */ 1111 private void handleLanguageSwitchKey() { 1112 mLatinIME.switchToNextSubtype(); 1113 } 1114 1115 /** 1116 * Swap a space with a space-swapping punctuation sign. 1117 * 1118 * This method will check that there are two characters before the cursor and that the first 1119 * one is a space before it does the actual swapping. 1120 * @param event The event to handle. 1121 * @param inputTransaction The transaction in progress. 1122 * @return true if the swap has been performed, false if it was prevented by preliminary checks. 1123 */ 1124 private boolean trySwapSwapperAndSpace(final Event event, 1125 final InputTransaction inputTransaction) { 1126 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 1127 if (Constants.CODE_SPACE != codePointBeforeCursor) { 1128 return false; 1129 } 1130 mConnection.deleteSurroundingText(1, 0); 1131 final String text = event.getTextToCommit() + " "; 1132 mConnection.commitText(text, 1); 1133 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 1134 return true; 1135 } 1136 1137 /* 1138 * Strip a trailing space if necessary and returns whether it's a swap weak space situation. 1139 * @param event The event to handle. 1140 * @param inputTransaction The transaction in progress. 1141 * @return whether we should swap the space instead of removing it. 1142 */ 1143 private boolean tryStripSpaceAndReturnWhetherShouldSwapInstead(final Event event, 1144 final InputTransaction inputTransaction) { 1145 final int codePoint = event.mCodePoint; 1146 final boolean isFromSuggestionStrip = event.isSuggestionStripPress(); 1147 if (Constants.CODE_ENTER == codePoint && 1148 SpaceState.SWAP_PUNCTUATION == inputTransaction.mSpaceState) { 1149 mConnection.removeTrailingSpace(); 1150 return false; 1151 } 1152 if ((SpaceState.WEAK == inputTransaction.mSpaceState 1153 || SpaceState.SWAP_PUNCTUATION == inputTransaction.mSpaceState) 1154 && isFromSuggestionStrip) { 1155 if (inputTransaction.mSettingsValues.isUsuallyPrecededBySpace(codePoint)) { 1156 return false; 1157 } 1158 if (inputTransaction.mSettingsValues.isUsuallyFollowedBySpace(codePoint)) { 1159 return true; 1160 } 1161 mConnection.removeTrailingSpace(); 1162 } 1163 return false; 1164 } 1165 1166 public void startDoubleSpacePeriodCountdown(final InputTransaction inputTransaction) { 1167 mDoubleSpacePeriodCountdownStart = inputTransaction.mTimestamp; 1168 } 1169 1170 public void cancelDoubleSpacePeriodCountdown() { 1171 mDoubleSpacePeriodCountdownStart = 0; 1172 } 1173 1174 public boolean isDoubleSpacePeriodCountdownActive(final InputTransaction inputTransaction) { 1175 return inputTransaction.mTimestamp - mDoubleSpacePeriodCountdownStart 1176 < inputTransaction.mSettingsValues.mDoubleSpacePeriodTimeout; 1177 } 1178 1179 /** 1180 * Apply the double-space-to-period transformation if applicable. 1181 * 1182 * The double-space-to-period transformation means that we replace two spaces with a 1183 * period-space sequence of characters. This typically happens when the user presses space 1184 * twice in a row quickly. 1185 * This method will check that the double-space-to-period is active in settings, that the 1186 * two spaces have been input close enough together, that the typed character is a space 1187 * and that the previous character allows for the transformation to take place. If all of 1188 * these conditions are fulfilled, this method applies the transformation and returns true. 1189 * Otherwise, it does nothing and returns false. 1190 * 1191 * @param event The event to handle. 1192 * @param inputTransaction The transaction in progress. 1193 * @return true if we applied the double-space-to-period transformation, false otherwise. 1194 */ 1195 private boolean tryPerformDoubleSpacePeriod(final Event event, 1196 final InputTransaction inputTransaction) { 1197 // Check the setting, the typed character and the countdown. If any of the conditions is 1198 // not fulfilled, return false. 1199 if (!inputTransaction.mSettingsValues.mUseDoubleSpacePeriod 1200 || Constants.CODE_SPACE != event.mCodePoint 1201 || !isDoubleSpacePeriodCountdownActive(inputTransaction)) { 1202 return false; 1203 } 1204 // We only do this when we see one space and an accepted code point before the cursor. 1205 // The code point may be a surrogate pair but the space may not, so we need 3 chars. 1206 final CharSequence lastTwo = mConnection.getTextBeforeCursor(3, 0); 1207 if (null == lastTwo) return false; 1208 final int length = lastTwo.length(); 1209 if (length < 2) return false; 1210 if (lastTwo.charAt(length - 1) != Constants.CODE_SPACE) return false; 1211 // We know there is a space in pos -1, and we have at least two chars. If we have only two 1212 // chars, isSurrogatePairs can't return true as charAt(1) is a space, so this is fine. 1213 final int firstCodePoint = 1214 Character.isSurrogatePair(lastTwo.charAt(0), lastTwo.charAt(1)) ? 1215 Character.codePointAt(lastTwo, length - 3) : lastTwo.charAt(length - 2); 1216 if (canBeFollowedByDoubleSpacePeriod(firstCodePoint)) { 1217 cancelDoubleSpacePeriodCountdown(); 1218 mConnection.deleteSurroundingText(1, 0); 1219 final String textToInsert = inputTransaction.mSettingsValues.mSpacingAndPunctuations 1220 .mSentenceSeparatorAndSpace; 1221 mConnection.commitText(textToInsert, 1); 1222 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 1223 inputTransaction.setRequiresUpdateSuggestions(); 1224 return true; 1225 } 1226 return false; 1227 } 1228 1229 /** 1230 * Returns whether this code point can be followed by the double-space-to-period transformation. 1231 * 1232 * See #maybeDoubleSpaceToPeriod for details. 1233 * Generally, most word characters can be followed by the double-space-to-period transformation, 1234 * while most punctuation can't. Some punctuation however does allow for this to take place 1235 * after them, like the closing parenthesis for example. 1236 * 1237 * @param codePoint the code point after which we may want to apply the transformation 1238 * @return whether it's fine to apply the transformation after this code point. 1239 */ 1240 private static boolean canBeFollowedByDoubleSpacePeriod(final int codePoint) { 1241 // TODO: This should probably be a blacklist rather than a whitelist. 1242 // TODO: This should probably be language-dependant... 1243 return Character.isLetterOrDigit(codePoint) 1244 || codePoint == Constants.CODE_SINGLE_QUOTE 1245 || codePoint == Constants.CODE_DOUBLE_QUOTE 1246 || codePoint == Constants.CODE_CLOSING_PARENTHESIS 1247 || codePoint == Constants.CODE_CLOSING_SQUARE_BRACKET 1248 || codePoint == Constants.CODE_CLOSING_CURLY_BRACKET 1249 || codePoint == Constants.CODE_CLOSING_ANGLE_BRACKET 1250 || codePoint == Constants.CODE_PLUS 1251 || codePoint == Constants.CODE_PERCENT 1252 || Character.getType(codePoint) == Character.OTHER_SYMBOL; 1253 } 1254 1255 /** 1256 * Performs a recapitalization event. 1257 * @param settingsValues The current settings values. 1258 */ 1259 private void performRecapitalization(final SettingsValues settingsValues) { 1260 if (!mConnection.hasSelection() || !mRecapitalizeStatus.mIsEnabled()) { 1261 return; // No selection or recapitalize is disabled for now 1262 } 1263 final int selectionStart = mConnection.getExpectedSelectionStart(); 1264 final int selectionEnd = mConnection.getExpectedSelectionEnd(); 1265 final int numCharsSelected = selectionEnd - selectionStart; 1266 if (numCharsSelected > Constants.MAX_CHARACTERS_FOR_RECAPITALIZATION) { 1267 // We bail out if we have too many characters for performance reasons. We don't want 1268 // to suck possibly multiple-megabyte data. 1269 return; 1270 } 1271 // If we have a recapitalize in progress, use it; otherwise, start a new one. 1272 if (!mRecapitalizeStatus.isStarted() 1273 || !mRecapitalizeStatus.isSetAt(selectionStart, selectionEnd)) { 1274 final CharSequence selectedText = 1275 mConnection.getSelectedText(0 /* flags, 0 for no styles */); 1276 if (TextUtils.isEmpty(selectedText)) return; // Race condition with the input connection 1277 mRecapitalizeStatus.start(selectionStart, selectionEnd, selectedText.toString(), 1278 settingsValues.mLocale, 1279 settingsValues.mSpacingAndPunctuations.mSortedWordSeparators); 1280 // We trim leading and trailing whitespace. 1281 mRecapitalizeStatus.trim(); 1282 } 1283 mConnection.finishComposingText(); 1284 mRecapitalizeStatus.rotate(); 1285 mConnection.setSelection(selectionEnd, selectionEnd); 1286 mConnection.deleteSurroundingText(numCharsSelected, 0); 1287 mConnection.commitText(mRecapitalizeStatus.getRecapitalizedString(), 0); 1288 mConnection.setSelection(mRecapitalizeStatus.getNewCursorStart(), 1289 mRecapitalizeStatus.getNewCursorEnd()); 1290 } 1291 1292 private void performAdditionToUserHistoryDictionary(final SettingsValues settingsValues, 1293 final String suggestion, final PrevWordsInfo prevWordsInfo) { 1294 // If correction is not enabled, we don't add words to the user history dictionary. 1295 // That's to avoid unintended additions in some sensitive fields, or fields that 1296 // expect to receive non-words. 1297 if (!settingsValues.mAutoCorrectionEnabledPerUserSettings) return; 1298 1299 if (TextUtils.isEmpty(suggestion)) return; 1300 final boolean wasAutoCapitalized = 1301 mWordComposer.wasAutoCapitalized() && !mWordComposer.isMostlyCaps(); 1302 final int timeStampInSeconds = (int)TimeUnit.MILLISECONDS.toSeconds( 1303 System.currentTimeMillis()); 1304 mDictionaryFacilitator.addToUserHistory(suggestion, wasAutoCapitalized, 1305 prevWordsInfo, timeStampInSeconds, settingsValues.mBlockPotentiallyOffensive); 1306 } 1307 1308 public void performUpdateSuggestionStripSync(final SettingsValues settingsValues, 1309 final int inputStyle) { 1310 // Check if we have a suggestion engine attached. 1311 if (!settingsValues.needsToLookupSuggestions()) { 1312 if (mWordComposer.isComposingWord()) { 1313 Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not " 1314 + "requested!"); 1315 } 1316 // Clear the suggestions strip. 1317 mSuggestionStripViewAccessor.showSuggestionStrip(SuggestedWords.EMPTY); 1318 return; 1319 } 1320 1321 if (!mWordComposer.isComposingWord() && !settingsValues.mBigramPredictionEnabled) { 1322 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1323 return; 1324 } 1325 1326 final AsyncResultHolder<SuggestedWords> holder = new AsyncResultHolder<>(); 1327 mInputLogicHandler.getSuggestedWords(inputStyle, SuggestedWords.NOT_A_SEQUENCE_NUMBER, 1328 new OnGetSuggestedWordsCallback() { 1329 @Override 1330 public void onGetSuggestedWords(final SuggestedWords suggestedWords) { 1331 final String typedWord = mWordComposer.getTypedWord(); 1332 // Show new suggestions if we have at least one. Otherwise keep the old 1333 // suggestions with the new typed word. Exception: if the length of the 1334 // typed word is <= 1 (after a deletion typically) we clear old suggestions. 1335 if (suggestedWords.size() > 1 || typedWord.length() <= 1) { 1336 holder.set(suggestedWords); 1337 } else { 1338 holder.set(retrieveOlderSuggestions(typedWord, mSuggestedWords)); 1339 } 1340 } 1341 } 1342 ); 1343 1344 // This line may cause the current thread to wait. 1345 final SuggestedWords suggestedWords = holder.get(null, 1346 Constants.GET_SUGGESTED_WORDS_TIMEOUT); 1347 if (suggestedWords != null) { 1348 mSuggestionStripViewAccessor.showSuggestionStrip(suggestedWords); 1349 } 1350 } 1351 1352 /** 1353 * Check if the cursor is touching a word. If so, restart suggestions on this word, else 1354 * do nothing. 1355 * 1356 * @param settingsValues the current values of the settings. 1357 * @param shouldIncludeResumedWordInSuggestions whether to include the word on which we resume 1358 * suggestions in the suggestion list. 1359 */ 1360 // TODO: make this private. 1361 public void restartSuggestionsOnWordTouchedByCursor(final SettingsValues settingsValues, 1362 final boolean shouldIncludeResumedWordInSuggestions, 1363 // TODO: remove this argument, put it into settingsValues 1364 final int currentKeyboardScriptId) { 1365 // HACK: We may want to special-case some apps that exhibit bad behavior in case of 1366 // recorrection. This is a temporary, stopgap measure that will be removed later. 1367 // TODO: remove this. 1368 if (settingsValues.isBrokenByRecorrection() 1369 // Recorrection is not supported in languages without spaces because we don't know 1370 // how to segment them yet. 1371 || !settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces 1372 // If no suggestions are requested, don't try restarting suggestions. 1373 || !settingsValues.needsToLookupSuggestions() 1374 // If we are currently in a batch input, we must not resume suggestions, or the result 1375 // of the batch input will replace the new composition. This may happen in the corner case 1376 // that the app moves the cursor on its own accord during a batch input. 1377 || mInputLogicHandler.isInBatchInput() 1378 // If the cursor is not touching a word, or if there is a selection, return right away. 1379 || mConnection.hasSelection() 1380 // If we don't know the cursor location, return. 1381 || mConnection.getExpectedSelectionStart() < 0) { 1382 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1383 return; 1384 } 1385 final int expectedCursorPosition = mConnection.getExpectedSelectionStart(); 1386 if (!mConnection.isCursorTouchingWord(settingsValues.mSpacingAndPunctuations)) { 1387 // Show predictions. 1388 mWordComposer.setCapitalizedModeAtStartComposingTime(WordComposer.CAPS_MODE_OFF); 1389 mLatinIME.mHandler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_RECORRECTION); 1390 return; 1391 } 1392 final TextRange range = mConnection.getWordRangeAtCursor( 1393 settingsValues.mSpacingAndPunctuations.mSortedWordSeparators, 1394 currentKeyboardScriptId); 1395 if (null == range) return; // Happens if we don't have an input connection at all 1396 if (range.length() <= 0) { 1397 // Race condition, or touching a word in a non-supported script. 1398 mLatinIME.setNeutralSuggestionStrip(); 1399 return; 1400 } 1401 // If for some strange reason (editor bug or so) we measure the text before the cursor as 1402 // longer than what the entire text is supposed to be, the safe thing to do is bail out. 1403 if (range.mHasUrlSpans) return; // If there are links, we don't resume suggestions. Making 1404 // edits to a linkified text through batch commands would ruin the URL spans, and unless 1405 // we take very complicated steps to preserve the whole link, we can't do things right so 1406 // we just do not resume because it's safer. 1407 final int numberOfCharsInWordBeforeCursor = range.getNumberOfCharsInWordBeforeCursor(); 1408 if (numberOfCharsInWordBeforeCursor > expectedCursorPosition) return; 1409 final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<>(); 1410 final String typedWord = range.mWord.toString(); 1411 if (shouldIncludeResumedWordInSuggestions) { 1412 suggestions.add(new SuggestedWordInfo(typedWord, 1413 SuggestedWords.MAX_SUGGESTIONS + 1, 1414 SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED, 1415 SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */, 1416 SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */)); 1417 } 1418 if (!isResumableWord(settingsValues, typedWord)) { 1419 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1420 return; 1421 } 1422 int i = 0; 1423 for (final SuggestionSpan span : range.getSuggestionSpansAtWord()) { 1424 for (final String s : span.getSuggestions()) { 1425 ++i; 1426 if (!TextUtils.equals(s, typedWord)) { 1427 suggestions.add(new SuggestedWordInfo(s, 1428 SuggestedWords.MAX_SUGGESTIONS - i, 1429 SuggestedWordInfo.KIND_RESUMED, Dictionary.DICTIONARY_RESUMED, 1430 SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */, 1431 SuggestedWordInfo.NOT_A_CONFIDENCE 1432 /* autoCommitFirstWordConfidence */)); 1433 } 1434 } 1435 } 1436 final int[] codePoints = StringUtils.toCodePointArray(typedWord); 1437 // We want the previous word for suggestion. If we have chars in the word 1438 // before the cursor, then we want the word before that, hence 2; otherwise, 1439 // we want the word immediately before the cursor, hence 1. 1440 final PrevWordsInfo prevWordsInfo = getPrevWordsInfoFromNthPreviousWordForSuggestion( 1441 settingsValues.mSpacingAndPunctuations, 1442 0 == numberOfCharsInWordBeforeCursor ? 1 : 2); 1443 mWordComposer.setComposingWord(codePoints, 1444 mLatinIME.getCoordinatesForCurrentKeyboard(codePoints)); 1445 mWordComposer.setCursorPositionWithinWord( 1446 typedWord.codePointCount(0, numberOfCharsInWordBeforeCursor)); 1447 mConnection.maybeMoveTheCursorAroundAndRestoreToWorkaroundABug(); 1448 mConnection.setComposingRegion(expectedCursorPosition - numberOfCharsInWordBeforeCursor, 1449 expectedCursorPosition + range.getNumberOfCharsInWordAfterCursor()); 1450 if (suggestions.size() <= (shouldIncludeResumedWordInSuggestions ? 1 : 0)) { 1451 // If there weren't any suggestion spans on this word, suggestions#size() will be 1 1452 // if shouldIncludeResumedWordInSuggestions is true, 0 otherwise. In this case, we 1453 // have no useful suggestions, so we will try to compute some for it instead. 1454 mInputLogicHandler.getSuggestedWords(Suggest.SESSION_ID_TYPING, 1455 SuggestedWords.NOT_A_SEQUENCE_NUMBER, new OnGetSuggestedWordsCallback() { 1456 @Override 1457 public void onGetSuggestedWords( 1458 final SuggestedWords suggestedWordsIncludingTypedWord) { 1459 final SuggestedWords suggestedWords; 1460 if (suggestedWordsIncludingTypedWord.size() > 1 1461 && !shouldIncludeResumedWordInSuggestions) { 1462 // We were able to compute new suggestions for this word. 1463 // Remove the typed word, since we don't want to display it in this 1464 // case. The #getSuggestedWordsExcludingTypedWord() method sets 1465 // willAutoCorrect to false. 1466 suggestedWords = suggestedWordsIncludingTypedWord 1467 .getSuggestedWordsExcludingTypedWord(SuggestedWords 1468 .INPUT_STYLE_RECORRECTION); 1469 } else { 1470 // No saved suggestions, and we were unable to compute any good one 1471 // either. Rather than displaying an empty suggestion strip, we'll 1472 // display the original word alone in the middle. 1473 // Since there is only one word, willAutoCorrect is false. 1474 suggestedWords = suggestedWordsIncludingTypedWord; 1475 } 1476 mIsAutoCorrectionIndicatorOn = false; 1477 mLatinIME.mHandler.showSuggestionStrip(suggestedWords); 1478 }}); 1479 } else { 1480 // We found suggestion spans in the word. We'll create the SuggestedWords out of 1481 // them, and make willAutoCorrect false. We make typedWordValid false, because the 1482 // color of the word in the suggestion strip changes according to this parameter, 1483 // and false gives the correct color. 1484 final SuggestedWords suggestedWords = new SuggestedWords(suggestions, 1485 null /* rawSuggestions */, typedWord, 1486 false /* typedWordValid */, false /* willAutoCorrect */, 1487 false /* isObsoleteSuggestions */, false /* isPrediction */, 1488 SuggestedWords.INPUT_STYLE_RECORRECTION, 1489 SuggestedWords.NOT_A_SEQUENCE_NUMBER); 1490 mIsAutoCorrectionIndicatorOn = false; 1491 mLatinIME.mHandler.showSuggestionStrip(suggestedWords); 1492 } 1493 } 1494 1495 /** 1496 * Reverts a previous commit with auto-correction. 1497 * 1498 * This is triggered upon pressing backspace just after a commit with auto-correction. 1499 * 1500 * @param inputTransaction The transaction in progress. 1501 */ 1502 private void revertCommit(final InputTransaction inputTransaction) { 1503 final CharSequence originallyTypedWord = mLastComposedWord.mTypedWord; 1504 final CharSequence committedWord = mLastComposedWord.mCommittedWord; 1505 final String committedWordString = committedWord.toString(); 1506 final int cancelLength = committedWord.length(); 1507 // We want java chars, not codepoints for the following. 1508 final int separatorLength = mLastComposedWord.mSeparatorString.length(); 1509 // TODO: should we check our saved separator against the actual contents of the text view? 1510 final int deleteLength = cancelLength + separatorLength; 1511 if (DebugFlags.DEBUG_ENABLED) { 1512 if (mWordComposer.isComposingWord()) { 1513 throw new RuntimeException("revertCommit, but we are composing a word"); 1514 } 1515 final CharSequence wordBeforeCursor = 1516 mConnection.getTextBeforeCursor(deleteLength, 0).subSequence(0, cancelLength); 1517 if (!TextUtils.equals(committedWord, wordBeforeCursor)) { 1518 throw new RuntimeException("revertCommit check failed: we thought we were " 1519 + "reverting \"" + committedWord 1520 + "\", but before the cursor we found \"" + wordBeforeCursor + "\""); 1521 } 1522 } 1523 mConnection.deleteSurroundingText(deleteLength, 0); 1524 if (!TextUtils.isEmpty(committedWord)) { 1525 mDictionaryFacilitator.removeWordFromPersonalizedDicts(committedWordString); 1526 } 1527 final String stringToCommit = originallyTypedWord + mLastComposedWord.mSeparatorString; 1528 final SpannableString textToCommit = new SpannableString(stringToCommit); 1529 if (committedWord instanceof SpannableString) { 1530 final SpannableString committedWordWithSuggestionSpans = (SpannableString)committedWord; 1531 final Object[] spans = committedWordWithSuggestionSpans.getSpans(0, 1532 committedWord.length(), Object.class); 1533 final int lastCharIndex = textToCommit.length() - 1; 1534 // We will collect all suggestions in the following array. 1535 final ArrayList<String> suggestions = new ArrayList<>(); 1536 // First, add the committed word to the list of suggestions. 1537 suggestions.add(committedWordString); 1538 for (final Object span : spans) { 1539 // If this is a suggestion span, we check that the locale is the right one, and 1540 // that the word is not the committed word. That should mostly be the case. 1541 // Given this, we add it to the list of suggestions, otherwise we discard it. 1542 if (span instanceof SuggestionSpan) { 1543 final SuggestionSpan suggestionSpan = (SuggestionSpan)span; 1544 if (!suggestionSpan.getLocale().equals( 1545 inputTransaction.mSettingsValues.mLocale.toString())) { 1546 continue; 1547 } 1548 for (final String suggestion : suggestionSpan.getSuggestions()) { 1549 if (!suggestion.equals(committedWordString)) { 1550 suggestions.add(suggestion); 1551 } 1552 } 1553 } else { 1554 // If this is not a suggestion span, we just add it as is. 1555 textToCommit.setSpan(span, 0 /* start */, lastCharIndex /* end */, 1556 committedWordWithSuggestionSpans.getSpanFlags(span)); 1557 } 1558 } 1559 // Add the suggestion list to the list of suggestions. 1560 textToCommit.setSpan(new SuggestionSpan(inputTransaction.mSettingsValues.mLocale, 1561 suggestions.toArray(new String[suggestions.size()]), 0 /* flags */), 1562 0 /* start */, lastCharIndex /* end */, 0 /* flags */); 1563 } 1564 if (inputTransaction.mSettingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces) { 1565 // For languages with spaces, we revert to the typed string, but the cursor is still 1566 // after the separator so we don't resume suggestions. If the user wants to correct 1567 // the word, they have to press backspace again. 1568 mConnection.commitText(textToCommit, 1); 1569 } else { 1570 // For languages without spaces, we revert the typed string but the cursor is flush 1571 // with the typed word, so we need to resume suggestions right away. 1572 final int[] codePoints = StringUtils.toCodePointArray(stringToCommit); 1573 mWordComposer.setComposingWord(codePoints, 1574 mLatinIME.getCoordinatesForCurrentKeyboard(codePoints)); 1575 mConnection.setComposingText(textToCommit, 1); 1576 } 1577 // Don't restart suggestion yet. We'll restart if the user deletes the separator. 1578 mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 1579 // We have a separator between the word and the cursor: we should show predictions. 1580 inputTransaction.setRequiresUpdateSuggestions(); 1581 } 1582 1583 /** 1584 * Factor in auto-caps and manual caps and compute the current caps mode. 1585 * @param settingsValues the current settings values. 1586 * @param keyboardShiftMode the current shift mode of the keyboard. See 1587 * KeyboardSwitcher#getKeyboardShiftMode() for possible values. 1588 * @return the actual caps mode the keyboard is in right now. 1589 */ 1590 private int getActualCapsMode(final SettingsValues settingsValues, 1591 final int keyboardShiftMode) { 1592 if (keyboardShiftMode != WordComposer.CAPS_MODE_AUTO_SHIFTED) { 1593 return keyboardShiftMode; 1594 } 1595 final int auto = getCurrentAutoCapsState(settingsValues); 1596 if (0 != (auto & TextUtils.CAP_MODE_CHARACTERS)) { 1597 return WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED; 1598 } 1599 if (0 != auto) { 1600 return WordComposer.CAPS_MODE_AUTO_SHIFTED; 1601 } 1602 return WordComposer.CAPS_MODE_OFF; 1603 } 1604 1605 /** 1606 * Gets the current auto-caps state, factoring in the space state. 1607 * 1608 * This method tries its best to do this in the most efficient possible manner. It avoids 1609 * getting text from the editor if possible at all. 1610 * This is called from the KeyboardSwitcher (through a trampoline in LatinIME) because it 1611 * needs to know auto caps state to display the right layout. 1612 * 1613 * @param settingsValues the relevant settings values 1614 * @return a caps mode from TextUtils.CAP_MODE_* or Constants.TextUtils.CAP_MODE_OFF. 1615 */ 1616 public int getCurrentAutoCapsState(final SettingsValues settingsValues) { 1617 if (!settingsValues.mAutoCap) return Constants.TextUtils.CAP_MODE_OFF; 1618 1619 final EditorInfo ei = getCurrentInputEditorInfo(); 1620 if (ei == null) return Constants.TextUtils.CAP_MODE_OFF; 1621 final int inputType = ei.inputType; 1622 // Warning: this depends on mSpaceState, which may not be the most current value. If 1623 // mSpaceState gets updated later, whoever called this may need to be told about it. 1624 return mConnection.getCursorCapsMode(inputType, settingsValues.mSpacingAndPunctuations, 1625 SpaceState.PHANTOM == mSpaceState); 1626 } 1627 1628 public int getCurrentRecapitalizeState() { 1629 if (!mRecapitalizeStatus.isStarted() 1630 || !mRecapitalizeStatus.isSetAt(mConnection.getExpectedSelectionStart(), 1631 mConnection.getExpectedSelectionEnd())) { 1632 // Not recapitalizing at the moment 1633 return RecapitalizeStatus.NOT_A_RECAPITALIZE_MODE; 1634 } 1635 return mRecapitalizeStatus.getCurrentMode(); 1636 } 1637 1638 /** 1639 * @return the editor info for the current editor 1640 */ 1641 private EditorInfo getCurrentInputEditorInfo() { 1642 return mLatinIME.getCurrentInputEditorInfo(); 1643 } 1644 1645 /** 1646 * Get information fo previous words from the nth previous word before the cursor as context 1647 * for the suggestion process. 1648 * @param spacingAndPunctuations the current spacing and punctuations settings. 1649 * @param nthPreviousWord reverse index of the word to get (1-indexed) 1650 * @return the information of previous words 1651 */ 1652 // TODO: Make this private 1653 public PrevWordsInfo getPrevWordsInfoFromNthPreviousWordForSuggestion( 1654 final SpacingAndPunctuations spacingAndPunctuations, final int nthPreviousWord) { 1655 if (spacingAndPunctuations.mCurrentLanguageHasSpaces) { 1656 // If we are typing in a language with spaces we can just look up the previous 1657 // word information from textview. 1658 return mConnection.getPrevWordsInfoFromNthPreviousWord( 1659 spacingAndPunctuations, nthPreviousWord); 1660 } else { 1661 return LastComposedWord.NOT_A_COMPOSED_WORD == mLastComposedWord ? 1662 PrevWordsInfo.BEGINNING_OF_SENTENCE : 1663 new PrevWordsInfo(new PrevWordsInfo.WordInfo( 1664 mLastComposedWord.mCommittedWord.toString())); 1665 } 1666 } 1667 1668 /** 1669 * Tests the passed word for resumability. 1670 * 1671 * We can resume suggestions on words whose first code point is a word code point (with some 1672 * nuances: check the code for details). 1673 * 1674 * @param settings the current values of the settings. 1675 * @param word the word to evaluate. 1676 * @return whether it's fine to resume suggestions on this word. 1677 */ 1678 private static boolean isResumableWord(final SettingsValues settings, final String word) { 1679 final int firstCodePoint = word.codePointAt(0); 1680 return settings.isWordCodePoint(firstCodePoint) 1681 && Constants.CODE_SINGLE_QUOTE != firstCodePoint 1682 && Constants.CODE_DASH != firstCodePoint; 1683 } 1684 1685 /** 1686 * @param actionId the action to perform 1687 */ 1688 private void performEditorAction(final int actionId) { 1689 mConnection.performEditorAction(actionId); 1690 } 1691 1692 /** 1693 * Perform the processing specific to inputting TLDs. 1694 * 1695 * Some keys input a TLD (specifically, the ".com" key) and this warrants some specific 1696 * processing. First, if this is a TLD, we ignore PHANTOM spaces -- this is done by type 1697 * of character in onCodeInput, but since this gets inputted as a whole string we need to 1698 * do it here specifically. Then, if the last character before the cursor is a period, then 1699 * we cut the dot at the start of ".com". This is because humans tend to type "www.google." 1700 * and then press the ".com" key and instinctively don't expect to get "www.google..com". 1701 * 1702 * @param text the raw text supplied to onTextInput 1703 * @return the text to actually send to the editor 1704 */ 1705 private String performSpecificTldProcessingOnTextInput(final String text) { 1706 if (text.length() <= 1 || text.charAt(0) != Constants.CODE_PERIOD 1707 || !Character.isLetter(text.charAt(1))) { 1708 // Not a tld: do nothing. 1709 return text; 1710 } 1711 // We have a TLD (or something that looks like this): make sure we don't add 1712 // a space even if currently in phantom mode. 1713 mSpaceState = SpaceState.NONE; 1714 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 1715 // If no code point, #getCodePointBeforeCursor returns NOT_A_CODE_POINT. 1716 if (Constants.CODE_PERIOD == codePointBeforeCursor) { 1717 return text.substring(1); 1718 } else { 1719 return text; 1720 } 1721 } 1722 1723 /** 1724 * Handle a press on the settings key. 1725 */ 1726 private void onSettingsKeyPressed() { 1727 mLatinIME.displaySettingsDialog(); 1728 } 1729 1730 /** 1731 * Resets the whole input state to the starting state. 1732 * 1733 * This will clear the composing word, reset the last composed word, clear the suggestion 1734 * strip and tell the input connection about it so that it can refresh its caches. 1735 * 1736 * @param newSelStart the new selection start, in java characters. 1737 * @param newSelEnd the new selection end, in java characters. 1738 * @param clearSuggestionStrip whether this method should clear the suggestion strip. 1739 */ 1740 // TODO: how is this different from startInput ?! 1741 private void resetEntireInputState(final int newSelStart, final int newSelEnd, 1742 final boolean clearSuggestionStrip) { 1743 final boolean shouldFinishComposition = mWordComposer.isComposingWord(); 1744 resetComposingState(true /* alsoResetLastComposedWord */); 1745 if (clearSuggestionStrip) { 1746 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1747 } 1748 mConnection.resetCachesUponCursorMoveAndReturnSuccess(newSelStart, newSelEnd, 1749 shouldFinishComposition); 1750 } 1751 1752 /** 1753 * Resets only the composing state. 1754 * 1755 * Compare #resetEntireInputState, which also clears the suggestion strip and resets the 1756 * input connection caches. This only deals with the composing state. 1757 * 1758 * @param alsoResetLastComposedWord whether to also reset the last composed word. 1759 */ 1760 private void resetComposingState(final boolean alsoResetLastComposedWord) { 1761 mWordComposer.reset(); 1762 if (alsoResetLastComposedWord) { 1763 mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 1764 } 1765 } 1766 1767 /** 1768 * Make a {@link com.android.inputmethod.latin.SuggestedWords} object containing a typed word 1769 * and obsolete suggestions. 1770 * See {@link com.android.inputmethod.latin.SuggestedWords#getTypedWordAndPreviousSuggestions( 1771 * String, com.android.inputmethod.latin.SuggestedWords)}. 1772 * @param typedWord The typed word as a string. 1773 * @param previousSuggestedWords The previously suggested words. 1774 * @return Obsolete suggestions with the newly typed word. 1775 */ 1776 private SuggestedWords retrieveOlderSuggestions(final String typedWord, 1777 final SuggestedWords previousSuggestedWords) { 1778 final SuggestedWords oldSuggestedWords = 1779 previousSuggestedWords.isPunctuationSuggestions() ? SuggestedWords.EMPTY 1780 : previousSuggestedWords; 1781 final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions = 1782 SuggestedWords.getTypedWordAndPreviousSuggestions(typedWord, oldSuggestedWords); 1783 return new SuggestedWords(typedWordAndPreviousSuggestions, null /* rawSuggestions */, 1784 false /* typedWordValid */, false /* hasAutoCorrectionCandidate */, 1785 true /* isObsoleteSuggestions */, false /* isPrediction */, 1786 oldSuggestedWords.mInputStyle); 1787 } 1788 1789 /** 1790 * Gets a chunk of text with or the auto-correction indicator underline span as appropriate. 1791 * 1792 * This method looks at the old state of the auto-correction indicator to put or not put 1793 * the underline span as appropriate. It is important to note that this does not correspond 1794 * exactly to whether this word will be auto-corrected to or not: what's important here is 1795 * to keep the same indication as before. 1796 * When we add a new code point to a composing word, we don't know yet if we are going to 1797 * auto-correct it until the suggestions are computed. But in the mean time, we still need 1798 * to display the character and to extend the previous underline. To avoid any flickering, 1799 * the underline should keep the same color it used to have, even if that's not ultimately 1800 * the correct color for this new word. When the suggestions are finished evaluating, we 1801 * will call this method again to fix the color of the underline. 1802 * 1803 * @param text the text on which to maybe apply the span. 1804 * @return the same text, with the auto-correction underline span if that's appropriate. 1805 */ 1806 // TODO: Shouldn't this go in some *Utils class instead? 1807 private CharSequence getTextWithUnderline(final String text) { 1808 return mIsAutoCorrectionIndicatorOn 1809 ? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(mLatinIME, text) 1810 : text; 1811 } 1812 1813 /** 1814 * Sends a DOWN key event followed by an UP key event to the editor. 1815 * 1816 * If possible at all, avoid using this method. It causes all sorts of race conditions with 1817 * the text view because it goes through a different, asynchronous binder. Also, batch edits 1818 * are ignored for key events. Use the normal software input methods instead. 1819 * 1820 * @param keyCode the key code to send inside the key event. 1821 */ 1822 private void sendDownUpKeyEvent(final int keyCode) { 1823 final long eventTime = SystemClock.uptimeMillis(); 1824 mConnection.sendKeyEvent(new KeyEvent(eventTime, eventTime, 1825 KeyEvent.ACTION_DOWN, keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 1826 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); 1827 mConnection.sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime, 1828 KeyEvent.ACTION_UP, keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 1829 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); 1830 } 1831 1832 /** 1833 * Sends a code point to the editor, using the most appropriate method. 1834 * 1835 * Normally we send code points with commitText, but there are some cases (where backward 1836 * compatibility is a concern for example) where we want to use deprecated methods. 1837 * 1838 * @param settingsValues the current values of the settings. 1839 * @param codePoint the code point to send. 1840 */ 1841 // TODO: replace these two parameters with an InputTransaction 1842 private void sendKeyCodePoint(final SettingsValues settingsValues, final int codePoint) { 1843 // TODO: Remove this special handling of digit letters. 1844 // For backward compatibility. See {@link InputMethodService#sendKeyChar(char)}. 1845 if (codePoint >= '0' && codePoint <= '9') { 1846 sendDownUpKeyEvent(codePoint - '0' + KeyEvent.KEYCODE_0); 1847 return; 1848 } 1849 1850 // TODO: we should do this also when the editor has TYPE_NULL 1851 if (Constants.CODE_ENTER == codePoint && settingsValues.isBeforeJellyBean()) { 1852 // Backward compatibility mode. Before Jelly bean, the keyboard would simulate 1853 // a hardware keyboard event on pressing enter or delete. This is bad for many 1854 // reasons (there are race conditions with commits) but some applications are 1855 // relying on this behavior so we continue to support it for older apps. 1856 sendDownUpKeyEvent(KeyEvent.KEYCODE_ENTER); 1857 } else { 1858 mConnection.commitText(StringUtils.newSingleCodePointString(codePoint), 1); 1859 } 1860 } 1861 1862 /** 1863 * Promote a phantom space to an actual space. 1864 * 1865 * This essentially inserts a space, and that's it. It just checks the options and the text 1866 * before the cursor are appropriate before doing it. 1867 * 1868 * @param settingsValues the current values of the settings. 1869 */ 1870 private void promotePhantomSpace(final SettingsValues settingsValues) { 1871 if (settingsValues.shouldInsertSpacesAutomatically() 1872 && settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces 1873 && !mConnection.textBeforeCursorLooksLikeURL()) { 1874 sendKeyCodePoint(settingsValues, Constants.CODE_SPACE); 1875 } 1876 } 1877 1878 /** 1879 * Do the final processing after a batch input has ended. This commits the word to the editor. 1880 * @param settingsValues the current values of the settings. 1881 * @param suggestedWords suggestedWords to use. 1882 */ 1883 public void onUpdateTailBatchInputCompleted(final SettingsValues settingsValues, 1884 final SuggestedWords suggestedWords, 1885 // TODO: remove this argument 1886 final KeyboardSwitcher keyboardSwitcher) { 1887 final String batchInputText = suggestedWords.isEmpty() ? null : suggestedWords.getWord(0); 1888 if (TextUtils.isEmpty(batchInputText)) { 1889 return; 1890 } 1891 mConnection.beginBatchEdit(); 1892 if (SpaceState.PHANTOM == mSpaceState) { 1893 promotePhantomSpace(settingsValues); 1894 } 1895 final SuggestedWordInfo autoCommitCandidate = mSuggestedWords.getAutoCommitCandidate(); 1896 // Commit except the last word for phrase gesture if the top suggestion is eligible for auto 1897 // commit. 1898 if (settingsValues.mPhraseGestureEnabled && null != autoCommitCandidate) { 1899 // Find the last space 1900 final int indexOfLastSpace = batchInputText.lastIndexOf(Constants.CODE_SPACE) + 1; 1901 if (0 != indexOfLastSpace) { 1902 mConnection.commitText(batchInputText.substring(0, indexOfLastSpace), 1); 1903 final SuggestedWords suggestedWordsForLastWordOfPhraseGesture = 1904 suggestedWords.getSuggestedWordsForLastWordOfPhraseGesture(); 1905 mLatinIME.showSuggestionStrip(suggestedWordsForLastWordOfPhraseGesture); 1906 } 1907 final String lastWord = batchInputText.substring(indexOfLastSpace); 1908 mWordComposer.setBatchInputWord(lastWord); 1909 mConnection.setComposingText(lastWord, 1); 1910 } else { 1911 mWordComposer.setBatchInputWord(batchInputText); 1912 mConnection.setComposingText(batchInputText, 1); 1913 } 1914 mConnection.endBatchEdit(); 1915 // Space state must be updated before calling updateShiftState 1916 mSpaceState = SpaceState.PHANTOM; 1917 keyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(settingsValues), 1918 getCurrentRecapitalizeState()); 1919 } 1920 1921 /** 1922 * Commit the typed string to the editor. 1923 * 1924 * This is typically called when we should commit the currently composing word without applying 1925 * auto-correction to it. Typically, we come here upon pressing a separator when the keyboard 1926 * is configured to not do auto-correction at all (because of the settings or the properties of 1927 * the editor). In this case, `separatorString' is set to the separator that was pressed. 1928 * We also come here in a variety of cases with external user action. For example, when the 1929 * cursor is moved while there is a composition, or when the keyboard is closed, or when the 1930 * user presses the Send button for an SMS, we don't auto-correct as that would be unexpected. 1931 * In this case, `separatorString' is set to NOT_A_SEPARATOR. 1932 * 1933 * @param settingsValues the current values of the settings. 1934 * @param separatorString the separator that's causing the commit, or NOT_A_SEPARATOR if none. 1935 */ 1936 // TODO: Make this private 1937 public void commitTyped(final SettingsValues settingsValues, final String separatorString) { 1938 if (!mWordComposer.isComposingWord()) return; 1939 final String typedWord = mWordComposer.getTypedWord(); 1940 if (typedWord.length() > 0) { 1941 commitChosenWord(settingsValues, typedWord, 1942 LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD, separatorString); 1943 } 1944 } 1945 1946 /** 1947 * Commit the current auto-correction. 1948 * 1949 * This will commit the best guess of the keyboard regarding what the user meant by typing 1950 * the currently composing word. The IME computes suggestions and assigns a confidence score 1951 * to each of them; when it's confident enough in one suggestion, it replaces the typed string 1952 * by this suggestion at commit time. When it's not confident enough, or when it has no 1953 * suggestions, or when the settings or environment does not allow for auto-correction, then 1954 * this method just commits the typed string. 1955 * Note that if suggestions are currently being computed in the background, this method will 1956 * block until the computation returns. This is necessary for consistency (it would be very 1957 * strange if pressing space would commit a different word depending on how fast you press). 1958 * 1959 * @param settingsValues the current value of the settings. 1960 * @param separator the separator that's causing the commit to happen. 1961 */ 1962 private void commitCurrentAutoCorrection(final SettingsValues settingsValues, 1963 final String separator, 1964 // TODO: Remove this argument. 1965 final LatinIME.UIHandler handler) { 1966 // Complete any pending suggestions query first 1967 if (handler.hasPendingUpdateSuggestions()) { 1968 handler.cancelUpdateSuggestionStrip(); 1969 // To know the input style here, we should retrieve the in-flight "update suggestions" 1970 // message and read its arg1 member here. However, the Handler class does not let 1971 // us retrieve this message, so we can't do that. But in fact, we notice that 1972 // we only ever come here when the input style was typing. In the case of batch 1973 // input, we update the suggestions synchronously when the tail batch comes. Likewise 1974 // for application-specified completions. As for recorrections, we never auto-correct, 1975 // so we don't come here either. Hence, the input style is necessarily 1976 // INPUT_STYLE_TYPING. 1977 performUpdateSuggestionStripSync(settingsValues, SuggestedWords.INPUT_STYLE_TYPING); 1978 } 1979 final String typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull(); 1980 final String typedWord = mWordComposer.getTypedWord(); 1981 final String autoCorrection = (typedAutoCorrection != null) 1982 ? typedAutoCorrection : typedWord; 1983 if (autoCorrection != null) { 1984 if (TextUtils.isEmpty(typedWord)) { 1985 throw new RuntimeException("We have an auto-correction but the typed word " 1986 + "is empty? Impossible! I must commit suicide."); 1987 } 1988 commitChosenWord(settingsValues, autoCorrection, 1989 LastComposedWord.COMMIT_TYPE_DECIDED_WORD, separator); 1990 if (!typedWord.equals(autoCorrection)) { 1991 // This will make the correction flash for a short while as a visual clue 1992 // to the user that auto-correction happened. It has no other effect; in particular 1993 // note that this won't affect the text inside the text field AT ALL: it only makes 1994 // the segment of text starting at the supplied index and running for the length 1995 // of the auto-correction flash. At this moment, the "typedWord" argument is 1996 // ignored by TextView. 1997 mConnection.commitCorrection(new CorrectionInfo( 1998 mConnection.getExpectedSelectionEnd() - autoCorrection.length(), 1999 typedWord, autoCorrection)); 2000 } 2001 } 2002 } 2003 2004 /** 2005 * Commits the chosen word to the text field and saves it for later retrieval. This is a 2006 * synonym of {@code commitChosenWordWithBackgroundColor(settingsValues, chosenWord, 2007 * commitType, separatorString, Color.TRANSPARENT}. 2008 * 2009 * @param settingsValues the current values of the settings. 2010 * @param chosenWord the word we want to commit. 2011 * @param commitType the type of the commit, as one of LastComposedWord.COMMIT_TYPE_* 2012 * @param separatorString the separator that's causing the commit, or NOT_A_SEPARATOR if none. 2013 */ 2014 private void commitChosenWord(final SettingsValues settingsValues, final String chosenWord, 2015 final int commitType, final String separatorString) { 2016 commitChosenWordWithBackgroundColor(settingsValues, chosenWord, commitType, separatorString, 2017 Color.TRANSPARENT); 2018 } 2019 2020 /** 2021 * Commits the chosen word to the text field and saves it for later retrieval. 2022 * 2023 * @param settingsValues the current values of the settings. 2024 * @param chosenWord the word we want to commit. 2025 * @param commitType the type of the commit, as one of LastComposedWord.COMMIT_TYPE_* 2026 * @param separatorString the separator that's causing the commit, or NOT_A_SEPARATOR if none. 2027 * @param backgroundColor the background color to be specified with the committed text. Pass 2028 * {@link Color#TRANSPARENT} to not specify the background color. 2029 */ 2030 private void commitChosenWordWithBackgroundColor(final SettingsValues settingsValues, 2031 final String chosenWord, final int commitType, final String separatorString, 2032 final int backgroundColor) { 2033 final SuggestedWords suggestedWords = mSuggestedWords; 2034 final CharSequence chosenWordWithSuggestions = 2035 SuggestionSpanUtils.getTextWithSuggestionSpan(mLatinIME, chosenWord, 2036 suggestedWords); 2037 // When we are composing word, get previous words information from the 2nd previous word 2038 // because the 1st previous word is the word to be committed. Otherwise get previous words 2039 // information from the 1st previous word. 2040 final PrevWordsInfo prevWordsInfo = mConnection.getPrevWordsInfoFromNthPreviousWord( 2041 settingsValues.mSpacingAndPunctuations, mWordComposer.isComposingWord() ? 2 : 1); 2042 mConnection.commitTextWithBackgroundColor(chosenWordWithSuggestions, 1, backgroundColor); 2043 // Add the word to the user history dictionary 2044 performAdditionToUserHistoryDictionary(settingsValues, chosenWord, prevWordsInfo); 2045 // TODO: figure out here if this is an auto-correct or if the best word is actually 2046 // what user typed. Note: currently this is done much later in 2047 // LastComposedWord#didCommitTypedWord by string equality of the remembered 2048 // strings. 2049 mLastComposedWord = mWordComposer.commitWord(commitType, 2050 chosenWordWithSuggestions, separatorString, prevWordsInfo); 2051 } 2052 2053 /** 2054 * Retry resetting caches in the rich input connection. 2055 * 2056 * When the editor can't be accessed we can't reset the caches, so we schedule a retry. 2057 * This method handles the retry, and re-schedules a new retry if we still can't access. 2058 * We only retry up to 5 times before giving up. 2059 * 2060 * @param tryResumeSuggestions Whether we should resume suggestions or not. 2061 * @param remainingTries How many times we may try again before giving up. 2062 * @return whether true if the caches were successfully reset, false otherwise. 2063 */ 2064 // TODO: make this private 2065 public boolean retryResetCachesAndReturnSuccess(final boolean tryResumeSuggestions, 2066 final int remainingTries, 2067 // TODO: remove these arguments 2068 final LatinIME.UIHandler handler) { 2069 final boolean shouldFinishComposition = mConnection.hasSelection() 2070 || !mConnection.isCursorPositionKnown(); 2071 if (!mConnection.resetCachesUponCursorMoveAndReturnSuccess( 2072 mConnection.getExpectedSelectionStart(), mConnection.getExpectedSelectionEnd(), 2073 shouldFinishComposition)) { 2074 if (0 < remainingTries) { 2075 handler.postResetCaches(tryResumeSuggestions, remainingTries - 1); 2076 return false; 2077 } 2078 // If remainingTries is 0, we should stop waiting for new tries, however we'll still 2079 // return true as we need to perform other tasks (for example, loading the keyboard). 2080 } 2081 mConnection.tryFixLyingCursorPosition(); 2082 if (tryResumeSuggestions) { 2083 // This is triggered when starting input anew, so we want to include the resumed 2084 // word in suggestions. 2085 handler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */, 2086 true /* shouldDelay */); 2087 } 2088 return true; 2089 } 2090 2091 public void getSuggestedWords(final SettingsValues settingsValues, 2092 final ProximityInfo proximityInfo, final int keyboardShiftMode, final int inputStyle, 2093 final int sequenceNumber, final OnGetSuggestedWordsCallback callback) { 2094 mWordComposer.adviseCapitalizedModeBeforeFetchingSuggestions( 2095 getActualCapsMode(settingsValues, keyboardShiftMode)); 2096 mSuggest.getSuggestedWords(mWordComposer, 2097 getPrevWordsInfoFromNthPreviousWordForSuggestion( 2098 settingsValues.mSpacingAndPunctuations, 2099 // Get the word on which we should search the bigrams. If we are composing 2100 // a word, it's whatever is *before* the half-committed word in the buffer, 2101 // hence 2; if we aren't, we should just skip whitespace if any, so 1. 2102 mWordComposer.isComposingWord() ? 2 : 1), 2103 proximityInfo, 2104 new SettingsValuesForSuggestion(settingsValues.mBlockPotentiallyOffensive, 2105 settingsValues.mPhraseGestureEnabled, 2106 settingsValues.mAdditionalFeaturesSettingValues), 2107 settingsValues.mAutoCorrectionEnabledPerUserSettings, 2108 inputStyle, sequenceNumber, callback); 2109 } 2110} 2111