Skip to content

Commit e01a196

Browse files
committed
fix(gesture): learn from a swiped word deleted and retyped (#946)
Swipe corrections were only learned when another suggestion was picked from the strip. Deleting the swiped word with backspace and typing a word in its place taught nothing, which is the only way to correct a swipe with suggestions hidden. Now the deleted swipe and its other candidates are remembered, and the first word typed in the same place is recorded in GestureWordBias when it was one of them. Without suggestion lookups (suggestions hidden and auto-correct off) letters are committed one by one, so the word is read from the text at the next separator or swipe. Deleting past the swipe, a word that was no candidate, incognito mode, fields without suggestions or Personalized suggestions off record nothing. Picking a suggestion after a swipe now also respects Personalized suggestions.
1 parent f4ddfe5 commit e01a196

3 files changed

Lines changed: 206 additions & 4 deletions

File tree

‎app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ class InputLogic(
117117
private var mLastExpandedCursorOffset = -1
118118
private var mJustRevertedExpandedShortcut: String? = null
119119
private var mJustRevertedACommit = false
120+
/** a swiped word removed with backspace, for learning from the word typed in its place, see [recordRetypedSwipeCorrection] */
121+
private var mDeletedSwipe: DeletedSwipe? = null
120122
private var mIsProcessingSelectionUpdate = false
121123
private var mIsRecoveringComposingSpan = false
122124
private var mLastSpanReclaimTime = 0L
@@ -143,6 +145,7 @@ class InputLogic(
143145
mCapsLockFromRecapitalize = false
144146
mEnteredText = null
145147
mWordBeingCorrectedByCursor = null
148+
mDeletedSwipe = null
146149
mConnection.onStartInput()
147150
if (mWordComposer.getTypedWord().isNotEmpty()) {
148151
StatsUtils.onWordCommitUserTyped(mWordComposer.getTypedWord(), mWordComposer.isBatchMode())
@@ -343,7 +346,7 @@ class InputLogic(
343346

344347
// A swiped word replaced by another suggestion is a correction the next swipes should learn from
345348
if (mWordComposer.isBatchMode() && mWordComposer.isComposingWord() && !settingsValues.mIncognitoModeEnabled
346-
&& !suggestionInfo.isEmoji && !suggestionInfo.isKindOf(SuggestedWordInfo.KIND_SHORTCUT)
349+
&& settingsValues.mUsePersonalizedDicts && !suggestionInfo.isEmoji && !suggestionInfo.isKindOf(SuggestedWordInfo.KIND_SHORTCUT)
347350
) {
348351
val replacedWord = mWordComposer.getTypedWord()
349352
if (replacedWord.isNotEmpty() && !replacedWord.equals(rawSuggestion, ignoreCase = true))
@@ -569,6 +572,7 @@ class InputLogic(
569572
}
570573
mConnection.beginBatchEdit()
571574
try {
575+
recordRetypedSwipeFromText(settingsValues)
572576
if (mWordComposer.isComposingWord()) {
573577
if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) {
574578
unlearnWord(mWordComposer.getTypedWord(), settingsValues, Constants.EVENT_BACKSPACE)
@@ -584,6 +588,8 @@ class InputLogic(
584588
mWordComposer.setRejectedBatchModeSuggestion(selectedText.toString())
585589
}
586590
}
591+
// a word typed in place of a deleted swipe was committed just above, a new swipe starts over
592+
mDeletedSwipe = null
587593
val codePointBeforeCursor = mConnection.codePointBeforeCursor
588594
if (Character.isLetterOrDigit(codePointBeforeCursor)
589595
|| settingsValues.isUsuallyFollowedBySpace(codePointBeforeCursor)
@@ -1438,6 +1444,7 @@ class InputLogic(
14381444
val codePoint = event.codePoint
14391445
val settingsValues = inputTransaction.settingsValues
14401446
val wasComposingWord = mWordComposer.isComposingWord()
1447+
recordRetypedSwipeFromText(settingsValues)
14411448
val needsSegmentation = ScriptUtils.needsWordSegmentation(settingsValues.mLocale)
14421449
val shouldAvoidSendingCode = Constants.CODE_SPACE == codePoint
14431450
&& !settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces
@@ -1722,6 +1729,8 @@ class InputLogic(
17221729
val currentKeyboardScript = inputTransaction.settingsValues.mCurrentKeyboardScript
17231730
mSpaceState = SpaceState.NONE
17241731
mDeleteCount++
1732+
// deleting more than the word typed in place of a deleted swipe: the user is not just correcting the swipe
1733+
mDeletedSwipe?.let { if (!mWordComposer.isComposingWord() && mConnection.expectedSelectionStart <= it.position) mDeletedSwipe = null }
17251734

17261735
val selection = if (event.isKeyRepeat) null else mConnection.getSelectedText(0)
17271736
val hasSelection = !selection.isNullOrEmpty() || (!event.isKeyRepeat && mConnection.hasSelection())
@@ -1788,8 +1797,14 @@ class InputLogic(
17881797
val wasBatchMode = mWordComposer.isBatchMode()
17891798
val initialLength = mWordComposer.getTypedWord().length
17901799
var deletedCodePoints = 0
1800+
var deletedSwipe: DeletedSwipe? = null
17911801
if (mWordComposer.isBatchMode()) {
17921802
val rejectedSuggestion = mWordComposer.getTypedWord()
1803+
if (rejectedSuggestion.isNotEmpty()) {
1804+
val candidates = (0 until mSuggestedWords.size()).map { mSuggestedWords.getWord(it) }
1805+
.filterNot { it.equals(rejectedSuggestion, ignoreCase = true) }
1806+
deletedSwipe = DeletedSwipe(rejectedSuggestion, candidates, -1)
1807+
}
17931808
mWordComposer.reset()
17941809
mWordComposer.setRejectedBatchModeSuggestion(rejectedSuggestion)
17951810
if (!TextUtils.isEmpty(rejectedSuggestion)) {
@@ -1836,6 +1851,7 @@ class InputLogic(
18361851
} else {
18371852
if (wasBatchMode) {
18381853
mConnection.commitText("", 1)
1854+
mDeletedSwipe = deletedSwipe?.copy(position = mConnection.expectedSelectionStart)
18391855
} else {
18401856
mConnection.finishComposingText()
18411857
mConnection.deleteTextBeforeCursor(initialLength)
@@ -2317,6 +2333,8 @@ class InputLogic(
23172333
suggestion: String,
23182334
ngramContext: NgramContext
23192335
) {
2336+
// before the check below: swipe corrections are learned also when suggestions are not shown
2337+
recordRetypedSwipeCorrection(settingsValues, suggestion)
23202338
if (!settingsValues.isSuggestionsEnabledPerUserSettings() || TextUtils.isEmpty(suggestion)) {
23212339
return
23222340
}
@@ -2340,6 +2358,49 @@ class InputLogic(
23402358
if (mWordComposer.isBatchMode()) mDictionaryFacilitator.recordGestureAccepted(word)
23412359
}
23422360

2361+
/**
2362+
* A swiped word was removed with backspace and [committedWord] typed in its place: if it was one of the
2363+
* swipe's other candidates, it is learned like picking it from the suggestion strip, see GestureWordBias.
2364+
* Only the first word committed after the deletion counts.
2365+
*/
2366+
private fun recordRetypedSwipeCorrection(settingsValues: SettingsValues, committedWord: String) {
2367+
val deletedSwipe = mDeletedSwipe ?: return
2368+
mDeletedSwipe = null
2369+
if (mWordComposer.isBatchMode() || !canLearnSwipeCorrections(settingsValues)) return
2370+
// the word must be where the swiped word was, allowing for a space added before it
2371+
val start = mConnection.expectedSelectionStart - committedWord.length
2372+
if (start != deletedSwipe.position && start != deletedSwipe.position + 1) return
2373+
val word = stripWordSeparatorsFromEnd(UnicodeStyleEngine.toPlainText(committedWord), settingsValues)
2374+
if (deletedSwipe.candidates.none { it.equals(word, ignoreCase = true) }) return
2375+
mDictionaryFacilitator.recordGestureCorrection(word, deletedSwipe.word)
2376+
}
2377+
2378+
/**
2379+
* Without suggestion lookups (suggestions hidden and auto-correct off) typed letters are committed one by one
2380+
* and no word commit reaches [recordRetypedSwipeCorrection]: read the word typed in place of a deleted swipe
2381+
* from the text, when a separator is typed or the next swipe starts.
2382+
*/
2383+
private fun recordRetypedSwipeFromText(settingsValues: SettingsValues) {
2384+
val deletedSwipe = mDeletedSwipe ?: return
2385+
if (mWordComposer.isComposingWord()) return // committed through performAdditionToUserHistoryDictionary
2386+
val length = mConnection.expectedSelectionStart - deletedSwipe.position
2387+
if (length <= 0 || length > MAX_RETYPED_SWIPE_LENGTH) {
2388+
mDeletedSwipe = null
2389+
return
2390+
}
2391+
val typed = mConnection.getTextBeforeCursor(length, 0)?.toString()
2392+
if (typed == null) {
2393+
mDeletedSwipe = null
2394+
return
2395+
}
2396+
recordRetypedSwipeCorrection(settingsValues, typed.trimStart(' '))
2397+
}
2398+
2399+
private fun canLearnSwipeCorrections(settingsValues: SettingsValues) = !settingsValues.mIncognitoModeEnabled
2400+
&& settingsValues.mUsePersonalizedDicts && settingsValues.mInputAttributes.mShouldShowSuggestions
2401+
2402+
private data class DeletedSwipe(val word: String, val candidates: List<String>, val position: Int)
2403+
23432404
private fun stripWordSeparatorsFromEnd(word: String, settingsValues: SettingsValues): String {
23442405
return if (settingsValues.mSpacingAndPunctuations.isWordSeparator(word.codePointBefore(word.length))) {
23452406
var endIndex = word.length - 1
@@ -3469,6 +3530,8 @@ class InputLogic(
34693530
companion object {
34703531
private const val TAG = "InputLogic"
34713532
private const val INLINE_EMOJI_SEARCH_MARKER = ':'
3533+
/** longer text typed in place of a deleted swipe is not a single word correcting it */
3534+
private const val MAX_RETYPED_SWIPE_LENGTH = 48
34723535
private const val KEY_REPEAT_INTERVAL_MS = 50
34733536
/** interval before the second word, it gets shorter with each word until the minimum */
34743537
private const val BACKSPACE_WORD_START_INTERVAL = 350f

‎app/src/test/java/helium314/keyboard/latin/InputLogicTest.kt‎

Lines changed: 141 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1515,6 +1515,137 @@ class InputLogicTest {
15151515

15161516
}
15171517

1518+
@Test fun `deleted swipe retyped as one of its candidates is learned`() {
1519+
reset()
1520+
chainInput("say ")
1521+
glideTypingInput("hall", "hello", "hill")
1522+
functionalKeyPress(KeyCode.DELETE)
1523+
assertEquals("say ", text)
1524+
chainInput("hello ")
1525+
assertEquals("say hello ", text)
1526+
assertEquals(listOf("hello" to "hall"), ShadowFacilitator2.gestureCorrections)
1527+
}
1528+
1529+
@Test fun `deleted swipe retyped is learned when the next swipe commits it`() {
1530+
reset()
1531+
glideTypingInput("hall", "hello")
1532+
functionalKeyPress(KeyCode.DELETE)
1533+
chainInput("hello")
1534+
// starting the next swipe commits the typed word
1535+
latinIME.mInputLogic.onStartBatchInput(settingsValues, KeyboardSwitcher.getInstance(), latinIME.handler)
1536+
assertEquals(listOf("hello" to "hall"), ShadowFacilitator2.gestureCorrections)
1537+
// and a word typed after that swipe is not a correction of the first one
1538+
glideTypingInput("there", "then")
1539+
chainInput(" hall ")
1540+
assertEquals(listOf("hello" to "hall"), ShadowFacilitator2.gestureCorrections)
1541+
}
1542+
1543+
@Test fun `deleted swipe replaced by a word that was no candidate is not learned`() {
1544+
reset()
1545+
glideTypingInput("hall", "hello")
1546+
functionalKeyPress(KeyCode.DELETE)
1547+
chainInput("goodbye ")
1548+
assertEquals(emptyList<Pair<String, String>>(), ShadowFacilitator2.gestureCorrections)
1549+
}
1550+
1551+
@Test fun `deleting more after a deleted swipe is not learned`() {
1552+
reset()
1553+
chainInput("say ")
1554+
glideTypingInput("hall", "hello")
1555+
functionalKeyPress(KeyCode.DELETE)
1556+
functionalKeyPress(KeyCode.DELETE) // removes the space: editing more than the swiped word
1557+
chainInput(" hello ")
1558+
assertEquals(emptyList<Pair<String, String>>(), ShadowFacilitator2.gestureCorrections)
1559+
}
1560+
1561+
@Test fun `only the first word after a deleted swipe counts`() {
1562+
reset()
1563+
glideTypingInput("hall", "hello")
1564+
functionalKeyPress(KeyCode.DELETE)
1565+
chainInput("hi hello ")
1566+
assertEquals(emptyList<Pair<String, String>>(), ShadowFacilitator2.gestureCorrections)
1567+
}
1568+
1569+
@Test fun `deleted swipe retyped is not learned in incognito mode or without personalized suggestions`() {
1570+
reset()
1571+
latinIME.prefs().edit { putBoolean(Settings.PREF_ALWAYS_INCOGNITO_MODE, true) }
1572+
glideTypingInput("hall", "hello")
1573+
functionalKeyPress(KeyCode.DELETE)
1574+
chainInput("hello ")
1575+
latinIME.prefs().edit { putBoolean(Settings.PREF_ALWAYS_INCOGNITO_MODE, false) }
1576+
latinIME.prefs().edit { putBoolean(Settings.PREF_KEY_USE_PERSONALIZED_DICTS, false) }
1577+
glideTypingInput("hall", "hello")
1578+
functionalKeyPress(KeyCode.DELETE)
1579+
chainInput("hello ")
1580+
latinIME.prefs().edit { putBoolean(Settings.PREF_KEY_USE_PERSONALIZED_DICTS, true) }
1581+
assertEquals(emptyList<Pair<String, String>>(), ShadowFacilitator2.gestureCorrections)
1582+
}
1583+
1584+
@Test fun `deleted swipe retyped is learned when suggestions are hidden`() {
1585+
reset()
1586+
latinIME.prefs().edit { putBoolean(Settings.PREF_SHOW_SUGGESTIONS, false) }
1587+
glideTypingInput("hall", "hello")
1588+
functionalKeyPress(KeyCode.DELETE)
1589+
chainInput("hello ")
1590+
latinIME.prefs().edit { putBoolean(Settings.PREF_SHOW_SUGGESTIONS, true) }
1591+
assertEquals(listOf("hello" to "hall"), ShadowFacilitator2.gestureCorrections)
1592+
}
1593+
1594+
// suggestions hidden and auto-correct off: no suggestion lookups, typed letters are committed one by one
1595+
private fun disableSuggestionLookups() = latinIME.prefs().edit {
1596+
putBoolean(Settings.PREF_SHOW_SUGGESTIONS, false)
1597+
putBoolean(Settings.PREF_AUTO_CORRECTION, false)
1598+
}
1599+
1600+
@Test fun `deleted swipe retyped without suggestion lookups is learned`() {
1601+
reset()
1602+
disableSuggestionLookups()
1603+
chainInput("say ")
1604+
glideTypingInput("hall", "hello")
1605+
functionalKeyPress(KeyCode.DELETE)
1606+
chainInput("hello ")
1607+
assertEquals("say hello ", text)
1608+
assertEquals(listOf("hello" to "hall"), ShadowFacilitator2.gestureCorrections)
1609+
}
1610+
1611+
@Test fun `deleted swipe retyped with a fixed typo without suggestion lookups is learned`() {
1612+
reset()
1613+
disableSuggestionLookups()
1614+
glideTypingInput("hall", "hello")
1615+
functionalKeyPress(KeyCode.DELETE)
1616+
chainInput("helk")
1617+
functionalKeyPress(KeyCode.DELETE)
1618+
chainInput("lo,")
1619+
assertEquals(listOf("hello" to "hall"), ShadowFacilitator2.gestureCorrections)
1620+
}
1621+
1622+
@Test fun `deleted swipe without suggestion lookups is not learned from other text`() {
1623+
reset()
1624+
disableSuggestionLookups()
1625+
chainInput("say ")
1626+
glideTypingInput("hall", "hello")
1627+
functionalKeyPress(KeyCode.DELETE)
1628+
chainInput("goodbye ") // no candidate
1629+
glideTypingInput("hall", "hello")
1630+
functionalKeyPress(KeyCode.DELETE)
1631+
functionalKeyPress(KeyCode.DELETE) // deletes the space before the swipe
1632+
chainInput(" hello ")
1633+
glideTypingInput("hall", "hello")
1634+
functionalKeyPress(KeyCode.DELETE)
1635+
chainInput("hi hello ") // the first word counts
1636+
assertEquals(emptyList<Pair<String, String>>(), ShadowFacilitator2.gestureCorrections)
1637+
}
1638+
1639+
@Test fun `deleted swipe retyped without suggestion lookups is learned when the next swipe starts`() {
1640+
reset()
1641+
disableSuggestionLookups()
1642+
glideTypingInput("hall", "hello")
1643+
functionalKeyPress(KeyCode.DELETE)
1644+
chainInput("hello")
1645+
latinIME.mInputLogic.onStartBatchInput(settingsValues, KeyboardSwitcher.getInstance(), latinIME.handler)
1646+
assertEquals(listOf("hello" to "hall"), ShadowFacilitator2.gestureCorrections)
1647+
}
1648+
15181649
@Test fun `held backspace accelerates composing word deletion past threshold`() {
15191650
reset()
15201651
chainInput("abcdefghijklmnopqrstuvwxy") // 25 characters
@@ -1840,6 +1971,7 @@ class InputLogicTest {
18401971
lastNgramContext = ""
18411972
addedWords.clear()
18421973
ngramContexts.clear()
1974+
ShadowFacilitator2.gestureCorrections.clear()
18431975
messages.clear()
18441976
delayedMessages.clear()
18451977

@@ -2075,9 +2207,11 @@ class InputLogicTest {
20752207
checkConnectionConsistency()
20762208
}
20772209

2078-
private fun glideTypingInput(word: String) {
2210+
private fun glideTypingInput(word: String, vararg otherCandidates: String) {
20792211
val info = SuggestedWordInfo(word, "", 0, 0, Mockito.mock(Dictionary::class.java), 0, 0)
2080-
val sw = SuggestedWords(ArrayList(listOf(info)), null, info, true, false, false, 0, 0)
2212+
val others = otherCandidates.map { SuggestedWordInfo(it, "", 0, 0, Mockito.mock(Dictionary::class.java), 0, 0) }
2213+
val sw = SuggestedWords(ArrayList(listOf(info) + others), null, info, true, false, false, 0, 0)
2214+
latinIME.mInputLogic.setSuggestedWords(sw) // the suggestions are set before the word, as in InputLogicHandler
20812215
latinIME.mInputLogic.onUpdateTailBatchInputCompleted(settingsValues, sw, KeyboardSwitcher.getInstance())
20822216
}
20832217

@@ -2452,7 +2586,12 @@ class ShadowFacilitator2 {
24522586
addedWords.add(suggestion)
24532587
ngramContexts.add(lastNgramContext)
24542588
}
2589+
@Implementation
2590+
fun recordGestureCorrection(picked: String, replaced: String) {
2591+
gestureCorrections.add(picked to replaced)
2592+
}
24552593
companion object {
2594+
val gestureCorrections = mutableListOf<Pair<String, String>>()
24562595
var lastAddedWord = ""
24572596
var lastNgramContext = ""
24582597
val addedWords = mutableListOf<String>()

‎docs/FEATURES.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,7 @@ LeanType learns your vocabulary organically as you type while providing deep gra
518518

519519
- Swipe typing needs a separate gesture typing library, which is not included in the app. Without it, swiping does not produce words.
520520
- Supports floating preview text, customizable trail colors, and space-aware gesture input.
521-
- Learns from corrections: when you replace a swiped word with another suggestion, your pick gets a small boost in later swipes where the choice is close. Nothing new is learned in incognito mode.
521+
- Learns from corrections: when you replace a swiped word with another suggestion, or delete it with backspace and type one of the swipe's other candidates in its place, that word gets a small boost in later swipes where the choice is close. This also works with suggestions hidden. Nothing new is learned in incognito mode or with **Settings → Suggestions → Personalized suggestions** off.
522522
- Add the library under **Settings → Gestures & swipes → Load gesture typing library**: `standard` builds can download it there, for `offline` builds download the file yourself and load it.
523523

524524
---

0 commit comments

Comments
 (0)