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
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ import java.util.concurrent.TimeUnit
* instantiate and select the correct dictionaries (based on language and settings), update entries
* and fetch suggestions.
*/
/** a word in the learning history; [count] is how often it was used (decays over time) */
data class LearnedWord(val word: String, val locale: Locale, val count: Int)

interface DictionaryFacilitator {

interface DictionaryInitializationListener {
Expand Down Expand Up @@ -144,6 +147,12 @@ interface DictionaryFacilitator {

fun clearUserHistoryDictionary(context: Context)

/** words in the learning history of the current languages, for the learned words screen; may block, not on the UI thread */
fun getLearnedWords(): List<LearnedWord> = emptyList()

/** remove one word from the learning history of [locale] */
fun removeLearnedWord(word: String, locale: Locale) {}

fun dump(context: Context): String

fun dumpDictionaryForDebug(dictName: String)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,20 @@ class DictionaryFacilitatorImpl : DictionaryFacilitator {
}
}

override fun getLearnedWords(): List<LearnedWord> = dictionaryGroups.flatMap { group ->
val dict = group.getSubDict(Dictionary.TYPE_USER_HISTORY) ?: return@flatMap emptyList()
dict.getWordPropertiesForSyncing(LEARNED_WORDS_TIMEOUT_MS)
.filter { !it.mIsNotAWord && !it.mIsBeginningOfSentence && it.mWord.isNotEmpty() }
.map { LearnedWord(it.mWord, group.locale, it.mProbabilityInfo.mCount) }
}

override fun removeLearnedWord(word: String, locale: Locale) {
for (group in dictionaryGroups) {
if (group.locale == locale) group.getSubDict(Dictionary.TYPE_USER_HISTORY)?.removeUnigramEntryDynamically(word)
}
sessionWordBoost?.removeWord(word)
}

override fun clearUserHistoryDictionary(context: Context) {
sessionWordBoost?.clear()
gestureWordBias?.clear()
Expand Down Expand Up @@ -1084,6 +1098,8 @@ class DictionaryFacilitatorImpl : DictionaryFacilitator {

// HACK: This threshold is being used when adding a capitalized entry in the User History dictionary.
private const val CAPITALIZED_FORM_MAX_PROBABILITY_FOR_INSERT = 140
// reading a large learning history word by word takes longer than the usual 100 ms
private const val LEARNED_WORDS_TIMEOUT_MS = 3000L

// Multiplier to convert session boost values into native score-space (native scores are ~0-255)
private const val BOOST_SCORE_MULTIPLIER = 1.0f
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@ abstract class ExpandableBinaryDictionary(
})
}

fun getWordPropertiesForSyncing(): Array<WordProperty> {
fun getWordPropertiesForSyncing(timeoutMs: Long = TIMEOUT_FOR_READ_OPS_IN_MILLISECONDS.toLong()): Array<WordProperty> {
reloadDictionaryIfRequired()
val result = AsyncResultHolder<Array<WordProperty>>("WordPropertiesForSync")
asyncExecuteTaskWithLock(mLock.readLock(), Runnable {
Expand All @@ -519,7 +519,7 @@ abstract class ExpandableBinaryDictionary(
result.set(wordPropertyList.toTypedArray())
}
})
return result.get(DEFAULT_WORD_PROPERTIES_FOR_SYNC, TIMEOUT_FOR_READ_OPS_IN_MILLISECONDS.toLong()) ?: DEFAULT_WORD_PROPERTIES_FOR_SYNC
return result.get(DEFAULT_WORD_PROPERTIES_FOR_SYNC, timeoutMs) ?: DEFAULT_WORD_PROPERTIES_FOR_SYNC
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ class Settings private constructor() : SharedPreferences.OnSharedPreferenceChang
const val PREF_ALWAYS_SHOW_SUGGESTIONS = "always_show_suggestions"
const val PREF_ALWAYS_SHOW_SUGGESTIONS_EXCEPT_WEB_TEXT = "always_show_suggestions_except_web_text"
const val PREF_KEY_USE_PERSONALIZED_DICTS = "use_personalized_dicts"
const val PREF_CLEAR_LEARNED_WORDS = "pref_clear_learned_words"
const val PREF_LEARNED_WORDS = "pref_learned_words"
const val PREF_KEY_USE_DOUBLE_SPACE_PERIOD = "use_double_space_period"
const val PREF_BLOCK_POTENTIALLY_OFFENSIVE = "block_potentially_offensive"
const val PREF_SHOW_LANGUAGE_SWITCH_KEY = "show_language_switch_key"
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/helium314/keyboard/settings/SearchScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,8 @@ fun <T: Any?> SearchScreen(
menu: List<Pair<String, () -> Unit>>? = null,
headerContent: (@Composable () -> Unit)? = null,
content: @Composable (ColumnScope.() -> Unit)? = null,
/** more top bar buttons, after the search button */
actions: (@Composable () -> Unit)? = null,
) {
// searchText and showSearch should have the same remember or rememberSaveable
// saveable survives orientation changes and switching between screens, but shows the
Expand Down Expand Up @@ -325,6 +327,7 @@ fun <T: Any?> SearchScreen(
IconButton(onClick = { setShowSearch(!showSearch) }) { SearchIcon() }
else
icon()
actions?.invoke()
if (menu != null)
Box {
var showMenu by remember { mutableStateOf(false) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import helium314.keyboard.settings.screens.MainSettingsScreen
import helium314.keyboard.settings.screens.PersonalDictionariesScreen
import helium314.keyboard.settings.screens.PersonalDictionaryScreen
import helium314.keyboard.settings.screens.BlockedWordsScreen
import helium314.keyboard.settings.screens.LearnedWordsScreen
import helium314.keyboard.settings.screens.PreferencesScreen
import helium314.keyboard.settings.screens.SecondaryLayoutScreen
import helium314.keyboard.settings.screens.SoundSettingsScreen
Expand Down Expand Up @@ -199,6 +200,9 @@ fun SettingsNavHost(
composable(SettingsDestination.BlockedWords) {
BlockedWordsScreen(onClickBack = ::goBack)
}
composable(SettingsDestination.LearnedWords) {
LearnedWordsScreen(onClickBack = ::goBack)
}
composable(SettingsDestination.Languages) {
LanguageScreen(onClickBack = ::goBack)
}
Expand Down Expand Up @@ -275,6 +279,7 @@ object SettingsDestination {
const val PersonalDictionaries = "personal_dictionaries"
const val PersonalDictionary = "personal_dictionary/"
const val BlockedWords = "blocked_words"
const val LearnedWords = "learned_words"
const val Languages = "languages"
const val LanguagesList = "languages_list"
const val Subtype = "subtype/"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package helium314.keyboard.settings.screens

import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
Expand Down Expand Up @@ -31,7 +30,6 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
Expand All @@ -44,7 +42,6 @@ import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.content.edit
import helium314.keyboard.latin.dictionary.Dictionary
import helium314.keyboard.latin.personalization.PersonalizationHelper
import helium314.keyboard.latin.R
import helium314.keyboard.latin.common.Links
import helium314.keyboard.latin.common.LocaleUtils
Expand All @@ -59,7 +56,6 @@ import helium314.keyboard.latin.utils.locale
import helium314.keyboard.latin.utils.withHtmlLink
import helium314.keyboard.settings.SearchScreen
import helium314.keyboard.settings.Theme
import helium314.keyboard.settings.dialogs.ConfirmationDialog
import helium314.keyboard.settings.dialogs.DictionaryDialog
import helium314.keyboard.settings.dictionaryFilePicker
import helium314.keyboard.settings.initPreview
Expand Down Expand Up @@ -89,7 +85,6 @@ fun DictionaryScreen(
.sortedWith(comparer)
var selectedLocale: Locale? by remember { mutableStateOf(null) }
var showAddDictDialog by remember { mutableStateOf(false) }
var showClearHistoryDialog by rememberSaveable { mutableStateOf(false) }
val dictPicker = dictionaryFilePicker(selectedLocale)

SearchScreen(
Expand Down Expand Up @@ -141,12 +136,12 @@ fun DictionaryScreen(
value = { NextScreenIcon() }
)

// Clear Learned Words Entry
Preference(
name = stringResource(R.string.clear_learned_words_title),
description = stringResource(R.string.clear_learned_words_summary),
icon = R.drawable.ic_clear_all,
onClick = { showClearHistoryDialog = true }
name = stringResource(R.string.learned_words),
description = stringResource(R.string.learned_words_summary),
icon = R.drawable.ic_dictionary,
onClick = { SettingsDestination.navigateTo(SettingsDestination.LearnedWords) },
value = { NextScreenIcon() }
)

// Dictionary Source Entry
Expand Down Expand Up @@ -319,16 +314,6 @@ fun DictionaryScreen(
}
}
)
if (showClearHistoryDialog) {
ConfirmationDialog(
onDismissRequest = { showClearHistoryDialog = false },
onConfirmed = {
PersonalizationHelper.clearUserHistory(ctx)
Toast.makeText(ctx, ctx.getString(R.string.clear_learned_words_success), Toast.LENGTH_SHORT).show()
},
content = { Text(stringResource(R.string.clear_learned_words_confirmation)) }
)
}
if (showAddDictDialog) {
PreferenceDialog(
onDismissRequest = { showAddDictDialog = false },
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// SPDX-License-Identifier: GPL-3.0-only
package helium314.keyboard.settings.screens

import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import helium314.keyboard.latin.LatinIME
import helium314.keyboard.latin.LearnedWord
import helium314.keyboard.latin.R
import helium314.keyboard.latin.personalization.PersonalizationHelper
import helium314.keyboard.settings.SearchScreen
import helium314.keyboard.settings.dialogs.ConfirmationDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/** most used first, then alphabetical */
internal fun sortLearnedWords(words: List<LearnedWord>): List<LearnedWord> =
words.sortedWith(compareByDescending<LearnedWord> { it.count }.thenBy { it.word.lowercase(it.locale) })

/** The learning history of the keyboard's current languages: view, search and delete single words (#948). */
@Composable
fun LearnedWordsScreen(onClickBack: () -> Unit) {
val ctx = LocalContext.current
var words: List<LearnedWord>? by remember { mutableStateOf(null) }
var showClearDialog by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
// the history is held by the running keyboard, reading it waits for its dictionary thread
words = withContext(Dispatchers.IO) {
sortLearnedWords(LatinIME.getInstance()?.getDictionaryFacilitator()?.getLearnedWords().orEmpty())
}
}
val list = words
SearchScreen(
onClickBack = onClickBack,
title = { Text(if (list == null) stringResource(R.string.learned_words) else "${stringResource(R.string.learned_words)} (${list.size})") },
filteredItems = { term -> list.orEmpty().filter { it.word.startsWith(term, ignoreCase = true) } },
actions = {
IconButton(onClick = { showClearDialog = true }) {
Icon(painterResource(R.drawable.ic_clear_all), stringResource(R.string.clear_learned_words_title))
}
},
content = if (list != null && list.isEmpty()) { {
Text(
stringResource(R.string.learned_words_empty),
modifier = Modifier.padding(16.dp),
color = MaterialTheme.colorScheme.onSurfaceVariant
)
} } else null,
itemContent = { item ->
Card(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp, horizontal = 16.dp)
) {
Column(modifier = Modifier.weight(1f)) {
Text(item.word, style = MaterialTheme.typography.bodyLarge)
Text(
item.locale.getLocaleDisplayNameForUserDictSettings(ctx),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = {
LatinIME.getInstance()?.getDictionaryFacilitator()?.removeLearnedWord(item.word, item.locale)
words = words?.minus(item)
}) {
Icon(painterResource(R.drawable.ic_bin), stringResource(R.string.delete))
}
}
}
}
)
if (showClearDialog) {
ConfirmationDialog(
onDismissRequest = { showClearDialog = false },
onConfirmed = {
showClearDialog = false
PersonalizationHelper.clearUserHistory(ctx)
words = emptyList()
Toast.makeText(ctx, ctx.getString(R.string.clear_learned_words_success), Toast.LENGTH_SHORT).show()
},
title = { Text(stringResource(R.string.clear_learned_words_title)) },
content = { Text(stringResource(R.string.clear_learned_words_details)) },
confirmButtonText = stringResource(R.string.clear_all),
cancelButtonText = stringResource(android.R.string.cancel),
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.Toast
import android.provider.Settings as AndroidSettings
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
Expand All @@ -31,7 +30,6 @@ import androidx.core.content.edit
import helium314.keyboard.dictionarypack.DictionaryPackConstants
import helium314.keyboard.keyboard.KeyboardSwitcher
import helium314.keyboard.latin.R
import helium314.keyboard.latin.personalization.PersonalizationHelper
import helium314.keyboard.latin.permissions.PermissionsUtil
import helium314.keyboard.latin.settings.Defaults
import helium314.keyboard.latin.settings.Settings
Expand All @@ -44,6 +42,8 @@ import helium314.keyboard.settings.SearchSettingsScreen
import helium314.keyboard.settings.Setting
import helium314.keyboard.settings.SettingsActivity
import helium314.keyboard.settings.Theme
import helium314.keyboard.settings.NextScreenIcon
import helium314.keyboard.settings.SettingsDestination
import helium314.keyboard.settings.dialogs.ConfirmationDialog
import helium314.keyboard.settings.initPreview
import helium314.keyboard.settings.preferences.ExpandablePreference
Expand Down Expand Up @@ -87,7 +87,7 @@ fun SuggestionsScreen(
Settings.PREF_BIGRAM_PREDICTIONS,
if (bigramPredictionsEnabled) Settings.PREF_SUGGESTION_BALANCE else null,
Settings.PREF_KEY_USE_PERSONALIZED_DICTS,
Settings.PREF_CLEAR_LEARNED_WORDS,
Settings.PREF_LEARNED_WORDS,
if (bigramPredictionsEnabled) Settings.PREF_EXPAND_FINE_TUNE_PREDICTION else null,
if (bigramPredictionsEnabled && fineTunePredictionExpanded) Settings.PREF_PRIORITIZE_PERSONAL_SUGGESTIONS else null,
if (bigramPredictionsEnabled && fineTunePredictionExpanded) Settings.PREF_NEXT_WORD_STRICT_NGRAM else null,
Expand Down Expand Up @@ -171,27 +171,14 @@ fun createSuggestionsSettings(context: Context) = listOf(
)
}
},
Setting(context, Settings.PREF_CLEAR_LEARNED_WORDS,
R.string.clear_learned_words_title, R.string.clear_learned_words_summary
) { setting ->
var showConfirmDialog by rememberSaveable { mutableStateOf(false) }
val ctx = LocalContext.current
Setting(context, Settings.PREF_LEARNED_WORDS, R.string.learned_words, R.string.learned_words_summary) { setting ->
Preference(
name = setting.title,
description = setting.description,
icon = R.drawable.ic_clear_all,
onClick = { showConfirmDialog = true }
icon = R.drawable.ic_dictionary,
onClick = { SettingsDestination.navigateTo(SettingsDestination.LearnedWords) },
value = { NextScreenIcon() }
)
if (showConfirmDialog) {
ConfirmationDialog(
onDismissRequest = { showConfirmDialog = false },
onConfirmed = {
PersonalizationHelper.clearUserHistory(ctx)
Toast.makeText(ctx, ctx.getString(R.string.clear_learned_words_success), Toast.LENGTH_SHORT).show()
},
content = { Text(stringResource(R.string.clear_learned_words_confirmation)) }
)
}
},
Setting(context, Settings.PREF_BIGRAM_PREDICTIONS,
R.string.bigram_prediction, R.string.bigram_prediction_summary
Expand Down
Loading
Loading