Language: the account's by default, Settings › Language, per-app locale
CI / check (push) Canceled after 0s

The app followed the phone's locale, so a Slovak phone showed Slovak while the
instance and the account were English. Now the default is the account's
language from /api/v2/me (read once per instance in use, kept in Prefs), and
Settings › Language offers Same as my account / Phone language / each language
the app has, named in itself.

Android 13+: LocaleManager.setApplicationLocales, and android:localeConfig
(res/xml/locales_config.xml, written by gen-strings.py from LANGS) so the
system's per-app language lists the same set; a choice made there is adopted
as the person's. Older phones: the chosen tag in a small synchronous file,
applied in attachBaseContext of every activity and to the assistant's window.
No AppCompat: the framework API covers it.

LanguageTest holds the offered list, the values-* folders and the locale
config equal. Screenshot 17-language.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Opus 5.5 committed 2026-11-10 08:06:47 +00:00
1 parent 6828dbd844
commit 37cf778c44
25 files changed
+467 -4

No files matched your search

@@ -0,0 +1,109 @@
package eu.llembas.android
import android.app.Activity
import android.app.LocaleManager
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.os.LocaleList
import java.util.Locale
/**
* The app's language. By default the account's, from the server (`/api/v2/me`'s `language`), so
* a phone set to one language shows the app in the language the person chose on their instance;
* Settings › Language can choose the phone's language instead, or any language the app has.
*
* Android 13 and newer keep a per-app language themselves (`LocaleManager`, and the system's own
* Settings › Apps › LLeMbas › Language, which `res/xml/locales_config.xml` feeds). Older phones
* have none: there the chosen language is kept in a small synchronous file and every activity
* wraps its context in it ([wrap]), because the DataStore is read too late for `attachBaseContext`.
*/
object AppLanguage {
/** Prefs.language: the account's language (the default). */
const val ACCOUNT = ""
/** Prefs.language: the phone's language. */
const val PHONE = "system"
/**
* The languages the app has, by code, each named in itself. The same set as the
* `values-*` folders `scripts/gen-strings.py` writes, plus English; a test holds them equal.
*/
val LANGUAGES: List<Pair<String, String>> = listOf(
"en" to "English",
"cs" to "Čeština",
"de" to "Deutsch",
"es" to "Español",
"fr" to "Français",
"hu" to "Magyar",
"it" to "Italiano",
"pl" to "Polski",
"sk" to "Slovenčina",
)
private val CODES = LANGUAGES.map { it.first }.toSet()
/** A language's own name, or null for one the app does not have. */
fun name(code: String?): String? = LANGUAGES.firstOrNull { it.first == code?.lowercase()?.substringBefore('-')?.substringBefore('_') }?.second
/** The app's code for a server's language (`sk`, `pt_BR` -> `pt`), or null if the app lacks it. */
fun known(code: String?): String? = code?.trim()?.lowercase()?.substringBefore('-')?.substringBefore('_')?.takeIf { it in CODES }
/**
* The language the app should be in: a language tag, or null for the phone's own.
* [choice] is Prefs.language; [account] the account's language as the server last said it.
* An account in a language the app does not have follows the phone, rather than English.
*/
fun effective(choice: String, account: String): String? = when (choice) {
ACCOUNT -> known(account)
PHONE -> null
else -> known(choice)
}
private const val FILE = "language"
private const val APPLIED = "applied"
/** What [apply] last set; null if it never ran. */
fun applied(context: Context): String? = context.getSharedPreferences(FILE, Context.MODE_PRIVATE).getString(APPLIED, null)
/**
* What the system says the app's language is now (Android 13+): "" for the phone's. Differs
* from [applied] when the person chose a language in the system's settings for the app.
*/
fun systemChoice(context: Context): String? {
if (Build.VERSION.SDK_INT < 33) return null
val locales = context.getSystemService(LocaleManager::class.java)?.applicationLocales ?: return null
return if (locales.isEmpty) "" else locales[0].language
}
/**
* Put the app in [tag] (null: the phone's language). Does nothing when that is already so,
* so a running app is not recreated for nothing. Android 13+ recreates the activities
* itself; an older phone recreates [activity].
*/
fun apply(context: Context, tag: String?, activity: Activity? = null) {
val value = tag.orEmpty()
if (applied(context) == value && (Build.VERSION.SDK_INT < 33 || systemChoice(context) == value)) return
context.getSharedPreferences(FILE, Context.MODE_PRIVATE).edit().putString(APPLIED, value).commit()
if (Build.VERSION.SDK_INT >= 33) {
context.getSystemService(LocaleManager::class.java)?.applicationLocales =
if (value.isEmpty()) LocaleList.getEmptyLocaleList() else LocaleList.forLanguageTags(value)
} else {
activity?.recreate()
}
}
/**
* [base] in the chosen language, for `attachBaseContext` and for a window that is not an
* activity's (the assistant's sheet). Android 13+ does this itself; the context is returned
* as it is there.
*/
fun wrap(base: Context): Context {
if (Build.VERSION.SDK_INT >= 33) return base
val tag = base.getSharedPreferences(FILE, Context.MODE_PRIVATE).getString(APPLIED, null)
if (tag.isNullOrEmpty()) return base
val locale = Locale.forLanguageTag(tag)
val config = Configuration(base.resources.configuration).apply { setLocales(LocaleList(locale)) }
return base.createConfigurationContext(config)
}
}
@@ -1,6 +1,7 @@
package eu.llembas.android
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
@@ -49,6 +50,7 @@ import eu.llembas.android.ui.scheduled.SchedulingModelsScreen
import eu.llembas.android.ui.settings.SettingsScreen
import eu.llembas.android.ui.signin.SignInScreen
import eu.llembas.android.ui.theme.LembasTheme
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
@@ -62,10 +64,13 @@ class MainActivity : ComponentActivity() {
/** A chat or a schedule a notification, the assistant or a share asked to open; consumed once. */
private val opening = mutableStateOf<Opening?>(null)
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
take(intent)
followLanguage()
if (Build.VERSION.SDK_INT >= 33 &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
) {
@@ -79,6 +84,25 @@ class MainActivity : ComponentActivity() {
}
}
/**
* Keep the app in the language Settings › Language says: the account's by default. A
* language chosen for the app in the system's own settings (Android 13+) since the app last
* set one is the person's choice, and is kept as such.
*/
private fun followLanguage() {
lifecycleScope.launch {
val store = lembas.instances
val system = AppLanguage.systemChoice(this@MainActivity)
if (system != null && system != AppLanguage.applied(this@MainActivity).orEmpty()) {
store.savePrefs { it.copy(language = system.ifEmpty { AppLanguage.PHONE }) }
}
store.prefs
.map { AppLanguage.effective(it.language, it.accountLanguage) }
.distinctUntilChanged()
.collect { AppLanguage.apply(applicationContext, it, this@MainActivity) }
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
take(intent)
@@ -141,6 +165,13 @@ class MainActivity : ComponentActivity() {
scope.launch { drawer.close() }
nav.navigate(target)
}
// The account's language, which the app follows unless Settings › Language says
// otherwise. Read once per instance in use; kept, so the next start has it at once.
LaunchedEffect(instance.id) {
runCatching { lembas.instances.clientFor(instance).me() }.onSuccess { me ->
if (me.language.isNotBlank()) lembas.instances.savePrefs { it.copy(accountLanguage = me.language) }
}
}
// The list is read again each time the drawer opens, so a new title or a finished
// reply's dot is there without a pull.
LaunchedEffect(drawer.isOpen) { if (drawer.isOpen) chats.load() }
@@ -2,6 +2,7 @@ package eu.llembas.android.assist
import android.Manifest
import android.app.KeyguardManager
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
@@ -20,6 +21,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.lifecycleScope
import eu.llembas.android.AppLanguage
import eu.llembas.android.auth.Prefs
import eu.llembas.android.lembas
import eu.llembas.android.ui.theme.LembasTheme
@@ -36,6 +38,8 @@ class AssistActivity : ComponentActivity() {
if (granted) controller.listen()
}
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
@@ -20,6 +20,7 @@ import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryController
import androidx.savedstate.SavedStateRegistryOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import eu.llembas.android.AppLanguage
import eu.llembas.android.lembas
import eu.llembas.android.ui.theme.LembasTheme
import kotlinx.coroutines.CoroutineScope
@@ -66,7 +67,8 @@ class LembasAssistSession(context: Context) :
override fun onCreateContentView(): View {
val theme = runBlocking { context.lembas.instances.prefs.first() }.theme
return ComposeView(context).apply {
// In the app's language on a phone older than Android 13, which has no per-app one.
return ComposeView(AppLanguage.wrap(context)).apply {
setViewTreeLifecycleOwner(this@LembasAssistSession)
setViewTreeSavedStateRegistryOwner(this@LembasAssistSession)
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow)
@@ -66,9 +66,19 @@ private val INSTANCES = stringPreferencesKey("instances")
private val ACTIVE = stringPreferencesKey("active")
private val PREFS = stringPreferencesKey("prefs")
/** What the person chose in Settings, for this phone. */
/**
* What the person chose in Settings, for this phone. [language]: "" the account's language (the
* default), "system" the phone's, or a language's code -- see [eu.llembas.android.AppLanguage].
* [accountLanguage] is the account's language as the instance in use last said it.
*/
@Serializable
data class Prefs(val theme: String = "", val assistantTemporary: Boolean = false, val readAloudSpoken: Boolean = true)
data class Prefs(
val theme: String = "",
val assistantTemporary: Boolean = false,
val readAloudSpoken: Boolean = true,
val language: String = "",
val accountLanguage: String = "",
)
class InstanceStore(private val context: Context) {
private val listSerializer = ListSerializer(Instance.serializer())
@@ -1,5 +1,6 @@
package eu.llembas.android.share
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
@@ -22,6 +23,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.content.IntentCompat
import androidx.lifecycle.lifecycleScope
import eu.llembas.android.AppLanguage
import eu.llembas.android.MainActivity
import eu.llembas.android.R
import eu.llembas.android.lembas
@@ -39,6 +41,8 @@ import kotlinx.coroutines.withContext
class ShareActivity : ComponentActivity() {
private val failure = mutableStateOf<String?>(null)
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
@@ -34,10 +34,12 @@ import androidx.compose.material.icons.filled.Palette
import androidx.compose.material.icons.filled.RecordVoiceOver
import androidx.compose.material.icons.filled.SystemUpdate
import androidx.compose.material.icons.filled.Timer
import androidx.compose.material.icons.filled.Translate
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
@@ -45,6 +47,7 @@ import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@@ -62,6 +65,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.llembas.android.AppLanguage
import eu.llembas.android.BuildConfig
import eu.llembas.android.R
import eu.llembas.android.auth.Instance
@@ -78,6 +82,7 @@ interface SettingsActions {
fun add() {}
fun signOut(instance: Instance) {}
fun theme(value: String) {}
fun language(value: String) {}
fun enablePush(instance: Instance) {}
fun notificationSettings() {}
fun assistantSettings() {}
@@ -129,6 +134,11 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
scope.launch { store.savePrefs { it.copy(theme = value) } }
}
// MainActivity follows the choice: it puts the app in the language at once.
override fun language(value: String) {
scope.launch { store.savePrefs { it.copy(language = value) } }
}
override fun enablePush(instance: Instance) {
(context as? Activity)?.let { activity ->
Push.enable(activity, instance) { ok -> pushNote = context.getString(if (ok) R.string.push_on else R.string.push_failed) }
@@ -184,6 +194,15 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
@Composable
fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -> Unit = {}) {
val palette = LocalPalette.current
var choosingLanguage by remember { mutableStateOf(false) }
if (choosingLanguage) {
ModalBottomSheet(onDismissRequest = { choosingLanguage = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
LanguageChoices(state.prefs, onPick = {
choosingLanguage = false
actions.language(it)
})
}
}
Scaffold(
containerColor = palette.bg,
topBar = {
@@ -248,6 +267,16 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
}
}
}
item {
Group(stringResource(R.string.settings_language)) {
SettingRow(
Icons.Filled.Translate,
languageLabel(state.prefs),
subtitle = stringResource(R.string.language_hint),
onClick = { choosingLanguage = true },
)
}
}
item {
Group(stringResource(R.string.settings_theme)) {
listOf("" to R.string.theme_system, "moria" to R.string.theme_moria, "shire" to R.string.theme_shire).forEachIndexed { i, (value, label) ->
@@ -394,3 +423,70 @@ private fun Initial(name: String) {
Text(name.trim().firstOrNull()?.uppercase() ?: "?", style = MaterialTheme.typography.titleMedium, color = palette.accent)
}
}
/** The phone's own language, named in itself: what "Phone language" would show. */
private fun phoneLanguage(): String {
val locale = android.content.res.Resources.getSystem().configuration.locales[0]
return locale.getDisplayName(locale).replaceFirstChar { it.titlecase(locale) }
}
/** The language row's words: what is chosen, and for the account's, which language that is. */
@Composable
private fun languageLabel(prefs: Prefs): String = when (prefs.language) {
AppLanguage.ACCOUNT -> AppLanguage.name(prefs.accountLanguage)?.let { stringResource(R.string.language_account_is, it) }
?: stringResource(R.string.language_account)
AppLanguage.PHONE -> stringResource(R.string.language_phone_is, phoneLanguage())
else -> AppLanguage.name(prefs.language) ?: stringResource(R.string.language_account)
}
/**
* Settings › Language, as a sheet: the account's language (the default), the phone's, then every
* language the app has, each named in itself so a person who cannot read the current one still
* finds theirs.
*/
@Composable
fun LanguageChoices(prefs: Prefs, onPick: (String) -> Unit) {
val palette = LocalPalette.current
val choices = buildList {
add(
Triple(
AppLanguage.ACCOUNT,
stringResource(R.string.language_account),
AppLanguage.name(prefs.accountLanguage) ?: stringResource(R.string.language_account_unknown),
),
)
add(Triple(AppLanguage.PHONE, stringResource(R.string.language_phone), phoneLanguage()))
AppLanguage.LANGUAGES.forEach { (code, name) -> add(Triple(code, name, null)) }
}
LazyColumn(Modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 24.dp)) {
item {
Text(
stringResource(R.string.settings_language),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp),
)
}
choices.forEachIndexed { i, (value, title, subtitle) ->
item(key = "lang-$value-$i") {
if (i == 2) HorizontalDivider(color = palette.border, modifier = Modifier.padding(vertical = 4.dp))
Row(
Modifier
.fillMaxWidth()
.clickable { onPick(value) }
.heightIn(min = 56.dp)
.padding(horizontal = 24.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.bodyLarge)
subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
}
Spacer(Modifier.width(12.dp))
RadioButton(selected = prefs.language == value, onClick = { onPick(value) })
}
}
}
}
}