Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/src/main/java/helium314/keyboard/latin/LatinIME.kt
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ class LatinIME : InputMethodService(),
AudioAndHapticFeedbackManager.init(this)
AccessibilityUtils.init(this)
AppQuirksManager.init(this)
RevertedCorrectionHistory.init(this)
statsUtilsManager.onCreate(this, dictionaryFacilitator)
displayContext = getDisplayContext()
KeyboardSwitcher.init(this)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2668,7 +2668,8 @@ class InputLogic(
mConnection.deleteTextBeforeCursor(deleteLength)
if (!TextUtils.isEmpty(committedWord)) {
unlearnWord(committedWordString, inputTransaction.settingsValues, Constants.EVENT_REVERT)
RevertedCorrectionHistory.record(originallyTypedWord, committedWordString)
RevertedCorrectionHistory.record(originallyTypedWord, committedWordString,
!inputTransaction.settingsValues.mIncognitoModeEnabled)
}
val stringToCommit = originallyTypedWord + (if (usePhantomSpace) "" else separatorString)
val textToCommit = SpannableString(stringToCommit)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

package helium314.keyboard.latin.personalization

import helium314.keyboard.latin.utils.RevertedCorrectionHistory
import android.content.Context
import helium314.keyboard.latin.LatinIME
import helium314.keyboard.latin.utils.Log
Expand Down Expand Up @@ -44,6 +45,7 @@ object PersonalizationHelper {
}

fun removeAllUserHistoryDictionaries(context: Context) {
RevertedCorrectionHistory.forgetAccentSwaps(context)
synchronized(sLangUserHistoryDictCache) {
for (ref in sLangUserHistoryDictCache.values) {
ref?.get()?.clear()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,67 @@
// SPDX-License-Identifier: GPL-3.0-only
package helium314.keyboard.latin.utils

import android.content.Context
import android.content.SharedPreferences
import android.util.LruCache
import androidx.core.content.edit
import java.text.Normalizer
import java.util.Locale

/**
* In-memory short-term cache of recently reverted auto-corrections.
* When a user reverts an auto-correction via Backspace, this cache remembers
* the pair (typedWord -> revertedCandidate) to suppress repeating the same
* auto-correction immediately upon subsequent spaces or separators.
*
* Short words that only differ by an accent ("e" and "è", #1074) are often both common, so a reverted swap of those
* is remembered until the learned words are cleared.
*/
object RevertedCorrectionHistory {
private const val MAX_SIZE = 30
private val cache = LruCache<String, Set<String>>(MAX_SIZE)
private const val PREF_ACCENTS = "rejected_accent_corrections"
private val combiningMarks = Regex("\\p{Mn}")

private fun normalize(word: CharSequence?) = word?.toString()?.trim()?.lowercase(Locale.ROOT).orEmpty()

private var prefs: SharedPreferences? = null

fun init(context: Context) {
prefs = context.prefs()
}

private fun withoutAccents(word: String) = Normalizer.normalize(word, Normalizer.Form.NFD).replace(combiningMarks, "")

/** the stored form of an accent swap between short words, null for other corrections */
private fun accentSwap(typed: String, candidate: String): String? =
if (typed.length in 1..2 && typed != candidate && withoutAccents(typed) == withoutAccents(candidate))
"$typed $candidate"
else null

private fun rejectedAccentSwaps(): Set<String> =
prefs?.getStringSet(PREF_ACCENTS, null).orEmpty()

/** [remember] is false where nothing may be stored (incognito) */
@Synchronized
fun record(typedWord: CharSequence?, revertedCandidate: CharSequence?) {
fun record(typedWord: CharSequence?, revertedCandidate: CharSequence?, remember: Boolean = true) {
val key = normalize(typedWord)
val candidate = normalize(revertedCandidate)
if (key.isEmpty() || candidate.isEmpty() || key == candidate) return
cache.put(key, cache.get(key).orEmpty() + candidate)
val swap = accentSwap(key, candidate)
if (remember && swap != null)
prefs?.edit { putStringSet(PREF_ACCENTS, rejectedAccentSwaps() + swap) }
}

@Synchronized
fun isRecentlyReverted(typedWord: CharSequence?, candidateWord: CharSequence?): Boolean {
val key = normalize(typedWord)
if (key.isEmpty()) return false
return cache.get(key)?.contains(normalize(candidateWord)) == true
val candidate = normalize(candidateWord)
if (cache.get(key)?.contains(candidate) == true) return true
val swap = accentSwap(key, candidate)
return swap != null && swap in rejectedAccentSwaps()
}

/** Allows [candidateWord] again for [typedWord], other rejected corrections stay */
Expand All @@ -41,6 +74,10 @@ object RevertedCorrectionHistory {
if (remaining.isEmpty()) cache.remove(key) else cache.put(key, remaining)
}

/** with the learned words */
fun forgetAccentSwaps(context: Context) = context.prefs().edit { remove(PREF_ACCENTS) }

/** forgets the short-term list only */
@Synchronized
fun clear() {
cache.evictAll()
Expand Down
7 changes: 6 additions & 1 deletion app/src/test/java/helium314/keyboard/Shadows.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import helium314.keyboard.latin.common.StringUtils
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.shadows.ShadowInputMethodManager
import java.text.Normalizer
import java.util.*

@Implements(LocaleManagerCompat::class)
Expand Down Expand Up @@ -46,7 +47,8 @@ class ShadowBinaryDictionaryUtils {
fun calcNormalizedScore(beforeString: String, afterString: String, score: Int): Float {
val before = StringUtils.toCodePointArray(beforeString)
val after = StringUtils.toCodePointArray(afterString)
val distance = editDistance(beforeString, afterString)
// like the native scoring, which ignores case and accents (CharUtils::toBaseLowerCase)
val distance = editDistance(toBaseLowerCase(beforeString), toBaseLowerCase(afterString))
val beforeLength = before.size
val afterLength = after.size
if (0 == beforeLength || 0 == afterLength) return 0.0f
Expand All @@ -65,6 +67,9 @@ class ShadowBinaryDictionaryUtils {
return score.toFloat() / 1000000.0f * weight
}

private fun toBaseLowerCase(word: String) =
Normalizer.normalize(word, Normalizer.Form.NFD).replace(Regex("\\p{Mn}"), "").lowercase()

private fun editDistance(x: String, y: String): Int {
val dp = Array(x.length + 1) {
IntArray(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-only
package helium314.keyboard.latin.utils

import androidx.test.core.app.ApplicationProvider
import helium314.keyboard.latin.App
import org.junit.After
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
Expand Down Expand Up @@ -73,4 +75,25 @@ class RevertedCorrectionHistoryTest {
assertFalse(RevertedCorrectionHistory.isRecentlyReverted("wrod1", "word1"))
assertFalse(RevertedCorrectionHistory.isRecentlyReverted("wrod2", "word2"))
}

// #1074: the swap of two short words that differ by an accent stays rejected after leaving the text field
@Test
fun testRevertedAccentSwapIsRemembered() {
val context = ApplicationProvider.getApplicationContext<App>()
RevertedCorrectionHistory.init(context)
RevertedCorrectionHistory.record("E", "È")
RevertedCorrectionHistory.record("si", "sì", remember = false) // incognito
RevertedCorrectionHistory.record("citta", "città") // longer
RevertedCorrectionHistory.record("ab", "an") // not only an accent
RevertedCorrectionHistory.clear() // leaving the field

assertTrue(RevertedCorrectionHistory.isRecentlyReverted("e", "è"))
assertFalse(RevertedCorrectionHistory.isRecentlyReverted("è", "e"))
assertFalse(RevertedCorrectionHistory.isRecentlyReverted("si", "sì"))
assertFalse(RevertedCorrectionHistory.isRecentlyReverted("citta", "città"))
assertFalse(RevertedCorrectionHistory.isRecentlyReverted("ab", "an"))

RevertedCorrectionHistory.forgetAccentSwaps(context) // clearing learned words
assertFalse(RevertedCorrectionHistory.isRecentlyReverted("e", "è"))
}
}
Loading