formatting, remove unused functionality

This commit is contained in:
Helium314 2023-09-17 12:55:59 +02:00
parent 7b9ba8d60e
commit 67c328ec1f
3 changed files with 70 additions and 155 deletions

View file

@ -233,9 +233,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
private static final int MSG_RESET_CACHES = 7; private static final int MSG_RESET_CACHES = 7;
private static final int MSG_WAIT_FOR_DICTIONARY_LOAD = 8; private static final int MSG_WAIT_FOR_DICTIONARY_LOAD = 8;
private static final int MSG_DEALLOCATE_MEMORY = 9; private static final int MSG_DEALLOCATE_MEMORY = 9;
private static final int MSG_RESUME_SUGGESTIONS_FOR_START_INPUT = 10; private static final int MSG_SWITCH_LANGUAGE_AUTOMATICALLY = 10;
private static final int MSG_SWITCH_LANGUAGE_AUTOMATICALLY = 11; private static final int MSG_UPDATE_CLIPBOARD_PINNED_CLIPS = 11;
private static final int MSG_UPDATE_CLIPBOARD_PINNED_CLIPS = 12;
// Update this when adding new messages // Update this when adding new messages
private static final int MSG_LAST = MSG_UPDATE_CLIPBOARD_PINNED_CLIPS; private static final int MSG_LAST = MSG_UPDATE_CLIPBOARD_PINNED_CLIPS;
@ -291,12 +290,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
break; break;
case MSG_RESUME_SUGGESTIONS: case MSG_RESUME_SUGGESTIONS:
latinIme.mInputLogic.restartSuggestionsOnWordTouchedByCursor( latinIme.mInputLogic.restartSuggestionsOnWordTouchedByCursor(
latinIme.mSettings.getCurrent(), false /* forStartInput */, latinIme.mSettings.getCurrent(),
latinIme.mKeyboardSwitcher.getCurrentKeyboardScriptId());
break;
case MSG_RESUME_SUGGESTIONS_FOR_START_INPUT:
latinIme.mInputLogic.restartSuggestionsOnWordTouchedByCursor(
latinIme.mSettings.getCurrent(), true /* forStartInput */,
latinIme.mKeyboardSwitcher.getCurrentKeyboardScriptId()); latinIme.mKeyboardSwitcher.getCurrentKeyboardScriptId());
break; break;
case MSG_REOPEN_DICTIONARIES: case MSG_REOPEN_DICTIONARIES:
@ -350,8 +344,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
sendMessage(obtainMessage(MSG_REOPEN_DICTIONARIES)); sendMessage(obtainMessage(MSG_REOPEN_DICTIONARIES));
} }
private void postResumeSuggestionsInternal(final boolean shouldDelay, public void postResumeSuggestions(final boolean shouldDelay) {
final boolean forStartInput) {
final LatinIME latinIme = getOwnerInstance(); final LatinIME latinIme = getOwnerInstance();
if (latinIme == null) { if (latinIme == null) {
return; return;
@ -360,9 +353,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
return; return;
} }
removeMessages(MSG_RESUME_SUGGESTIONS); removeMessages(MSG_RESUME_SUGGESTIONS);
removeMessages(MSG_RESUME_SUGGESTIONS_FOR_START_INPUT); final int message = MSG_RESUME_SUGGESTIONS;
final int message = forStartInput ? MSG_RESUME_SUGGESTIONS_FOR_START_INPUT
: MSG_RESUME_SUGGESTIONS;
if (shouldDelay) { if (shouldDelay) {
sendMessageDelayed(obtainMessage(message), sendMessageDelayed(obtainMessage(message),
mDelayInMillisecondsToUpdateSuggestions); mDelayInMillisecondsToUpdateSuggestions);
@ -371,14 +362,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
} }
} }
public void postResumeSuggestions(final boolean shouldDelay) {
postResumeSuggestionsInternal(shouldDelay, false /* forStartInput */);
}
public void postResumeSuggestionsForStartInput(final boolean shouldDelay) {
postResumeSuggestionsInternal(shouldDelay, true /* forStartInput */);
}
public void postResetCaches(final boolean tryResumeSuggestions, final int remainingTries) { public void postResetCaches(final boolean tryResumeSuggestions, final int remainingTries) {
removeMessages(MSG_RESET_CACHES); removeMessages(MSG_RESET_CACHES);
sendMessage(obtainMessage(MSG_RESET_CACHES, tryResumeSuggestions ? 1 : 0, sendMessage(obtainMessage(MSG_RESET_CACHES, tryResumeSuggestions ? 1 : 0,
@ -1048,7 +1031,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
// initialSelStart and initialSelEnd sometimes are lying. Make a best effort to // initialSelStart and initialSelEnd sometimes are lying. Make a best effort to
// work around this bug. // work around this bug.
mInputLogic.mConnection.tryFixLyingCursorPosition(); mInputLogic.mConnection.tryFixLyingCursorPosition();
mHandler.postResumeSuggestionsForStartInput(true /* shouldDelay */); mHandler.postResumeSuggestions(true /* shouldDelay */);
needToCallLoadKeyboardLater = false; needToCallLoadKeyboardLater = false;
} }
} else { } else {
@ -1445,8 +1428,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
int newPosition = mInputLogic.mConnection.mExpectedSelStart + steps; int newPosition = mInputLogic.mConnection.mExpectedSelStart + steps;
mInputLogic.mConnection.setSelection(newPosition, newPosition); mInputLogic.mConnection.setSelection(newPosition, newPosition);
mInputLogic.restartSuggestionsOnWordTouchedByCursor(mSettings.getCurrent(), mInputLogic.restartSuggestionsOnWordTouchedByCursor(mSettings.getCurrent(), mKeyboardSwitcher.getCurrentKeyboardScriptId());
false, mKeyboardSwitcher.getCurrentKeyboardScriptId());
} }
@Override @Override

View file

@ -1044,19 +1044,6 @@ public final class RichInputConnection implements PrivateCommandPerformer {
return INVALID_CURSOR_POSITION != mExpectedSelStart; return INVALID_CURSOR_POSITION != mExpectedSelStart;
} }
/**
* Work around a bug that was present before Jelly Bean upon rotation.
*
* Before Jelly Bean, there is a bug where setComposingRegion and other committing
* functions on the input connection get ignored until the cursor moves. This method works
* around the bug by wiggling the cursor first, which reactivates the connection and has
* the subsequent methods work, then restoring it to its original position.
*
* On platforms on which this method is not present, this is a no-op.
*/
public void maybeMoveTheCursorAroundAndRestoreToWorkaroundABug() {
}
/** /**
* Requests the editor to call back {@link InputMethodManager#updateCursorAnchorInfo}. * Requests the editor to call back {@link InputMethodManager#updateCursorAnchorInfo}.
* @param enableMonitor {@code true} to request the editor to call back the method whenever the * @param enableMonitor {@code true} to request the editor to call back the method whenever the

View file

@ -207,8 +207,7 @@ public final class InputLogic {
public void finishInput() { public void finishInput() {
if (mWordComposer.isComposingWord()) { if (mWordComposer.isComposingWord()) {
mConnection.finishComposingText(); mConnection.finishComposingText();
StatsUtils.onWordCommitUserTyped( StatsUtils.onWordCommitUserTyped(mWordComposer.getTypedWord(), mWordComposer.isBatchMode());
mWordComposer.getTypedWord(), mWordComposer.isBatchMode());
} }
resetComposingState(true /* alsoResetLastComposedWord */); resetComposingState(true /* alsoResetLastComposedWord */);
mInputLogicHandler.reset(); mInputLogicHandler.reset();
@ -282,13 +281,11 @@ public final class InputLogic {
// If this is a punctuation picked from the suggestion strip, pass it to onCodeInput // If this is a punctuation picked from the suggestion strip, pass it to onCodeInput
if (suggestion.length() == 1 && suggestedWords.isPunctuationSuggestions()) { if (suggestion.length() == 1 && suggestedWords.isPunctuationSuggestions()) {
// We still want to log a suggestion click. // We still want to log a suggestion click.
StatsUtils.onPickSuggestionManually( StatsUtils.onPickSuggestionManually(mSuggestedWords, suggestionInfo, mDictionaryFacilitator);
mSuggestedWords, suggestionInfo, mDictionaryFacilitator);
// Word separators are suggested before the user inputs something. // Word separators are suggested before the user inputs something.
// Rely on onCodeInput to do the complicated swapping/stripping logic consistently. // Rely on onCodeInput to do the complicated swapping/stripping logic consistently.
final Event event = Event.createPunctuationSuggestionPickedEvent(suggestionInfo); final Event event = Event.createPunctuationSuggestionPickedEvent(suggestionInfo);
return onCodeInput(settingsValues, event, keyboardShiftState, return onCodeInput(settingsValues, event, keyboardShiftState, currentKeyboardScriptId, handler);
currentKeyboardScriptId, handler);
} }
final Event event = Event.createSuggestionPickedEvent(suggestionInfo); final Event event = Event.createSuggestionPickedEvent(suggestionInfo);
@ -327,8 +324,7 @@ public final class InputLogic {
return inputTransaction; return inputTransaction;
} }
commitChosenWord(settingsValues, suggestion, LastComposedWord.COMMIT_TYPE_MANUAL_PICK, commitChosenWord(settingsValues, suggestion, LastComposedWord.COMMIT_TYPE_MANUAL_PICK, LastComposedWord.NOT_A_SEPARATOR);
LastComposedWord.NOT_A_SEPARATOR);
mConnection.endBatchEdit(); mConnection.endBatchEdit();
// Don't allow cancellation of manual pick // Don't allow cancellation of manual pick
mLastComposedWord.deactivate(); mLastComposedWord.deactivate();
@ -340,10 +336,8 @@ public final class InputLogic {
// That's going to be predictions (or punctuation suggestions), so INPUT_STYLE_NONE. // That's going to be predictions (or punctuation suggestions), so INPUT_STYLE_NONE.
handler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_NONE); handler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_NONE);
StatsUtils.onPickSuggestionManually( StatsUtils.onPickSuggestionManually(mSuggestedWords, suggestionInfo, mDictionaryFacilitator);
mSuggestedWords, suggestionInfo, mDictionaryFacilitator); StatsUtils.onWordCommitSuggestionPickedManually(suggestionInfo.mWord, mWordComposer.isBatchMode());
StatsUtils.onWordCommitSuggestionPickedManually(
suggestionInfo.mWord, mWordComposer.isBatchMode());
return inputTransaction; return inputTransaction;
} }
@ -405,8 +399,6 @@ public final class InputLogic {
// If the user is in the middle of correcting a word, we should learn it before moving // If the user is in the middle of correcting a word, we should learn it before moving
// the cursor away. // the cursor away.
if (!TextUtils.isEmpty(mWordBeingCorrectedByCursor)) { if (!TextUtils.isEmpty(mWordBeingCorrectedByCursor)) {
final int timeStampInSeconds = (int)TimeUnit.MILLISECONDS.toSeconds(
System.currentTimeMillis());
performAdditionToUserHistoryDictionary(settingsValues, mWordBeingCorrectedByCursor, performAdditionToUserHistoryDictionary(settingsValues, mWordBeingCorrectedByCursor,
NgramContext.EMPTY_PREV_WORDS_INFO); NgramContext.EMPTY_PREV_WORDS_INFO);
} }
@ -484,8 +476,7 @@ public final class InputLogic {
if (currentEvent.isConsumed()) { if (currentEvent.isConsumed()) {
handleConsumedEvent(currentEvent, inputTransaction); handleConsumedEvent(currentEvent, inputTransaction);
} else if (currentEvent.isFunctionalKeyEvent()) { } else if (currentEvent.isFunctionalKeyEvent()) {
handleFunctionalEvent(currentEvent, inputTransaction, currentKeyboardScriptId, handleFunctionalEvent(currentEvent, inputTransaction, currentKeyboardScriptId, handler);
handler);
} else { } else {
handleNonFunctionalEvent(currentEvent, inputTransaction, handler); handleNonFunctionalEvent(currentEvent, inputTransaction, handler);
} }
@ -494,10 +485,10 @@ public final class InputLogic {
// Try to record the word being corrected when the user enters a word character or // Try to record the word being corrected when the user enters a word character or
// the backspace key. // the backspace key.
if (!mConnection.hasSlowInputConnection() && !mWordComposer.isComposingWord() if (!mConnection.hasSlowInputConnection() && !mWordComposer.isComposingWord()
&& (settingsValues.isWordCodePoint(processedEvent.getMCodePoint()) || && (settingsValues.isWordCodePoint(processedEvent.getMCodePoint())
processedEvent.getMKeyCode() == Constants.CODE_DELETE)) { || processedEvent.getMKeyCode() == Constants.CODE_DELETE)
mWordBeingCorrectedByCursor = getWordAtCursor( ) {
settingsValues, currentKeyboardScriptId); mWordBeingCorrectedByCursor = getWordAtCursor(settingsValues, currentKeyboardScriptId);
} }
if (!inputTransaction.didAutoCorrect() && processedEvent.getMKeyCode() != Constants.CODE_SHIFT if (!inputTransaction.didAutoCorrect() && processedEvent.getMKeyCode() != Constants.CODE_SHIFT
&& processedEvent.getMKeyCode() != Constants.CODE_CAPSLOCK && processedEvent.getMKeyCode() != Constants.CODE_CAPSLOCK
@ -784,8 +775,7 @@ public final class InputLogic {
switch (event.getMCodePoint()) { switch (event.getMCodePoint()) {
case Constants.CODE_ENTER: case Constants.CODE_ENTER:
final EditorInfo editorInfo = getCurrentInputEditorInfo(); final EditorInfo editorInfo = getCurrentInputEditorInfo();
final int imeOptionsActionId = final int imeOptionsActionId = InputTypeUtils.getImeOptionsActionIdFromEditorInfo(editorInfo);
InputTypeUtils.getImeOptionsActionIdFromEditorInfo(editorInfo);
if (InputTypeUtils.IME_ACTION_CUSTOM_LABEL == imeOptionsActionId) { if (InputTypeUtils.IME_ACTION_CUSTOM_LABEL == imeOptionsActionId) {
// Either we have an actionLabel and we should performEditorAction with // Either we have an actionLabel and we should performEditorAction with
// actionId regardless of its value. // actionId regardless of its value.
@ -836,8 +826,7 @@ public final class InputLogic {
// If we are in the middle of a recorrection, we need to commit the recorrection // If we are in the middle of a recorrection, we need to commit the recorrection
// first so that we can insert the character at the current cursor position. // first so that we can insert the character at the current cursor position.
// We also need to unlearn the original word that is now being corrected. // We also need to unlearn the original word that is now being corrected.
unlearnWord(mWordComposer.getTypedWord(), inputTransaction.getMSettingsValues(), unlearnWord(mWordComposer.getTypedWord(), inputTransaction.getMSettingsValues(), Constants.EVENT_BACKSPACE);
Constants.EVENT_BACKSPACE);
resetEntireInputState(mConnection.getExpectedSelectionStart(), resetEntireInputState(mConnection.getExpectedSelectionStart(),
mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */);
} else { } else {
@ -878,8 +867,7 @@ public final class InputLogic {
// If we are in the middle of a recorrection, we need to commit the recorrection // If we are in the middle of a recorrection, we need to commit the recorrection
// first so that we can insert the character at the current cursor position. // first so that we can insert the character at the current cursor position.
// We also need to unlearn the original word that is now being corrected. // We also need to unlearn the original word that is now being corrected.
unlearnWord(mWordComposer.getTypedWord(), inputTransaction.getMSettingsValues(), unlearnWord(mWordComposer.getTypedWord(), inputTransaction.getMSettingsValues(), Constants.EVENT_BACKSPACE);
Constants.EVENT_BACKSPACE);
resetEntireInputState(mConnection.getExpectedSelectionStart(), resetEntireInputState(mConnection.getExpectedSelectionStart(),
mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */);
isComposingWord = false; isComposingWord = false;
@ -923,8 +911,7 @@ public final class InputLogic {
} }
setComposingTextInternal(getTextWithUnderline(mWordComposer.getTypedWord()), 1); setComposingTextInternal(getTextWithUnderline(mWordComposer.getTypedWord()), 1);
} else { } else {
final boolean swapWeakSpace = tryStripSpaceAndReturnWhetherShouldSwapInstead(event, final boolean swapWeakSpace = tryStripSpaceAndReturnWhetherShouldSwapInstead(event, inputTransaction);
inputTransaction);
if (swapWeakSpace && trySwapSwapperAndSpace(event, inputTransaction)) { if (swapWeakSpace && trySwapSwapperAndSpace(event, inputTransaction)) {
mSpaceState = SpaceState.WEAK; mSpaceState = SpaceState.WEAK;
@ -953,8 +940,7 @@ public final class InputLogic {
// If we are in the middle of a recorrection, we need to commit the recorrection // If we are in the middle of a recorrection, we need to commit the recorrection
// first so that we can insert the separator at the current cursor position. // first so that we can insert the separator at the current cursor position.
// We also need to unlearn the original word that is now being corrected. // We also need to unlearn the original word that is now being corrected.
unlearnWord(mWordComposer.getTypedWord(), inputTransaction.getMSettingsValues(), unlearnWord(mWordComposer.getTypedWord(), inputTransaction.getMSettingsValues(), Constants.EVENT_BACKSPACE);
Constants.EVENT_BACKSPACE);
resetEntireInputState(mConnection.getExpectedSelectionStart(), resetEntireInputState(mConnection.getExpectedSelectionStart(),
mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */);
} }
@ -966,13 +952,11 @@ public final class InputLogic {
commitCurrentAutoCorrection(settingsValues, separator, handler); commitCurrentAutoCorrection(settingsValues, separator, handler);
inputTransaction.setDidAutoCorrect(); inputTransaction.setDidAutoCorrect();
} else { } else {
commitTyped(settingsValues, commitTyped(settingsValues, StringUtils.newSingleCodePointString(codePoint));
StringUtils.newSingleCodePointString(codePoint));
} }
} }
final boolean swapWeakSpace = tryStripSpaceAndReturnWhetherShouldSwapInstead(event, final boolean swapWeakSpace = tryStripSpaceAndReturnWhetherShouldSwapInstead(event, inputTransaction);
inputTransaction);
final boolean isInsideDoubleQuoteOrAfterDigit = Constants.CODE_DOUBLE_QUOTE == codePoint final boolean isInsideDoubleQuoteOrAfterDigit = Constants.CODE_DOUBLE_QUOTE == codePoint
&& mConnection.isInsideDoubleQuoteOrAfterDigit(); && mConnection.isInsideDoubleQuoteOrAfterDigit();
@ -1072,9 +1056,9 @@ public final class InputLogic {
// shift state should be updated, so if this is a key repeat, we update after a small delay. // shift state should be updated, so if this is a key repeat, we update after a small delay.
// Then again, even in the case of a key repeat, if the cursor is at start of text, it // Then again, even in the case of a key repeat, if the cursor is at start of text, it
// can't go any further back, so we can update right away even if it's a key repeat. // can't go any further back, so we can update right away even if it's a key repeat.
final int shiftUpdateKind = final int shiftUpdateKind = event.isKeyRepeat() && mConnection.getExpectedSelectionStart() > 0
event.isKeyRepeat() && mConnection.getExpectedSelectionStart() > 0 ? InputTransaction.SHIFT_UPDATE_LATER
? InputTransaction.SHIFT_UPDATE_LATER : InputTransaction.SHIFT_UPDATE_NOW; : InputTransaction.SHIFT_UPDATE_NOW;
inputTransaction.requireShiftUpdate(shiftUpdateKind); inputTransaction.requireShiftUpdate(shiftUpdateKind);
if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) {
@ -1110,7 +1094,7 @@ public final class InputLogic {
} else { } else {
if (mLastComposedWord.canRevertCommit()) { if (mLastComposedWord.canRevertCommit()) {
final String lastComposedWord = mLastComposedWord.mTypedWord; final String lastComposedWord = mLastComposedWord.mTypedWord;
revertCommit(inputTransaction, inputTransaction.getMSettingsValues()); revertCommit(inputTransaction);
StatsUtils.onRevertAutoCorrect(); StatsUtils.onRevertAutoCorrect();
StatsUtils.onWordCommitUserTyped(lastComposedWord, mWordComposer.isBatchMode()); StatsUtils.onWordCommitUserTyped(lastComposedWord, mWordComposer.isBatchMode());
// Restart suggestions when backspacing into a reverted word. This is required for // Restart suggestions when backspacing into a reverted word. This is required for
@ -1120,12 +1104,10 @@ public final class InputLogic {
// Note: restartSuggestionsOnWordTouchedByCursor is already called for normal // Note: restartSuggestionsOnWordTouchedByCursor is already called for normal
// (non-revert) backspace handling. // (non-revert) backspace handling.
if (inputTransaction.getMSettingsValues().isSuggestionsEnabledPerUserSettings() if (inputTransaction.getMSettingsValues().isSuggestionsEnabledPerUserSettings()
&& inputTransaction.getMSettingsValues().mSpacingAndPunctuations && inputTransaction.getMSettingsValues().mSpacingAndPunctuations.mCurrentLanguageHasSpaces
.mCurrentLanguageHasSpaces
&& !mConnection.isCursorFollowedByWordCharacter( && !mConnection.isCursorFollowedByWordCharacter(
inputTransaction.getMSettingsValues().mSpacingAndPunctuations)) { inputTransaction.getMSettingsValues().mSpacingAndPunctuations)) {
restartSuggestionsOnWordTouchedByCursor(inputTransaction.getMSettingsValues(), restartSuggestionsOnWordTouchedByCursor(inputTransaction.getMSettingsValues(), currentKeyboardScriptId);
false /* forStartInput */, currentKeyboardScriptId);
} }
return; return;
} }
@ -1143,13 +1125,11 @@ public final class InputLogic {
} }
if (SpaceState.DOUBLE == inputTransaction.getMSpaceState()) { if (SpaceState.DOUBLE == inputTransaction.getMSpaceState()) {
cancelDoubleSpacePeriodCountdown(); cancelDoubleSpacePeriodCountdown();
if (mConnection.revertDoubleSpacePeriod( if (mConnection.revertDoubleSpacePeriod(inputTransaction.getMSettingsValues().mSpacingAndPunctuations)) {
inputTransaction.getMSettingsValues().mSpacingAndPunctuations)) {
// No need to reset mSpaceState, it has already be done (that's why we // No need to reset mSpaceState, it has already be done (that's why we
// receive it as a parameter) // receive it as a parameter)
inputTransaction.setRequiresUpdateSuggestions(); inputTransaction.setRequiresUpdateSuggestions();
mWordComposer.setCapitalizedModeAtStartComposingTime( mWordComposer.setCapitalizedModeAtStartComposingTime(WordComposer.CAPS_MODE_OFF);
WordComposer.CAPS_MODE_OFF);
StatsUtils.onRevertDoubleSpacePeriod(); StatsUtils.onRevertDoubleSpacePeriod();
return; return;
} }
@ -1183,8 +1163,7 @@ public final class InputLogic {
} else { } else {
// There is no selection, just delete one character. // There is no selection, just delete one character.
if (inputTransaction.getMSettingsValues().mInputAttributes.isTypeNull() if (inputTransaction.getMSettingsValues().mInputAttributes.isTypeNull()
|| Constants.NOT_A_CURSOR_POSITION || Constants.NOT_A_CURSOR_POSITION == mConnection.getExpectedSelectionEnd()) {
== mConnection.getExpectedSelectionEnd()) {
// There are three possible reasons to send a key event: either the field has // There are three possible reasons to send a key event: either the field has
// type TYPE_NULL, in which case the keyboard should send events, or we are // type TYPE_NULL, in which case the keyboard should send events, or we are
// running in backward compatibility mode, or we don't know the cursor position. // running in backward compatibility mode, or we don't know the cursor position.
@ -1257,12 +1236,10 @@ public final class InputLogic {
if (mConnection.hasSlowInputConnection()) { if (mConnection.hasSlowInputConnection()) {
mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); mSuggestionStripViewAccessor.setNeutralSuggestionStrip();
} else if (inputTransaction.getMSettingsValues().isSuggestionsEnabledPerUserSettings() } else if (inputTransaction.getMSettingsValues().isSuggestionsEnabledPerUserSettings()
&& inputTransaction.getMSettingsValues().mSpacingAndPunctuations && inputTransaction.getMSettingsValues().mSpacingAndPunctuations.mCurrentLanguageHasSpaces
.mCurrentLanguageHasSpaces
&& !mConnection.isCursorFollowedByWordCharacter( && !mConnection.isCursorFollowedByWordCharacter(
inputTransaction.getMSettingsValues().mSpacingAndPunctuations)) { inputTransaction.getMSettingsValues().mSpacingAndPunctuations)) {
restartSuggestionsOnWordTouchedByCursor(inputTransaction.getMSettingsValues(), restartSuggestionsOnWordTouchedByCursor(inputTransaction.getMSettingsValues(), currentKeyboardScriptId);
false /* forStartInput */, currentKeyboardScriptId);
} }
} }
} }
@ -1294,8 +1271,7 @@ public final class InputLogic {
// entered the composing state yet), unlearn the word. // entered the composing state yet), unlearn the word.
// TODO: Consider tracking whether or not this word was typed by the user. // TODO: Consider tracking whether or not this word was typed by the user.
if (!mConnection.isCursorFollowedByWordCharacter(settingsValues.mSpacingAndPunctuations)) { if (!mConnection.isCursorFollowedByWordCharacter(settingsValues.mSpacingAndPunctuations)) {
final String wordBeingDeleted = getWordAtCursor( final String wordBeingDeleted = getWordAtCursor(settingsValues, currentKeyboardScriptId);
settingsValues, currentKeyboardScriptId);
if (!TextUtils.isEmpty(wordBeingDeleted)) { if (!TextUtils.isEmpty(wordBeingDeleted)) {
unlearnWord(wordBeingDeleted, settingsValues, Constants.EVENT_BACKSPACE); unlearnWord(wordBeingDeleted, settingsValues, Constants.EVENT_BACKSPACE);
return true; return true;
@ -1305,12 +1281,9 @@ public final class InputLogic {
} }
void unlearnWord(final String word, final SettingsValues settingsValues, final int eventType) { void unlearnWord(final String word, final SettingsValues settingsValues, final int eventType) {
final NgramContext ngramContext = mConnection.getNgramContextFromNthPreviousWord( final NgramContext ngramContext = mConnection.getNgramContextFromNthPreviousWord(settingsValues.mSpacingAndPunctuations, 2);
settingsValues.mSpacingAndPunctuations, 2); final long timeStampInSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
final long timeStampInSeconds = TimeUnit.MILLISECONDS.toSeconds( mDictionaryFacilitator.unlearnFromUserHistory(word, ngramContext, timeStampInSeconds, eventType);
System.currentTimeMillis());
mDictionaryFacilitator.unlearnFromUserHistory(
word, ngramContext, timeStampInSeconds, eventType);
} }
/** /**
@ -1420,9 +1393,9 @@ public final class InputLogic {
} }
// We know there is a space in pos -1, and we have at least two chars. If we have only two // We know there is a space in pos -1, and we have at least two chars. If we have only two
// chars, isSurrogatePairs can't return true as charAt(1) is a space, so this is fine. // chars, isSurrogatePairs can't return true as charAt(1) is a space, so this is fine.
final int firstCodePoint = final int firstCodePoint = Character.isSurrogatePair(lastTwo.charAt(0), lastTwo.charAt(1))
Character.isSurrogatePair(lastTwo.charAt(0), lastTwo.charAt(1)) ? ? Character.codePointAt(lastTwo, length - 3)
Character.codePointAt(lastTwo, length - 3) : lastTwo.charAt(length - 2); : lastTwo.charAt(length - 2);
if (canBeFollowedByDoubleSpacePeriod(firstCodePoint)) { if (canBeFollowedByDoubleSpacePeriod(firstCodePoint)) {
cancelDoubleSpacePeriodCountdown(); cancelDoubleSpacePeriodCountdown();
mConnection.deleteTextBeforeCursor(1); mConnection.deleteTextBeforeCursor(1);
@ -1548,24 +1521,21 @@ public final class InputLogic {
final AsyncResultHolder<SuggestedWords> holder = new AsyncResultHolder<>("Suggest"); final AsyncResultHolder<SuggestedWords> holder = new AsyncResultHolder<>("Suggest");
mInputLogicHandler.getSuggestedWords(inputStyle, SuggestedWords.NOT_A_SEQUENCE_NUMBER, mInputLogicHandler.getSuggestedWords(inputStyle, SuggestedWords.NOT_A_SEQUENCE_NUMBER,
new OnGetSuggestedWordsCallback() { suggestedWords -> {
@Override final String typedWordString = mWordComposer.getTypedWord();
public void onGetSuggestedWords(final SuggestedWords suggestedWords) { final SuggestedWordInfo typedWordInfo = new SuggestedWordInfo(
final String typedWordString = mWordComposer.getTypedWord(); typedWordString, "" /* prevWordsContext */,
final SuggestedWordInfo typedWordInfo = new SuggestedWordInfo( SuggestedWordInfo.MAX_SCORE,
typedWordString, "" /* prevWordsContext */, SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED,
SuggestedWordInfo.MAX_SCORE, SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED, SuggestedWordInfo.NOT_A_CONFIDENCE);
SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */, // Show new suggestions if we have at least one. Otherwise keep the old
SuggestedWordInfo.NOT_A_CONFIDENCE); // suggestions with the new typed word. Exception: if the length of the
// Show new suggestions if we have at least one. Otherwise keep the old // typed word is <= 1 (after a deletion typically) we clear old suggestions.
// suggestions with the new typed word. Exception: if the length of the if (suggestedWords.size() > 1 || typedWordString.length() <= 1) {
// typed word is <= 1 (after a deletion typically) we clear old suggestions. holder.set(suggestedWords);
if (suggestedWords.size() > 1 || typedWordString.length() <= 1) { } else {
holder.set(suggestedWords); holder.set(retrieveOlderSuggestions(typedWordInfo, mSuggestedWords));
} else {
holder.set(retrieveOlderSuggestions(typedWordInfo, mSuggestedWords));
}
} }
} }
); );
@ -1587,12 +1557,8 @@ public final class InputLogic {
* do nothing. * do nothing.
* *
* @param settingsValues the current values of the settings. * @param settingsValues the current values of the settings.
* @param forStartInput whether we're doing this in answer to starting the input (as opposed
* to a cursor move, for example). In ICS, there is a platform bug that we need to work
* around only when we come here at input start time.
*/ */
public void restartSuggestionsOnWordTouchedByCursor(final SettingsValues settingsValues, public void restartSuggestionsOnWordTouchedByCursor(final SettingsValues settingsValues,
final boolean forStartInput,
// TODO: remove this argument, put it into settingsValues // TODO: remove this argument, put it into settingsValues
final int currentKeyboardScriptId) { final int currentKeyboardScriptId) {
// HACK: We may want to special-case some apps that exhibit bad behavior in case of // HACK: We may want to special-case some apps that exhibit bad behavior in case of
@ -1667,9 +1633,6 @@ public final class InputLogic {
mLatinIME.getCoordinatesForCurrentKeyboard(codePoints)); mLatinIME.getCoordinatesForCurrentKeyboard(codePoints));
mWordComposer.setCursorPositionWithinWord( mWordComposer.setCursorPositionWithinWord(
typedWordString.codePointCount(0, numberOfCharsInWordBeforeCursor)); typedWordString.codePointCount(0, numberOfCharsInWordBeforeCursor));
if (forStartInput) {
mConnection.maybeMoveTheCursorAroundAndRestoreToWorkaroundABug();
}
mConnection.setComposingRegion(expectedCursorPosition - numberOfCharsInWordBeforeCursor, mConnection.setComposingRegion(expectedCursorPosition - numberOfCharsInWordBeforeCursor,
expectedCursorPosition + range.getNumberOfCharsInWordAfterCursor()); expectedCursorPosition + range.getNumberOfCharsInWordAfterCursor());
if (suggestions.size() <= 1) { if (suggestions.size() <= 1) {
@ -1677,11 +1640,7 @@ public final class InputLogic {
// if shouldIncludeResumedWordInSuggestions is true, 0 otherwise. In this case, we // if shouldIncludeResumedWordInSuggestions is true, 0 otherwise. In this case, we
// have no useful suggestions, so we will try to compute some for it instead. // have no useful suggestions, so we will try to compute some for it instead.
mInputLogicHandler.getSuggestedWords(Suggest.SESSION_ID_TYPING, mInputLogicHandler.getSuggestedWords(Suggest.SESSION_ID_TYPING,
SuggestedWords.NOT_A_SEQUENCE_NUMBER, new OnGetSuggestedWordsCallback() { SuggestedWords.NOT_A_SEQUENCE_NUMBER, this::doShowSuggestionsAndClearAutoCorrectionIndicator);
@Override
public void onGetSuggestedWords(final SuggestedWords suggestedWords) {
doShowSuggestionsAndClearAutoCorrectionIndicator(suggestedWords);
}});
} else { } else {
// We found suggestion spans in the word. We'll create the SuggestedWords out of // We found suggestion spans in the word. We'll create the SuggestedWords out of
// them, and make willAutoCorrect false. We make typedWordValid false, because the // them, and make willAutoCorrect false. We make typedWordValid false, because the
@ -1706,13 +1665,9 @@ public final class InputLogic {
* This is triggered upon pressing backspace just after a commit with auto-correction. * This is triggered upon pressing backspace just after a commit with auto-correction.
* *
* @param inputTransaction The transaction in progress. * @param inputTransaction The transaction in progress.
* @param settingsValues the current values of the settings.
*/ */
private void revertCommit(final InputTransaction inputTransaction, private void revertCommit(final InputTransaction inputTransaction) {
final SettingsValues settingsValues) {
final CharSequence originallyTypedWord = mLastComposedWord.mTypedWord; final CharSequence originallyTypedWord = mLastComposedWord.mTypedWord;
final String originallyTypedWordString =
originallyTypedWord != null ? originallyTypedWord.toString() : "";
final CharSequence committedWord = mLastComposedWord.mCommittedWord; final CharSequence committedWord = mLastComposedWord.mCommittedWord;
final String committedWordString = committedWord.toString(); final String committedWordString = committedWord.toString();
final int cancelLength = committedWord.length(); final int cancelLength = committedWord.length();
@ -1774,7 +1729,7 @@ public final class InputLogic {
// Add the suggestion list to the list of suggestions. // Add the suggestion list to the list of suggestions.
textToCommit.setSpan(new SuggestionSpan(mLatinIME /* context */, textToCommit.setSpan(new SuggestionSpan(mLatinIME /* context */,
inputTransaction.getMSettingsValues().mLocale, inputTransaction.getMSettingsValues().mLocale,
suggestions.toArray(new String[suggestions.size()]), 0 /* flags */, suggestions.toArray(new String[0]), 0 /* flags */,
null /* notificationTargetClass */), null /* notificationTargetClass */),
0 /* start */, lastCharIndex /* end */, 0 /* flags */); 0 /* start */, lastCharIndex /* end */, 0 /* flags */);
} }
@ -1789,8 +1744,7 @@ public final class InputLogic {
// For languages without spaces, we revert the typed string but the cursor is flush // For languages without spaces, we revert the typed string but the cursor is flush
// with the typed word, so we need to resume suggestions right away. // with the typed word, so we need to resume suggestions right away.
final int[] codePoints = StringUtils.toCodePointArray(stringToCommit); final int[] codePoints = StringUtils.toCodePointArray(stringToCommit);
mWordComposer.setComposingWord(codePoints, mWordComposer.setComposingWord(codePoints, mLatinIME.getCoordinatesForCurrentKeyboard(codePoints));
mLatinIME.getCoordinatesForCurrentKeyboard(codePoints));
setComposingTextInternal(textToCommit, 1); setComposingTextInternal(textToCommit, 1);
} }
// Don't restart suggestion yet. We'll restart if the user deletes the separator. // Don't restart suggestion yet. We'll restart if the user deletes the separator.
@ -1874,14 +1828,12 @@ public final class InputLogic {
if (spacingAndPunctuations.mCurrentLanguageHasSpaces) { if (spacingAndPunctuations.mCurrentLanguageHasSpaces) {
// If we are typing in a language with spaces we can just look up the previous // If we are typing in a language with spaces we can just look up the previous
// word information from textview. // word information from textview.
return mConnection.getNgramContextFromNthPreviousWord( return mConnection.getNgramContextFromNthPreviousWord(spacingAndPunctuations, nthPreviousWord);
spacingAndPunctuations, nthPreviousWord);
} }
if (LastComposedWord.NOT_A_COMPOSED_WORD == mLastComposedWord) { if (LastComposedWord.NOT_A_COMPOSED_WORD == mLastComposedWord) {
return NgramContext.BEGINNING_OF_SENTENCE; return NgramContext.BEGINNING_OF_SENTENCE;
} }
return new NgramContext(new NgramContext.WordInfo( return new NgramContext(new NgramContext.WordInfo(mLastComposedWord.mCommittedWord.toString()));
mLastComposedWord.mCommittedWord.toString()));
} }
/** /**
@ -1963,8 +1915,7 @@ public final class InputLogic {
if (clearSuggestionStrip) { if (clearSuggestionStrip) {
mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); mSuggestionStripViewAccessor.setNeutralSuggestionStrip();
} }
mConnection.resetCachesUponCursorMoveAndReturnSuccess(newSelStart, newSelEnd, mConnection.resetCachesUponCursorMoveAndReturnSuccess(newSelStart, newSelEnd, shouldFinishComposition);
shouldFinishComposition);
} }
/** /**
@ -2129,8 +2080,7 @@ public final class InputLogic {
mConnection.endBatchEdit(); mConnection.endBatchEdit();
// Space state must be updated before calling updateShiftState // Space state must be updated before calling updateShiftState
mSpaceState = SpaceState.PHANTOM; mSpaceState = SpaceState.PHANTOM;
keyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(settingsValues), keyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(settingsValues), getCurrentRecapitalizeState());
getCurrentRecapitalizeState());
} }
/** /**
@ -2153,8 +2103,7 @@ public final class InputLogic {
final String typedWord = mWordComposer.getTypedWord(); final String typedWord = mWordComposer.getTypedWord();
if (typedWord.length() > 0) { if (typedWord.length() > 0) {
final boolean isBatchMode = mWordComposer.isBatchMode(); final boolean isBatchMode = mWordComposer.isBatchMode();
commitChosenWord(settingsValues, typedWord, commitChosenWord(settingsValues, typedWord, LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD, separatorString);
LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD, separatorString);
StatsUtils.onWordCommitUserTyped(typedWord, isBatchMode); StatsUtils.onWordCommitUserTyped(typedWord, isBatchMode);
} }
} }
@ -2200,8 +2149,7 @@ public final class InputLogic {
+ "is empty? Impossible! I must commit suicide."); + "is empty? Impossible! I must commit suicide.");
} }
final boolean isBatchMode = mWordComposer.isBatchMode(); final boolean isBatchMode = mWordComposer.isBatchMode();
commitChosenWord(settingsValues, stringToCommit, commitChosenWord(settingsValues, stringToCommit, LastComposedWord.COMMIT_TYPE_DECIDED_WORD, separator);
LastComposedWord.COMMIT_TYPE_DECIDED_WORD, separator);
if (!typedWord.equals(stringToCommit)) { if (!typedWord.equals(stringToCommit)) {
// This will make the correction flash for a short while as a visual clue // This will make the correction flash for a short while as a visual clue
// to the user that auto-correction happened. It has no other effect; in particular // to the user that auto-correction happened. It has no other effect; in particular
@ -2384,11 +2332,9 @@ public final class InputLogic {
composingTextToBeSet = newComposingText; composingTextToBeSet = newComposingText;
} else { } else {
final SpannableString spannable = new SpannableString(newComposingText); final SpannableString spannable = new SpannableString(newComposingText);
final BackgroundColorSpan backgroundColorSpan = final BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(backgroundColor);
new BackgroundColorSpan(backgroundColor);
final int spanLength = Math.min(coloredTextLength, spannable.length()); final int spanLength = Math.min(coloredTextLength, spannable.length());
spannable.setSpan(backgroundColorSpan, 0, spanLength, spannable.setSpan(backgroundColorSpan, 0, spanLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING);
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING);
composingTextToBeSet = spannable; composingTextToBeSet = spannable;
} }
mConnection.setComposingText(composingTextToBeSet, newCursorPosition); mConnection.setComposingText(composingTextToBeSet, newCursorPosition);