diff --git a/CHANGELOG.md b/CHANGELOG.md index 2126eca..fc123b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Added +- Edit existing personal dictionary words in a prefilled dialog, with validation, + duplicate feedback and a single offline dictionary update (#120). - Warn when the selected keyboard declares that it disables Android's system spellchecker on Android 12 and newer. The warning refreshes when changing keyboards and offers a keyboard picker; older Android versions diff --git a/app/src/androidTest/kotlin/fr/zefut/grammalecte/GrammalecteEngineInstrumentedTest.kt b/app/src/androidTest/kotlin/fr/zefut/grammalecte/GrammalecteEngineInstrumentedTest.kt index 8444d59..8d37897 100644 --- a/app/src/androidTest/kotlin/fr/zefut/grammalecte/GrammalecteEngineInstrumentedTest.kt +++ b/app/src/androidTest/kotlin/fr/zefut/grammalecte/GrammalecteEngineInstrumentedTest.kt @@ -9,6 +9,7 @@ import fr.grammalecteandroid.engine.GrammalecteDictionaryPreferences import fr.grammalecteandroid.engine.GrammalectePersonalDictionaryPreferences import fr.grammalecteandroid.engine.GrammalecteQuickJsEngine import fr.grammalecteandroid.engine.GrammalecteRulePreferences +import fr.grammalecteandroid.engine.PersonalDictionaryEditResult import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue @@ -278,6 +279,56 @@ class GrammalecteEngineInstrumentedTest { } } + @Test + fun replacingPersonalDictionaryWordPreservesEntriesAndRefreshesOtherEngines() { + val context = ApplicationProvider.getApplicationContext() + val preferences = GrammalectePersonalDictionaryPreferences(context) + val original = "grammalecteandroidique" + val replacement = "grammalecteandroidissime" + val other = "grammalectepersonnelique" + preferences.replace(listOf(original, other)) + val editor = GrammalecteQuickJsEngine(context) + val reader = GrammalecteQuickJsEngine(context) + + try { + val initial = listOf(original, other).sorted() + assertEquals(initial, editor.personalDictionaryWords()) + assertEquals(initial, reader.personalDictionaryWords()) + + assertEquals(PersonalDictionaryEditResult.DUPLICATE, editor.replacePersonalDictionaryWord(original, other)) + assertEquals(PersonalDictionaryEditResult.UNCHANGED, editor.replacePersonalDictionaryWord(original, original)) + assertEquals(PersonalDictionaryEditResult.MISSING, editor.replacePersonalDictionaryWord("absent", replacement)) + assertTrue(runCatching { editor.replacePersonalDictionaryWord(original, "deux mots") }.isFailure) + // JavaScript rejects an embedded BOM as whitespace even though Kotlin does not. + assertTrue(runCatching { editor.replacePersonalDictionaryWord(original, "mot\uFEFFinvalide") }.isFailure) + assertEquals(initial, preferences.words()) + assertEquals(initial, editor.personalDictionaryWords()) + assertTrue(editor.checkWord(original, "fr-FR", 5).valid) + + assertEquals( + PersonalDictionaryEditResult.REPLACED, + editor.replacePersonalDictionaryWord(original, replacement), + ) + val updated = listOf(replacement, other).sorted() + assertEquals(updated, editor.personalDictionaryWords()) + assertEquals(updated, preferences.words()) + assertEquals(updated, reader.personalDictionaryWords()) + assertTrue(reader.checkWord(replacement, "fr-FR", 5).valid) + assertFalse(reader.checkWord(original, "fr-FR", 5).valid) + + val reopened = GrammalecteQuickJsEngine(context) + try { + assertEquals(updated, reopened.personalDictionaryWords()) + } finally { + reopened.close() + } + } finally { + reader.close() + editor.close() + preferences.reset() + } + } + @Test fun resetToDefaultsPersistsAcrossEngineRestart() { val context = diff --git a/app/src/androidTest/kotlin/fr/zefut/grammalecte/PersonalDictionaryActivityInstrumentedTest.kt b/app/src/androidTest/kotlin/fr/zefut/grammalecte/PersonalDictionaryActivityInstrumentedTest.kt new file mode 100644 index 0000000..73bd448 --- /dev/null +++ b/app/src/androidTest/kotlin/fr/zefut/grammalecte/PersonalDictionaryActivityInstrumentedTest.kt @@ -0,0 +1,108 @@ +package fr.zefut.grammalecte + +import android.content.Context +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.assertTextContains +import androidx.compose.ui.test.hasTestTag +import androidx.compose.ui.test.junit4.v2.createEmptyComposeRule +import androidx.compose.ui.test.onAllNodesWithTag +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollToNode +import androidx.compose.ui.test.performTextReplacement +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import fr.grammalecteandroid.engine.GrammalectePersonalDictionaryPreferences +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class PersonalDictionaryActivityInstrumentedTest { + @get:Rule val composeRule = createEmptyComposeRule() + + @Test + fun editValidatesCancelsAndPersistsAcrossRecreation() { + val context = ApplicationProvider.getApplicationContext() + val preferences = GrammalectePersonalDictionaryPreferences(context) + val original = "grammalecteandroidique" + val other = "grammalectepersonnelique" + val replacement = "grammalecteandroidissime" + val initial = listOf(original, other).sorted() + preferences.replace(initial) + + try { + ActivityScenario.launch(PersonalDictionaryActivity::class.java).use { scenario -> + waitForWordCount() + openEdit(original) + composeRule.onNodeWithTag("dictionary-edit-input").assertTextContains(original) + composeRule.onNodeWithTag("dictionary-edit-input").performTextReplacement(replacement) + composeRule.onNodeWithText("Annuler").performClick() + composeRule.onNodeWithTag("dictionary-edit-input").assertDoesNotExist() + assertEquals(initial, preferences.words()) + + openEdit(original) + submit("") + assertError("Saisissez un mot.") + submit("a".repeat(65)) + assertError("Le mot ne doit pas dépasser 64 caractères.") + submit("deux mots") + assertError("Saisissez un seul mot à la fois.") + submit(other) + composeRule.waitUntil(30_000) { + composeRule.onAllNodesWithTag("dictionary-edit-error").fetchSemanticsNodes().isNotEmpty() + } + assertError("Ce mot est déjà dans le dictionnaire.") + assertEquals(initial, preferences.words()) + composeRule.onNodeWithTag("dictionary-edit-input").assertTextContains(other) + + submit(replacement) + composeRule.waitUntil(30_000) { + composeRule.onAllNodesWithTag("dictionary-edit-input").fetchSemanticsNodes().isEmpty() + } + val updated = listOf(replacement, other).sorted() + assertEquals(updated, preferences.words()) + + scenario.recreate() + waitForWordCount() + openEdit(replacement) + composeRule.onNodeWithTag("dictionary-edit-input").assertTextContains(replacement) + composeRule.onNodeWithText("Annuler").performClick() + assertEquals(updated, preferences.words()) + } + } finally { + preferences.reset() + } + } + + private fun waitForWordCount() { + composeRule.waitUntil(30_000) { + composeRule.onAllNodesWithText("2 mots enregistrés.").fetchSemanticsNodes().isNotEmpty() + } + } + + private fun openEdit(word: String) { + val tag = "dictionary-edit-$word" + composeRule.onNodeWithTag("personal-dictionary").performScrollToNode(hasTestTag(tag)) + composeRule.onNodeWithTag(tag).performClick() + } + + private fun submit(word: String) { + composeRule.onNodeWithTag("dictionary-edit-input").performTextReplacement(word) + composeRule.onNodeWithText("Enregistrer").performClick() + } + + private fun assertError(message: String) { + composeRule + .onNodeWithTag("dictionary-edit-error") + .assertTextContains(message) + .assert(SemanticsMatcher.expectValue(SemanticsProperties.LiveRegion, LiveRegionMode.Polite)) + } +} diff --git a/app/src/androidTest/kotlin/fr/zefut/grammalecte/PersonalDictionaryScreenInstrumentedTest.kt b/app/src/androidTest/kotlin/fr/zefut/grammalecte/PersonalDictionaryScreenInstrumentedTest.kt index f4bfeea..12e935a 100644 --- a/app/src/androidTest/kotlin/fr/zefut/grammalecte/PersonalDictionaryScreenInstrumentedTest.kt +++ b/app/src/androidTest/kotlin/fr/zefut/grammalecte/PersonalDictionaryScreenInstrumentedTest.kt @@ -3,11 +3,13 @@ package fr.zefut.grammalecte import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.assertTextContains +import androidx.compose.ui.test.hasTestTag import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollToNode import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Assert.assertEquals import org.junit.Rule @@ -32,15 +34,22 @@ class PersonalDictionaryScreenInstrumentedTest { status = "1 mot", statusIsError = false, busy = false, + edit = null, onInputChange = { entered = it }, onAdd = { added++ }, onRemove = { removed = it }, + onEdit = {}, + onEditInputChange = {}, + onEditConfirm = {}, + onEditCancel = {}, onBack = { back++ }, ) } composeRule.onNodeWithText("Ajouter").assertIsEnabled().performClick() + composeRule.onNodeWithTag("personal-dictionary").performScrollToNode(hasTestTag("dictionary-edit-grammalecte")) composeRule.onNodeWithText("Supprimer").assertIsEnabled().performClick() + composeRule.onNodeWithTag("personal-dictionary").performScrollToNode(hasTestTag("dictionary-heading")) composeRule.onNodeWithContentDescription("Retour").performClick() composeRule.runOnIdle { assertEquals(1, added) @@ -58,9 +67,14 @@ class PersonalDictionaryScreenInstrumentedTest { status = "Ce mot est déjà dans le dictionnaire.", statusIsError = true, busy = false, + edit = null, onInputChange = {}, onAdd = {}, onRemove = {}, + onEdit = {}, + onEditInputChange = {}, + onEditConfirm = {}, + onEditCancel = {}, onBack = {}, ) } @@ -79,16 +93,23 @@ class PersonalDictionaryScreenInstrumentedTest { status = "Chargement…", statusIsError = false, busy = true, + edit = null, onInputChange = {}, onAdd = {}, onRemove = {}, + onEdit = {}, + onEditInputChange = {}, + onEditConfirm = {}, + onEditCancel = {}, onBack = {}, ) } composeRule.onNodeWithTag("dictionary-input").assertIsNotEnabled() composeRule.onNodeWithText("Ajouter").assertIsNotEnabled() - composeRule.onNodeWithText("Supprimer").assertIsNotEnabled() composeRule.onNodeWithTag("dictionary-status").assertTextContains("Chargement…") + composeRule.onNodeWithTag("personal-dictionary").performScrollToNode(hasTestTag("dictionary-edit-grammalecte")) + composeRule.onNodeWithText("Modifier").assertIsNotEnabled() + composeRule.onNodeWithText("Supprimer").assertIsNotEnabled() } } diff --git a/app/src/main/kotlin/fr/zefut/grammalecte/PersonalDictionaryActivity.kt b/app/src/main/kotlin/fr/zefut/grammalecte/PersonalDictionaryActivity.kt index 9d2fc44..40b8c85 100644 --- a/app/src/main/kotlin/fr/zefut/grammalecte/PersonalDictionaryActivity.kt +++ b/app/src/main/kotlin/fr/zefut/grammalecte/PersonalDictionaryActivity.kt @@ -9,6 +9,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import fr.grammalecteandroid.engine.GrammalecteQuickJsEngine +import fr.grammalecteandroid.engine.PersonalDictionaryEditResult import java.util.concurrent.Executors class PersonalDictionaryActivity : ComponentActivity() { @@ -19,6 +20,7 @@ class PersonalDictionaryActivity : ComponentActivity() { } private var input by mutableStateOf("") + private var edit by mutableStateOf(null) private var words by mutableStateOf>(emptyList()) private var status by mutableStateOf("Chargement…") private var statusIsError by mutableStateOf(false) @@ -31,6 +33,9 @@ class PersonalDictionaryActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) input = savedInstanceState?.getString(STATE_INPUT).orEmpty() + savedInstanceState?.getString(STATE_EDIT_ORIGINAL)?.let { original -> + edit = DictionaryEditState(original, savedInstanceState.getString(STATE_EDIT_INPUT) ?: original) + } setContent { PersonalDictionaryScreen( input = input, @@ -38,12 +43,17 @@ class PersonalDictionaryActivity : ComponentActivity() { status = status, statusIsError = statusIsError, busy = busy, + edit = edit, onInputChange = { input = it if (statusIsError) renderWords(words) }, onAdd = { addWord() }, onRemove = { removeWord(it) }, + onEdit = { edit = DictionaryEditState(it, it) }, + onEditInputChange = { edit = edit?.copy(input = it, error = null) }, + onEditConfirm = { editWord() }, + onEditCancel = { if (!busy) edit = null }, onBack = { finish() }, ) } @@ -52,6 +62,10 @@ class PersonalDictionaryActivity : ComponentActivity() { override fun onSaveInstanceState(outState: Bundle) { outState.putString(STATE_INPUT, input) + edit?.let { + outState.putString(STATE_EDIT_ORIGINAL, it.original) + outState.putString(STATE_EDIT_INPUT, it.input) + } super.onSaveInstanceState(outState) } @@ -74,22 +88,10 @@ class PersonalDictionaryActivity : ComponentActivity() { private fun addWord() { val word = input.trim() - when { - word.isEmpty() -> { - statusIsError = true - status = "Saisissez un mot." - return - } - word.length > 64 -> { - statusIsError = true - status = "Le mot ne doit pas dépasser 64 caractères." - return - } - word.any(Char::isWhitespace) -> { - statusIsError = true - status = "Ajoutez un seul mot à la fois." - return - } + wordValidationError(word)?.let { error -> + statusIsError = true + status = error + return } busy = true @@ -109,13 +111,70 @@ class PersonalDictionaryActivity : ComponentActivity() { input = "" renderWords(updatedWords) busy = false - status = if (added) "Mot ajouté." else "Ce mot est déjà dans le dictionnaire." + status = if (added) "Mot ajouté." else DUPLICATE_MESSAGE statusIsError = !added }.onFailure { showError(it) } } } } + private fun editWord() { + if (busy) return + val draft = edit ?: return + val replacement = draft.input.trim() + wordValidationError(replacement)?.let { error -> + edit = draft.copy(error = error) + return + } + + busy = true + edit = draft.copy(error = null) + executor.execute { + val result = + runCatching { + val currentEngine = currentEngine() + val outcome = currentEngine.replacePersonalDictionaryWord(draft.original, replacement) + outcome to currentEngine.personalDictionaryWords() + } + mainHandler.post { + if (destroyed) return@post + busy = false + result + .onSuccess { (outcome, updatedWords) -> + renderWords(updatedWords) + when (outcome) { + PersonalDictionaryEditResult.REPLACED -> { + edit = null + status = "Mot modifié." + } + PersonalDictionaryEditResult.UNCHANGED -> { + edit = null + status = "Mot inchangé." + } + PersonalDictionaryEditResult.DUPLICATE -> { + edit = draft.copy(error = DUPLICATE_MESSAGE) + } + PersonalDictionaryEditResult.MISSING -> { + edit = null + status = "Le mot d’origine n’est plus dans le dictionnaire." + statusIsError = true + } + } + }.onFailure { + edit = draft.copy(error = "Impossible de modifier ce mot. Réessayez.") + } + } + } + } + + private fun wordValidationError(word: String): String? = + when { + word.isEmpty() -> "Saisissez un mot." + word.length > 64 -> "Le mot ne doit pas dépasser 64 caractères." + word.any(Char::isWhitespace) -> "Saisissez un seul mot à la fois." + else -> null + } + private fun removeWord(word: String) { busy = true statusIsError = false @@ -178,5 +237,8 @@ class PersonalDictionaryActivity : ComponentActivity() { private companion object { const val STATE_INPUT = "personal_dictionary_input" + const val STATE_EDIT_ORIGINAL = "personal_dictionary_edit_original" + const val STATE_EDIT_INPUT = "personal_dictionary_edit_input" + const val DUPLICATE_MESSAGE = "Ce mot est déjà dans le dictionnaire." } } diff --git a/app/src/main/kotlin/fr/zefut/grammalecte/PersonalDictionaryScreen.kt b/app/src/main/kotlin/fr/zefut/grammalecte/PersonalDictionaryScreen.kt index c38be8b..5b8b33a 100644 --- a/app/src/main/kotlin/fr/zefut/grammalecte/PersonalDictionaryScreen.kt +++ b/app/src/main/kotlin/fr/zefut/grammalecte/PersonalDictionaryScreen.kt @@ -3,6 +3,7 @@ package fr.zefut.grammalecte import androidx.compose.foundation.background import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize @@ -17,6 +18,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.ArrowBack +import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults @@ -27,11 +29,13 @@ import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.semantics @@ -39,6 +43,12 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.dp +internal data class DictionaryEditState( + val original: String, + val input: String, + val error: String? = null, +) + @Composable internal fun PersonalDictionaryScreen( input: String, @@ -46,9 +56,14 @@ internal fun PersonalDictionaryScreen( status: String, statusIsError: Boolean, busy: Boolean, + edit: DictionaryEditState?, onInputChange: (String) -> Unit, onAdd: () -> Unit, onRemove: (String) -> Unit, + onEdit: (String) -> Unit, + onEditInputChange: (String) -> Unit, + onEditConfirm: () -> Unit, + onEditCancel: () -> Unit, onBack: () -> Unit, ) { MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkPalette else lightPalette) { @@ -147,25 +162,101 @@ internal fun PersonalDictionaryScreen( shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant), ) { - Row( + Column( modifier = Modifier.fillMaxWidth().padding(12.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, + verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text( word, style = MaterialTheme.typography.bodyLarge, - modifier = Modifier.weight(1f), ) - OutlinedButton( - onClick = { onRemove(word) }, - enabled = !busy, - modifier = Modifier.heightIn(min = 48.dp), - ) { Text("Supprimer") } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton( + onClick = { onEdit(word) }, + enabled = !busy, + modifier = + Modifier + .weight(1f) + .heightIn(min = 48.dp) + .semantics { contentDescription = "Modifier $word" } + .testTag("dictionary-edit-$word"), + ) { Text("Modifier") } + OutlinedButton( + onClick = { onRemove(word) }, + enabled = !busy, + modifier = + Modifier + .weight(1f) + .heightIn(min = 48.dp) + .semantics { contentDescription = "Supprimer $word" }, + ) { Text("Supprimer") } + } } } } } } + + if (edit != null) { + DictionaryEditDialog( + edit = edit, + busy = busy, + onInputChange = onEditInputChange, + onConfirm = onEditConfirm, + onCancel = onEditCancel, + ) + } } } + +@Composable +private fun DictionaryEditDialog( + edit: DictionaryEditState, + busy: Boolean, + onInputChange: (String) -> Unit, + onConfirm: () -> Unit, + onCancel: () -> Unit, +) { + AlertDialog( + onDismissRequest = { if (!busy) onCancel() }, + title = { Text("Modifier le mot") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = edit.input, + onValueChange = onInputChange, + enabled = !busy, + singleLine = true, + isError = edit.error != null, + label = { Text("Mot corrigé") }, + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.None), + modifier = Modifier.fillMaxWidth().testTag("dictionary-edit-input"), + ) + edit.error?.let { error -> + Text( + error, + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodyMedium, + modifier = + Modifier + .semantics { liveRegion = LiveRegionMode.Polite } + .testTag("dictionary-edit-error"), + ) + } + if (busy) { + Text("Enregistrement…") + } + } + }, + confirmButton = { + TextButton(onClick = onConfirm, enabled = !busy) { + Text("Enregistrer") + } + }, + dismissButton = { + TextButton(onClick = onCancel, enabled = !busy) { + Text("Annuler") + } + }, + ) +} diff --git a/engine-grammalecte/src/main/kotlin/fr/grammalecteandroid/engine/GrammalecteQuickJsEngine.kt b/engine-grammalecte/src/main/kotlin/fr/grammalecteandroid/engine/GrammalecteQuickJsEngine.kt index 731968c..8a5ebac 100644 --- a/engine-grammalecte/src/main/kotlin/fr/grammalecteandroid/engine/GrammalecteQuickJsEngine.kt +++ b/engine-grammalecte/src/main/kotlin/fr/grammalecteandroid/engine/GrammalecteQuickJsEngine.kt @@ -20,6 +20,13 @@ internal data class GrammalecteRuntimeMemorySnapshot( val stringCount: Long, ) +enum class PersonalDictionaryEditResult { + REPLACED, + UNCHANGED, + DUPLICATE, + MISSING, +} + class GrammalecteQuickJsEngine internal constructor( private val assetLoader: AssetTextLoader, private val rulePreferences: GrammalecteRulePreferences? = null, @@ -175,6 +182,45 @@ class GrammalecteQuickJsEngine internal constructor( } } + fun replacePersonalDictionaryWord( + original: String, + replacement: String, + ): PersonalDictionaryEditResult { + val normalizedOriginal = original.trim() + val normalizedReplacement = normalizePersonalDictionaryWords(listOf(replacement)).single() + + synchronized(lock) { + synchronizeStoredPersonalDictionary() + val current = appliedPersonalDictionaryWords.orEmpty() + if (normalizedOriginal !in current) return PersonalDictionaryEditResult.MISSING + if (normalizedOriginal == normalizedReplacement) return PersonalDictionaryEditResult.UNCHANGED + if (normalizedReplacement in current) return PersonalDictionaryEditResult.DUPLICATE + + val updated = + normalizePersonalDictionaryWords( + current.map { word -> if (word == normalizedOriginal) normalizedReplacement else word }, + ) + + // Validate and install the complete replacement before changing persistent storage. + // If the runtime rejects it, retain the original stored dictionary. + try { + applyPersonalDictionaryWords(updated) + } catch (error: Throwable) { + runCatching { applyPersonalDictionaryWords(current) } + .exceptionOrNull() + ?.let { + appliedPersonalDictionaryWords = null + error.addSuppressed(it) + } + throw error + } + + personalDictionaryPreferences?.replace(updated) + appliedPersonalDictionaryWords = updated + return PersonalDictionaryEditResult.REPLACED + } + } + fun removePersonalDictionaryWord(word: String): Boolean { val normalizedWord = word.trim()