From 08aa657e240eee72e425adc663bf0cf8b21dbf3a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 10:19:36 +0000 Subject: [PATCH 1/3] =?UTF-8?q?Easter=20egg:=20a=20fairy=20transformation?= =?UTF-8?q?=20and=20a=20pink=20theme=20for=20Tat=C3=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the profile name is Tatá, Tata or Thaissa (any case, accents or surname), the app plays a one-time transformation: a rose glow, a wand's trail of stars, a burst of hearts and stars, and the app turning pink underneath. From then on the brand colours are pink with plum ink, and the bitmap dither is replaced by smooth washes. Another name turns it off. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../main/java/com/pulseloop/MainActivity.kt | 34 +++- .../com/pulseloop/PulseLoopApplication.kt | 1 + .../main/java/com/pulseloop/data/dao/Daos.kt | 3 + .../pulseloop/ui/components/FairyTransform.kt | 188 ++++++++++++++++++ .../java/com/pulseloop/ui/theme/Dither.kt | 16 ++ .../java/com/pulseloop/ui/theme/FairyMode.kt | 77 +++++++ .../com/pulseloop/ui/theme/PulseColors.kt | 16 +- .../main/java/com/pulseloop/ui/theme/Theme.kt | 5 +- .../com/pulseloop/ui/theme/FairyModeTest.kt | 21 ++ 9 files changed, 343 insertions(+), 18 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt create mode 100644 app/src/main/java/com/pulseloop/ui/theme/FairyMode.kt create mode 100644 app/src/test/java/com/pulseloop/ui/theme/FairyModeTest.kt diff --git a/app/src/main/java/com/pulseloop/MainActivity.kt b/app/src/main/java/com/pulseloop/MainActivity.kt index 3fcbd83a..07df5c39 100644 --- a/app/src/main/java/com/pulseloop/MainActivity.kt +++ b/app/src/main/java/com/pulseloop/MainActivity.kt @@ -7,6 +7,8 @@ import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box @@ -82,15 +84,29 @@ class MainActivity : ComponentActivity() { // (under the status bar, above the navigation bar) rather than at the window edge, where // the bars covered it. The bars' insets are consumed here, so nothing inside pads for // them a second time. - Box( - Modifier - .fillMaxSize() - .background(PulseColors.background) - .windowInsetsPadding(WindowInsets.systemBars.union(WindowInsets.displayCutout)) - .border(4.dp, PulseColors.frame) - .padding(4.dp), - ) { - PulseLoopApp() + // Tatá's Easter egg (ui/theme/FairyMode.kt): the profile's name decides the palette. + val profile by androidx.compose.runtime.remember { + com.pulseloop.data.PulseLoopDatabase.getInstance(applicationContext).userProfileDao().getFlow() + }.collectAsState(initial = null) + androidx.compose.runtime.LaunchedEffect(profile?.name) { + if (profile != null) com.pulseloop.ui.theme.FairyMode.onProfileName(profile?.name) + } + // The frame flows from mint to pink rather than snapping. + val frame by androidx.compose.animation.animateColorAsState( + PulseColors.frame, androidx.compose.animation.core.tween(1200), label = "frame", + ) + Box(Modifier.fillMaxSize()) { + Box( + Modifier + .fillMaxSize() + .background(PulseColors.background) + .windowInsetsPadding(WindowInsets.systemBars.union(WindowInsets.displayCutout)) + .border(4.dp, frame) + .padding(4.dp), + ) { + PulseLoopApp() + } + com.pulseloop.ui.components.FairyTransformOverlay(profile?.name) } } diff --git a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt index f2f771de..c9e05e45 100644 --- a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt +++ b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt @@ -27,6 +27,7 @@ class PulseLoopApplication : Application() { super.onCreate() CrashLogger.install(this) com.pulseloop.service.DrinkPrefs.init(this) + com.pulseloop.ui.theme.FairyMode.init(this) com.pulseloop.health.source.HealthConnectSource.isEnabled(this) // warms [HealthConnectSource.enabledNow] // Application-scoped so capture runs whether or not the Debug screen is open. DiagnosticsSubscriber(PulseLoopDatabase.getInstance(this)).start(appScope) diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index 3cd75fa7..1a72b4da 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -486,6 +486,9 @@ interface UserProfileDao { @Query("SELECT * FROM user_profiles LIMIT 1") suspend fun get(): UserProfileEntity? + @Query("SELECT * FROM user_profiles LIMIT 1") + fun getFlow(): kotlinx.coroutines.flow.Flow + @Upsert suspend fun upsert(profile: UserProfileEntity) } diff --git a/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt b/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt new file mode 100644 index 00000000..e797c775 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt @@ -0,0 +1,188 @@ +package com.pulseloop.ui.components + +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.tween +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.scale +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.rotate +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.sp +import com.pulseloop.ui.theme.FairyMode +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.sin +import kotlin.random.Random + +/** + * Tatá's transformation (see [FairyMode]): a rose glow, a wand's trail of stars sweeping in, a burst + * of hearts and stars, and the app turning pink underneath them. Plays once, over everything, and + * swallows touches while it does. + */ +@Composable +fun FairyTransformOverlay(name: String?) { + if (!FairyMode.celebrating) return + val reduceMotion = rememberReduceMotion() + val progress = remember { Animatable(0f) } + val particles = remember { sparkles(if (reduceMotion) 18 else 90) } + + LaunchedEffect(Unit) { + val total = if (reduceMotion) 1400 else 4200 + progress.animateTo(0.45f, tween((total * 0.45f).toInt(), easing = LinearEasing)) + FairyMode.transform() + progress.animateTo(1f, tween((total * 0.55f).toInt(), easing = LinearEasing)) + FairyMode.celebrationDone() + } + + val p = progress.value + // Fade in over the first 12 %, hold, fade out over the last 15 %. + val veil = when { + p < 0.12f -> p / 0.12f + p > 0.85f -> (1f - p) / 0.15f + else -> 1f + }.coerceIn(0f, 1f) + + Box( + Modifier.fillMaxSize().pointerInput(Unit) { + awaitPointerEventScope { while (true) awaitPointerEvent().changes.forEach { it.consume() } } + }, + contentAlignment = Alignment.Center, + ) { + Canvas(Modifier.fillMaxSize()) { + val center = Offset(size.width / 2, size.height / 2) + val radius = maxOf(size.width, size.height) + // The glow: deep plum at the edges, rose at the heart, brightest at the moment of change. + val flash = (1f - kotlin.math.abs(p - 0.45f) / 0.2f).coerceIn(0f, 1f) + drawRect( + Brush.radialGradient( + listOf( + Color(0xFFFFD6EC).copy(alpha = 0.55f * veil + 0.35f * flash), + Color(0xFFFF5FA8).copy(alpha = 0.45f * veil), + Color(0xFF2A0A1E).copy(alpha = 0.85f * veil), + ), + center = center, radius = radius * (0.35f + 0.5f * p), + ), + ) + if (!reduceMotion) wandTrail(p, veil) + particles.forEach { drawParticle(it, p, center, radius) } + } + val textIn = ((p - 0.42f) / 0.18f).coerceIn(0f, 1f) + Column( + Modifier.alpha(textIn * veil).scale(0.7f + 0.3f * textIn), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + "Oi, ${name?.trim()?.split(Regex("\\s+"))?.firstOrNull() ?: "Tatá"} ✨", + fontSize = 34.sp, fontWeight = FontWeight.Bold, color = Color.White, textAlign = TextAlign.Center, + ) + Text( + "Feito com amor pra você 💗", + fontSize = 16.sp, color = Color(0xFFFFE3F1), textAlign = TextAlign.Center, + ) + } + } +} + +private enum class SparkleShape { STAR, HEART, DOT } + +private class Sparkle( + val shape: SparkleShape, + val angle: Float, + val speed: Float, + val size: Float, + val spin: Float, + val delay: Float, + val twinkle: Float, + val color: Color, +) + +private fun sparkles(n: Int): List { + val r = Random(0x7A7A) + return List(n) { + Sparkle( + shape = when (r.nextInt(10)) { in 0..3 -> SparkleShape.HEART; in 4..8 -> SparkleShape.STAR; else -> SparkleShape.DOT }, + angle = r.nextFloat() * 2f * PI.toFloat(), + speed = 0.25f + r.nextFloat() * 0.75f, + size = 10f + r.nextFloat() * 26f, + spin = (r.nextFloat() - 0.5f) * 540f, + delay = 0.30f + r.nextFloat() * 0.25f, + twinkle = r.nextFloat() * 6f, + color = FairyMode.Palette.sparkles[r.nextInt(FairyMode.Palette.sparkles.size)], + ) + } +} + +/** A sparkle bursts out from the centre once its [Sparkle.delay] passes, drifting upward as it slows and fades. */ +private fun DrawScope.drawParticle(s: Sparkle, p: Float, center: Offset, radius: Float) { + val t = ((p - s.delay) / (1f - s.delay)).coerceIn(0f, 1f) + if (t <= 0f) return + val ease = 1f - (1f - t) * (1f - t) + val dist = ease * s.speed * radius * 0.55f + val pos = Offset(center.x + cos(s.angle) * dist, center.y + sin(s.angle) * dist - t * t * radius * 0.12f) + val alpha = ((1f - t) * (0.65f + 0.35f * sin(t * 20f + s.twinkle))).coerceIn(0f, 1f) + val sz = s.size * density / 2.5f * (0.6f + 0.6f * sin(t * PI.toFloat())) + rotate(s.spin * t, pos) { + when (s.shape) { + SparkleShape.STAR -> drawPath(starPath(pos, sz), s.color.copy(alpha = alpha)) + SparkleShape.HEART -> drawPath(heartPath(pos, sz), s.color.copy(alpha = alpha)) + SparkleShape.DOT -> drawCircle(s.color.copy(alpha = alpha), sz / 3, pos) + } + } +} + +/** The wand: a curve of small stars sweeping in from the bottom left to the centre, its head brightest. */ +private fun DrawScope.wandTrail(p: Float, veil: Float) { + val head = (p / 0.45f).coerceIn(0f, 1f) + if (head <= 0f || p > 0.6f) return + val fade = if (p > 0.45f) 1f - (p - 0.45f) / 0.15f else 1f + val start = Offset(size.width * 0.05f, size.height * 0.95f) + val end = Offset(size.width / 2, size.height / 2) + val ctrl = Offset(size.width * 0.15f, size.height * 0.35f) + fun at(u: Float) = Offset( + (1 - u) * (1 - u) * start.x + 2 * (1 - u) * u * ctrl.x + u * u * end.x, + (1 - u) * (1 - u) * start.y + 2 * (1 - u) * u * ctrl.y + u * u * end.y, + ) + val steps = 24 + for (i in 0..steps) { + val u = head * i / steps + val a = (i / steps.toFloat()) * fade * veil + val sz = (4f + 10f * i / steps) * density / 2.5f + drawPath(starPath(at(u), sz), Color(0xFFFFF1F8).copy(alpha = a)) + } + drawCircle(Color.White.copy(alpha = 0.9f * fade * veil), 6f * density, at(head)) +} + +private fun starPath(c: Offset, r: Float): Path = Path().apply { + for (i in 0 until 10) { + val rad = if (i % 2 == 0) r else r * 0.42f + val a = -PI / 2 + i * PI / 5 + val x = c.x + (cos(a) * rad).toFloat() + val y = c.y + (sin(a) * rad).toFloat() + if (i == 0) moveTo(x, y) else lineTo(x, y) + } + close() +} + +private fun heartPath(c: Offset, r: Float): Path = Path().apply { + moveTo(c.x, c.y + r * 0.9f) + cubicTo(c.x - r * 1.4f, c.y, c.x - r * 0.9f, c.y - r * 1.1f, c.x, c.y - r * 0.35f) + cubicTo(c.x + r * 0.9f, c.y - r * 1.1f, c.x + r * 1.4f, c.y, c.x, c.y + r * 0.9f) + close() +} diff --git a/app/src/main/java/com/pulseloop/ui/theme/Dither.kt b/app/src/main/java/com/pulseloop/ui/theme/Dither.kt index 43bd84df..cbaf2d3e 100644 --- a/app/src/main/java/com/pulseloop/ui/theme/Dither.kt +++ b/app/src/main/java/com/pulseloop/ui/theme/Dither.kt @@ -75,6 +75,8 @@ object Dither { } fun DrawScope.ditherBrush(color: Color, coverage: Float): Brush? { + // Fairy mode trades the bitmap dots for a soft wash of the same strength. + if (FairyMode.on) return if (coverage <= 0f) null else SolidColor(color.copy(alpha = coverage.coerceIn(0f, 1f))) val lit = Dither.steps(coverage) if (lit == 0) return null return with(Dither) { brush(color, lit, cellPx()) } @@ -118,6 +120,8 @@ private val OUTLINE_DIRECTIONS = listOf( * any dither density. */ private fun ContentDrawScope.drawContentOutlined() { + // A smooth wash needs no outline to stay readable. + if (FairyMode.on) { drawContent(); return } val w = OUTLINE_WIDTH.toPx() val tint = Paint().apply { colorFilter = ColorFilter.tint(OUTLINE_COLOR, BlendMode.SrcIn) } drawIntoCanvas { canvas -> @@ -139,6 +143,18 @@ fun DrawScope.drawDitherFade( top: Float, bottom: Float, ) { + if (FairyMode.on) { + clipPath(path) { + drawRect( + Brush.verticalGradient( + listOf(color.copy(alpha = fromCoverage.coerceIn(0f, 1f)), color.copy(alpha = toCoverage.coerceIn(0f, 1f))), + startY = top, endY = bottom, + ), + topLeft = Offset(0f, top), size = Size(size.width, bottom - top), + ) + } + return + } val from = Dither.steps(fromCoverage) val to = Dither.steps(toCoverage) val bands = maxOf(1, kotlin.math.abs(from - to) + 1) diff --git a/app/src/main/java/com/pulseloop/ui/theme/FairyMode.kt b/app/src/main/java/com/pulseloop/ui/theme/FairyMode.kt new file mode 100644 index 00000000..4ff8eb46 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/theme/FairyMode.kt @@ -0,0 +1,77 @@ +package com.pulseloop.ui.theme + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import java.text.Normalizer + +/** + * An Easter egg for Tatá: when the profile's name is Tatá, Tata or Thaissa, the app plays a fairy + * transformation once (FairyTransformOverlay) and from then on wears pink instead of mint, with + * smooth washes where the bitmap dither would be. Changing the name to anything else turns it off. + * + * Snapshot state, so every composable reading a [PulseColors] brand colour recomposes when it + * flips, and draw code reading it redraws. + */ +object FairyMode { + + private val NAMES = setOf("tata", "thaissa", "thaisa") + + /** Whether the pink theme is on. */ + var on by mutableStateOf(false) + private set + + /** The transformation still to play; the overlay clears it. */ + var celebrating by mutableStateOf(false) + private set + + private var prefs: android.content.SharedPreferences? = null + + fun init(context: Context) { + if (prefs != null) return + prefs = context.applicationContext.getSharedPreferences("fairy", Context.MODE_PRIVATE) + on = prefs?.getBoolean("on", false) == true + } + + /** Whether a profile name is one of hers: the first word, ignoring case and accents. */ + fun matches(name: String?): Boolean { + val first = name?.trim()?.split(Regex("\\s+"))?.firstOrNull()?.takeIf { it.isNotEmpty() } ?: return false + val plain = Normalizer.normalize(first, Normalizer.Form.NFD).replace(Regex("\\p{M}+"), "").lowercase() + return plain in NAMES + } + + /** Follow the profile's name: start the transformation the first time it matches, revert when it no longer does. */ + fun onProfileName(name: String?) { + val match = matches(name) + if (match && !on && !celebrating) celebrating = true + if (!match && on) setOn(false) + } + + /** Called by the overlay at the moment of transformation, under the sparkles. */ + fun transform() = setOn(true) + + fun celebrationDone() { + celebrating = false + if (!on) setOn(true) + } + + private fun setOn(value: Boolean) { + on = value + prefs?.edit()?.putBoolean("on", value)?.apply() + } + + /** Her palette: a soft rose pink with deep plum ink on it (7.7:1). */ + object Palette { + val accent = Color(0xFFFF8FC7) + val accentSoft = Color(0x2EFF8FC7) + val onAccent = Color(0xFF3D0A26) + val rem = Color(0xFFFFB3DA) + /** Sparkle colours: pinks, a little gold and white. */ + val sparkles = listOf( + Color(0xFFFF8FC7), Color(0xFFFFB3DA), Color(0xFFFF5FA8), Color(0xFFFFD6EC), + Color(0xFFFFE08A), Color(0xFFFFFFFF), Color(0xFFE7B6FF), + ) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt b/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt index 59532037..ae7a17f9 100644 --- a/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt +++ b/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt @@ -11,6 +11,8 @@ import androidx.compose.ui.graphics.Color * ZonePalette alias. */ object PulseColors { + /** GMind mint. The brand colours below are getters so [FairyMode] can turn them pink. */ + private val MINT = Color(0xFF43F3B7) val background = Color(0xFF121214) val secondaryBackground = Color(0xFF161619) val card = Color(0xFF1C1B1F) @@ -21,11 +23,11 @@ object PulseColors { /** Tertiary text. #8E8D94 so it still reads at 4.5:1 on [card] and [cardSoft] (#7C7B82 was 4.1 / 3.7). */ val textMuted = Color(0xFF8E8D94) /** GMind mint: the primary action, the selected state, the screen frame. */ - val accent = Color(0xFF43F3B7) - val accentSoft = Color(0x2E43F3B7) // accent @ 18% + val accent: Color get() = if (FairyMode.on) FairyMode.Palette.accent else MINT + val accentSoft: Color get() = if (FairyMode.on) FairyMode.Palette.accentSoft else Color(0x2E43F3B7) // accent @ 18% /** Text and icons on a mint fill (GMind ON_MINT, 9:1 on mint). Never white on mint. */ - val onAccent = Color(0xFF033423) - val success = Color(0xFF43F3B7) + val onAccent: Color get() = if (FairyMode.on) FairyMode.Palette.onAccent else Color(0xFF033423) + val success: Color get() = accent val warning = Color(0xFFFFC46B) val danger = Color(0xFFFF7A70) // GMind coral (dark) val info = Color(0xFF5AD8F0) @@ -45,7 +47,7 @@ object PulseColors { val bloodSugar = Color(0xFFFFC46B) val fatigue = Color(0xFFC98CFF) val drinks = Color(0xFFE38FB5) // wine rose - val readiness = Color(0xFF43F3B7) // the headline score wears the brand mint + val readiness: Color get() = accent // the headline score wears the brand colour // Vitals reference-zone colors (AppTheme.swift zone*) — aliased by // ZonePalette (fine iOS-parity palette) and [MetricColors] (coarse semantic palette) @@ -61,12 +63,12 @@ object PulseColors { // Sleep stage colors (DesignSystem/Charts.swift SleepStageColors) val stageDeep = Color(0xFF4B3BD6) val stageLight = Color(0xFF9A8CFF) - val stageRem = Color(0xFF43F3B7) + val stageRem: Color get() = if (FairyMode.on) FairyMode.Palette.rem else MINT val stageAwake = Color(0xFFFFC46B) val borderSubtle = Color(0xFF2C2B30) // GMind hairline (LINE, dark) val borderStrong = Color(0xFF3D3C42) /** The GMind frame: a 4dp mint border round every screen. */ - val frame = accent + val frame: Color get() = accent } diff --git a/app/src/main/java/com/pulseloop/ui/theme/Theme.kt b/app/src/main/java/com/pulseloop/ui/theme/Theme.kt index dc61ef22..7a844b70 100644 --- a/app/src/main/java/com/pulseloop/ui/theme/Theme.kt +++ b/app/src/main/java/com/pulseloop/ui/theme/Theme.kt @@ -23,7 +23,8 @@ val UbuntuMono = FontFamily( Font(R.font.ubuntu_mono_bold_italic, FontWeight.Bold, FontStyle.Italic), ) -private val DarkColorScheme = darkColorScheme( +/** Built per composition, not once: the brand colours follow [FairyMode]. */ +private fun darkScheme() = darkColorScheme( primary = PulseColors.accent, onPrimary = PulseColors.onAccent, primaryContainer = PulseColors.accentSoft, @@ -71,7 +72,7 @@ private val PulseTypography = Typography().withFamily(UbuntuMono) @Composable fun PulseLoopTheme(content: @Composable () -> Unit) { MaterialTheme( - colorScheme = DarkColorScheme, + colorScheme = darkScheme(), typography = PulseTypography, // GMind radii: 4dp for small controls, 8dp for cards and dialogs, 16dp for sheets. shapes = Shapes( diff --git a/app/src/test/java/com/pulseloop/ui/theme/FairyModeTest.kt b/app/src/test/java/com/pulseloop/ui/theme/FairyModeTest.kt new file mode 100644 index 00000000..94d4a276 --- /dev/null +++ b/app/src/test/java/com/pulseloop/ui/theme/FairyModeTest.kt @@ -0,0 +1,21 @@ +package com.pulseloop.ui.theme + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class FairyModeTest { + @Test + fun `her names match, whatever the case, accents or surname`() { + listOf("Tatá", "Tata", "tata", "TATÁ", "Thaissa", "thaíssa", "Thaissa Silva", " Tatá ").forEach { + assertTrue(it, FairyMode.matches(it)) + } + } + + @Test + fun `other names don't`() { + listOf(null, "", "Gabriel", "Tatiana", "Ana Tata", "Thais").forEach { + assertFalse(it.toString(), FairyMode.matches(it)) + } + } +} From b249cd62063b5c97e4c4de4ef3299ca2d23de861 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 10:25:58 +0000 Subject: [PATCH 2/3] Portuguese: translation layer, language picker, UI strings wrapped (catalog to follow) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also: the fairy overlay now reads "Tatá, te amo!", and a JVM signature clash in FairyMode that broke the build is fixed. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 21 + .../main/java/com/pulseloop/MainActivity.kt | 7 +- .../com/pulseloop/PulseLoopApplication.kt | 1 + .../coach/context/CoachPromptBuilder.kt | 5 +- .../coach/summaries/CoachSummaryGenerator.kt | 2 +- .../java/com/pulseloop/ui/PulseLoopApp.kt | 19 +- .../pulseloop/ui/components/ActivityMeta.kt | 40 +- .../pulseloop/ui/components/ActivityRings.kt | 4 +- .../com/pulseloop/ui/components/AppChrome.kt | 20 +- .../com/pulseloop/ui/components/Charts.kt | 6 +- .../pulseloop/ui/components/DeviceHeroCard.kt | 4 +- .../ui/components/DeviceHeroStatus.kt | 26 +- .../pulseloop/ui/components/FairyTransform.kt | 13 +- .../com/pulseloop/ui/components/TodayTiles.kt | 8 +- .../pulseloop/ui/dashboard/DashboardCard.kt | 24 +- .../pulseloop/ui/dashboard/DashboardEdit.kt | 8 +- .../main/java/com/pulseloop/ui/i18n/L10n.kt | 97 +++ .../com/pulseloop/ui/onboarding/Editors.kt | 64 +- .../pulseloop/ui/screens/AccuracyCheckUi.kt | 102 +-- .../pulseloop/ui/screens/AccuracyReportUi.kt | 46 +- .../pulseloop/ui/screens/ActivityScreen.kt | 86 +-- .../ui/screens/BarcodeScannerScreen.kt | 16 +- .../java/com/pulseloop/ui/screens/BodyUi.kt | 14 +- .../pulseloop/ui/screens/CoachModelPicker.kt | 12 +- .../com/pulseloop/ui/screens/CoachScreen.kt | 48 +- .../pulseloop/ui/screens/CoachUsageSheet.kt | 18 +- .../java/com/pulseloop/ui/screens/CycleUi.kt | 26 +- .../com/pulseloop/ui/screens/DebugScreen.kt | 52 +- .../java/com/pulseloop/ui/screens/DrinksUi.kt | 164 ++--- .../java/com/pulseloop/ui/screens/FoodUi.kt | 12 +- .../com/pulseloop/ui/screens/GuidanceUi.kt | 10 +- .../ui/screens/HealthConnectSourceUi.kt | 52 +- .../com/pulseloop/ui/screens/JournalUi.kt | 20 +- .../ui/screens/LanguageSettingsScreen.kt | 59 ++ .../ui/screens/LogPastActivityScreen.kt | 28 +- .../pulseloop/ui/screens/MealAnalysisSheet.kt | 60 +- .../java/com/pulseloop/ui/screens/MedsUi.kt | 42 +- .../com/pulseloop/ui/screens/MyHealthUi.kt | 124 ++-- .../pulseloop/ui/screens/NutritionScreen.kt | 56 +- .../pulseloop/ui/screens/OnboardingScreen.kt | 74 +- .../com/pulseloop/ui/screens/PairingScreen.kt | 48 +- .../com/pulseloop/ui/screens/ReadinessUi.kt | 62 +- .../com/pulseloop/ui/screens/RecordScreen.kt | 28 +- .../java/com/pulseloop/ui/screens/Screens.kt | 160 ++-- .../pulseloop/ui/screens/SettingsScreen.kt | 59 +- .../ui/screens/SettingsSubScreens.kt | 684 +++++++++--------- .../com/pulseloop/ui/screens/SleepScreen.kt | 92 +-- .../com/pulseloop/ui/screens/TodayGlance.kt | 30 +- .../com/pulseloop/ui/screens/TodayScreen.kt | 36 +- .../com/pulseloop/ui/screens/WhatChangedUi.kt | 14 +- .../ui/screens/WorkoutSummaryScreen.kt | 54 +- .../java/com/pulseloop/ui/theme/FairyMode.kt | 8 +- .../com/pulseloop/ui/viewmodels/ViewModels.kt | 10 +- .../pulseloop/ui/viewmodels/VitalCardState.kt | 24 +- app/src/main/res/values-pt/strings.xml | 13 + .../ui/i18n/PortugueseCatalogTest.kt | 49 ++ 56 files changed, 1604 insertions(+), 1257 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/ui/i18n/L10n.kt create mode 100644 app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt create mode 100644 app/src/main/res/values-pt/strings.xml create mode 100644 app/src/test/java/com/pulseloop/ui/i18n/PortugueseCatalogTest.kt diff --git a/AGENTS.md b/AGENTS.md index c2bcc582..ae2164d4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1033,3 +1033,24 @@ and each one fails silently if broken: writing next month would then echo. It is exclusive with a paired ring: a `DeviceIdentified` turns it off. + +## Every UI string goes through `tr()`, and the English text is the key + +**The app speaks English and Brazilian Portuguese (Settings → Language, `ui/i18n/L10n.kt`).** There +are no string resources for UI text: a composable writes `Text(tr("Save"))`, and `tr` looks the +English up in `assets/i18n/pt-BR.json`, falling back to the English when there is no entry. So: + +- **New UI text: wrap it in `tr()` and add the pt-BR entry to the catalog in the same change.** An + unwrapped string, or a wrapped one with no entry, silently stays English for Portuguese users. + Rewording an English string orphans its translation the same way; update the key too. +- **Translate where text is shown, never where a value is defined.** A literal that is also + *compared* (`zone.label == "High"`, a `when` over labels) must stay English; wrap the display site + instead (`Text(tr(zone.label))`). `MetricThresholds` and `HeartRateZones` labels work this way. +- **Not inside an enum constructor or an object-level `val`:** those evaluate once, so a language + change wouldn't show until the process restarts. Use a getter (`val label get() = tr(en)`). +- **Never date patterns or format keys.** `tr("EEE d MMM")` would let a translation break parsing. + Dates already localise through the default `Locale`, which `L10n` sets. +- A string built by a template (`"Day $n"`) can't be a key. Split it into a translated part and the + value, or leave it English. Many still are; templates and service-layer text (insights, + notifications) are the known gaps. +- The coach answers in the app's language through `L10n.coachInstruction()`, appended to its prompts. diff --git a/app/src/main/java/com/pulseloop/MainActivity.kt b/app/src/main/java/com/pulseloop/MainActivity.kt index 07df5c39..a8739a39 100644 --- a/app/src/main/java/com/pulseloop/MainActivity.kt +++ b/app/src/main/java/com/pulseloop/MainActivity.kt @@ -44,6 +44,11 @@ import kotlinx.coroutines.launch */ class MainActivity : ComponentActivity() { + // Settings → Language: Android resources and system UI follow the app's language. + override fun attachBaseContext(newBase: android.content.Context) { + super.attachBaseContext(com.pulseloop.ui.i18n.L10n.wrap(newBase)) + } + // Request multiple permissions at once on Android 12+ private val blePermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() @@ -106,7 +111,7 @@ class MainActivity : ComponentActivity() { ) { PulseLoopApp() } - com.pulseloop.ui.components.FairyTransformOverlay(profile?.name) + com.pulseloop.ui.components.FairyTransformOverlay() } } diff --git a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt index c9e05e45..141321a6 100644 --- a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt +++ b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt @@ -28,6 +28,7 @@ class PulseLoopApplication : Application() { CrashLogger.install(this) com.pulseloop.service.DrinkPrefs.init(this) com.pulseloop.ui.theme.FairyMode.init(this) + com.pulseloop.ui.i18n.L10n.init(this) com.pulseloop.health.source.HealthConnectSource.isEnabled(this) // warms [HealthConnectSource.enabledNow] // Application-scoped so capture runs whether or not the Debug screen is open. DiagnosticsSubscriber(PulseLoopDatabase.getInstance(this)).start(appScope) diff --git a/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt b/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt index 7e1e0300..6f194b5b 100644 --- a/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt +++ b/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt @@ -5,7 +5,10 @@ package com.pulseloop.coach.context * System + developer prompts for the coach. */ object CoachPromptBuilder { - val systemPrompt = """ + /** The prompt, plus "reply in Portuguese" while the app is in Portuguese (Settings → Language). */ + val systemPrompt: String get() = baseSystemPrompt + com.pulseloop.ui.i18n.L10n.coachInstruction() + + private val baseSystemPrompt = """ You are PulseLoop Coach, a transparent, evidence-grounded health and fitness coach for a smart-ring app. You help users understand their own ring data: steps, distance, calories, active minutes, heart rate, SpO2, sleep duration, and sleep stages. You can also set goals, log corrections, take measurements, save notes, run simple analyses, and generate charts. diff --git a/app/src/main/java/com/pulseloop/coach/summaries/CoachSummaryGenerator.kt b/app/src/main/java/com/pulseloop/coach/summaries/CoachSummaryGenerator.kt index 908dff6e..1bef1787 100644 --- a/app/src/main/java/com/pulseloop/coach/summaries/CoachSummaryGenerator.kt +++ b/app/src/main/java/com/pulseloop/coach/summaries/CoachSummaryGenerator.kt @@ -32,7 +32,7 @@ object CoachSummaryGenerator { if (!flags.coachEnabled || apiKey.isBlank()) return@withContext fallback try { val input = JsonArray(listOf( - message("system", CoachSummaryPromptBuilder.systemPrompt(kind)), + message("system", CoachSummaryPromptBuilder.systemPrompt(kind) + com.pulseloop.ui.i18n.L10n.coachInstruction()), message("developer", CoachSummaryPromptBuilder.developerMessage(contextJSON, angle, recentTexts)), )) val textFormat = JsonObject(mapOf( diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index 464e2873..2b0c9dd7 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui +import com.pulseloop.ui.i18n.tr + import android.content.res.Configuration import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons @@ -318,11 +320,11 @@ fun PulseLoopApp() { } val tabs = listOf( - Tab("today", "Today", Icons.Filled.Adjust, Icons.Outlined.Adjust), - Tab("vitals", "Vitals", Icons.Filled.Favorite, Icons.Outlined.FavoriteBorder), - Tab("activity", "Activity", Icons.Filled.MonitorHeart, Icons.Outlined.MonitorHeart), - Tab("sleep", "Sleep", Icons.Filled.Bedtime, Icons.Outlined.Bedtime), - Tab("coach", "Coach", Icons.Filled.AutoAwesome, Icons.Outlined.AutoAwesome), + Tab("today", tr("Today"), Icons.Filled.Adjust, Icons.Outlined.Adjust), + Tab("vitals", tr("Vitals"), Icons.Filled.Favorite, Icons.Outlined.FavoriteBorder), + Tab("activity", tr("Activity"), Icons.Filled.MonitorHeart, Icons.Outlined.MonitorHeart), + Tab("sleep", tr("Sleep"), Icons.Filled.Bedtime, Icons.Outlined.Bedtime), + Tab("coach", tr("Coach"), Icons.Filled.AutoAwesome, Icons.Outlined.AutoAwesome), ) // ── Self-update: release-only. Checked on every return to foreground (ON_START also @@ -445,7 +447,7 @@ fun PulseLoopApp() { batteryPercent = ble.batteryPercent ?: storedDevice?.batteryPercent, onOpenSettings = { navController.navigate("settings") }, idle = ble.idleSince != null, - sourceLabel = hcSource?.let { com.pulseloop.health.source.HealthConnectSource.label(context, it) + " · Health Connect" }, + sourceLabel = hcSource?.let { com.pulseloop.health.source.HealthConnectSource.label(context, it) + tr(" · Health Connect") }, ) // Thin sync-progress accent under the greeting while history streams in. val syncPct = coordinator.syncProgress.collectAsState().value @@ -668,6 +670,9 @@ fun PulseLoopApp() { onCoach = discussMeal, ) } + paddedComposable("settings/language") { + LanguageSettingsScreen(onBack = { navController.popBackStack() }) + } paddedComposable("settings/about") { AboutSettingsScreen( onOpenDebug = { navController.navigate("debug") }, @@ -759,7 +764,7 @@ fun PulseLoopApp() { } } RecordScreen( - activityName = workoutState.activeSession?.type ?: "Workout", + activityName = workoutState.activeSession?.type ?: tr("Workout"), elapsedSeconds = workoutState.elapsedSeconds, distanceMeters = workoutState.distanceMeters, heartRate = workoutState.latestHeartRate, diff --git a/app/src/main/java/com/pulseloop/ui/components/ActivityMeta.kt b/app/src/main/java/com/pulseloop/ui/components/ActivityMeta.kt index 22c27623..77f70bcf 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ActivityMeta.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ActivityMeta.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr + import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.DirectionsBike import androidx.compose.material.icons.automirrored.filled.DirectionsRun @@ -23,29 +25,29 @@ object ActivityMeta { val ORDER = listOf("walk", "run", "cycle", "gym", "squash", "sport", "yoga", "dance", "hike", "other") fun label(type: String): String = when (type) { - "walk" -> "Walking" - "run" -> "Running" - "cycle" -> "Cycling" - "gym" -> "Gym" - "squash" -> "Squash" - "sport" -> "Sport" - "yoga" -> "Yoga" - "dance" -> "Dance" - "hike" -> "Hiking" + "walk" -> tr("Walking") + "run" -> tr("Running") + "cycle" -> tr("Cycling") + "gym" -> tr("Gym") + "squash" -> tr("Squash") + "sport" -> tr("Sport") + "yoga" -> tr("Yoga") + "dance" -> tr("Dance") + "hike" -> tr("Hiking") else -> type.replaceFirstChar { it.uppercase() } } fun helper(type: String): String = when (type) { - "walk" -> "Casual or brisk walking" - "run" -> "Outdoor or treadmill runs" - "cycle" -> "Road, trail, or stationary" - "gym" -> "Strength or circuit training" - "squash" -> "Court sessions" - "sport" -> "Team or racket sports" - "yoga" -> "Flow, stretch, or breathwork" - "dance" -> "Studio, cardio, or freestyle" - "hike" -> "Trails and elevation" - else -> "Anything else" + "walk" -> tr("Casual or brisk walking") + "run" -> tr("Outdoor or treadmill runs") + "cycle" -> tr("Road, trail, or stationary") + "gym" -> tr("Strength or circuit training") + "squash" -> tr("Court sessions") + "sport" -> tr("Team or racket sports") + "yoga" -> tr("Flow, stretch, or breathwork") + "dance" -> tr("Studio, cardio, or freestyle") + "hike" -> tr("Trails and elevation") + else -> tr("Anything else") } fun icon(type: String): ImageVector = when (type) { diff --git a/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt b/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt index d9257be2..db6a909a 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.trackBrush import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.size @@ -54,7 +56,7 @@ fun ActivityRings( labels: List = emptyList(), ) { // Drawn arcs say nothing to TalkBack; speak each ring's share of its goal instead. - val description = "Goal progress: " + rings.mapIndexed { i, ring -> + val description = tr("Goal progress: ") + rings.mapIndexed { i, ring -> val name = labels.getOrNull(i) ?: "ring ${i + 1}" if (ring.value == null) "$name unavailable" else "$name ${(ring.progress * 100).toInt()}%" }.joinToString(", ") diff --git a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt index 93417c26..7541b836 100644 --- a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt +++ b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr + import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable @@ -78,13 +80,13 @@ fun AppHeader( idle = idle, sourceLabel = sourceLabel, modifier = Modifier.clickable( - onClickLabel = "Open ring settings", + onClickLabel = tr("Open ring settings"), role = Role.Button, onClick = onOpenSettings, ), ) IconButton(onClick = onOpenSettings) { - Icon(Icons.Outlined.Settings, "Settings", tint = PulseColors.textSecondary) + Icon(Icons.Outlined.Settings, tr("Settings"), tint = PulseColors.textSecondary) } } } @@ -115,11 +117,11 @@ fun ConnectionStatusPill( val label = sourceLabel ?: when (state) { RingConnectionState.CONNECTED -> if (batteryPercent != null && batteryPercent > 0) "Connected · $batteryPercent%" else "Connected" - RingConnectionState.CONNECTING, RingConnectionState.RECONNECTING -> "Connecting…" - RingConnectionState.FAILED -> "Sync failed" + RingConnectionState.CONNECTING, RingConnectionState.RECONNECTING -> tr("Connecting…") + RingConnectionState.FAILED -> tr("Sync failed") else -> if (idleNow) { if (batteryPercent != null && batteryPercent > 0) "Idle · $batteryPercent%" else "Idle" - } else "Disconnected" + } else tr("Disconnected") } // Only run the transition while pulsing: an infinite 1f→1f animation still ticks every frame. val pulse = if (isPulsing) { @@ -159,10 +161,10 @@ fun ConnectionStatusPill( /** Time-of-day greeting, mirroring RootViews.swift `greetingForHour()`. */ fun greetingForHour(): String = when (Calendar.getInstance().get(Calendar.HOUR_OF_DAY)) { - in 5..11 -> "Good morning" - in 12..16 -> "Good afternoon" - in 17..21 -> "Good evening" - else -> "Good night" + in 5..11 -> tr("Good morning") + in 12..16 -> tr("Good afternoon") + in 17..21 -> tr("Good evening") + else -> tr("Good night") } /** diff --git a/app/src/main/java/com/pulseloop/ui/components/Charts.kt b/app/src/main/java/com/pulseloop/ui/components/Charts.kt index f2d11167..bfe16109 100644 --- a/app/src/main/java/com/pulseloop/ui/components/Charts.kt +++ b/app/src/main/java/com/pulseloop/ui/components/Charts.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.PulseColors import com.pulseloop.ui.theme.ditherBrush import com.pulseloop.ui.theme.drawDitherFade @@ -309,7 +311,7 @@ fun TrendChart( // TalkBack can't scrub; give it the shape of the data in one sentence instead. val summary = remember(points, secondary, title) { fun v(i: Int) = valueFormatter(points[i]) + (secondary.getOrNull(i)?.let { "/" + valueFormatter(it) } ?: "") - "${title ?: "Chart"}: latest ${v(points.lastIndex)}, " + + "${title ?: tr("Chart")}: latest ${v(points.lastIndex)}, " + "range ${valueFormatter(points.min())}–${valueFormatter(points.max())}, ${points.size} readings" } @@ -586,7 +588,7 @@ fun TrendChart( IconButton(onClick = { zoom = 1f; windowStart = 0f }) { Icon( Icons.Filled.Refresh, - contentDescription = "Reset zoom", + contentDescription = tr("Reset zoom"), tint = MaterialTheme.colorScheme.onSurfaceVariant, ) } diff --git a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt index 2bfbdecc..c46b4930 100644 --- a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt +++ b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -80,7 +82,7 @@ fun DeviceHeroCard( Row( Modifier .fillMaxWidth() - .clickable(onClickLabel = "Open ring settings", role = Role.Button, onClick = onOpenWearable), + .clickable(onClickLabel = tr("Open ring settings"), role = Role.Button, onClick = onOpenWearable), horizontalArrangement = Arrangement.spacedBy(16.dp), ) { RingArtView( diff --git a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt index b3526002..e900ad92 100644 --- a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt +++ b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr + import androidx.compose.ui.graphics.Color import com.pulseloop.ring.RingConnectionState import com.pulseloop.ui.theme.PulseColors @@ -28,10 +30,10 @@ data class DeviceHeroStatus( val actionTitle: String get() = when (action) { - Action.DISCONNECT -> "Disconnect" - Action.CONNECT -> "Connect" - Action.SET_UP -> "Set up a ring" - Action.PENDING -> "Connecting…" + Action.DISCONNECT -> tr("Disconnect") + Action.CONNECT -> tr("Connect") + Action.SET_UP -> tr("Set up a ring") + Action.PENDING -> tr("Connecting…") } /** The action button is inert while a connection attempt is in flight, so a tap can't @@ -54,28 +56,28 @@ data class DeviceHeroStatus( /** The ring hung up between syncs on its own (`IdleLinkPolicy`), not a fault. */ idle: Boolean = false, ): DeviceHeroStatus { - val title = connectedName ?: knownName ?: "No ring connected" + val title = connectedName ?: knownName ?: tr("No ring connected") val statusLine: String val statusTint: Color when (state) { RingConnectionState.CONNECTED -> { - statusLine = "Connected"; statusTint = PulseColors.success + statusLine = tr("Connected"); statusTint = PulseColors.success } RingConnectionState.CONNECTING, RingConnectionState.RECONNECTING -> { - statusLine = "Connecting…"; statusTint = PulseColors.warning + statusLine = tr("Connecting…"); statusTint = PulseColors.warning } RingConnectionState.SCANNING -> { - statusLine = "Searching…"; statusTint = PulseColors.warning + statusLine = tr("Searching…"); statusTint = PulseColors.warning } RingConnectionState.FAILED -> { - statusLine = "Connection failed"; statusTint = PulseColors.danger + statusLine = tr("Connection failed"); statusTint = PulseColors.danger } RingConnectionState.IDLE, RingConnectionState.DISCONNECTED -> { statusLine = when { - knownName == null -> "No ring paired" - idle && state == RingConnectionState.DISCONNECTED -> "Idle between syncs" - else -> "Disconnected" + knownName == null -> tr("No ring paired") + idle && state == RingConnectionState.DISCONNECTED -> tr("Idle between syncs") + else -> tr("Disconnected") } statusTint = PulseColors.textSecondary } diff --git a/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt b/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt index e797c775..1abc4e08 100644 --- a/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt +++ b/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr + import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.tween @@ -37,7 +39,7 @@ import kotlin.random.Random * swallows touches while it does. */ @Composable -fun FairyTransformOverlay(name: String?) { +fun FairyTransformOverlay() { if (!FairyMode.celebrating) return val reduceMotion = rememberReduceMotion() val progress = remember { Animatable(0f) } @@ -89,13 +91,10 @@ fun FairyTransformOverlay(name: String?) { horizontalAlignment = Alignment.CenterHorizontally, ) { Text( - "Oi, ${name?.trim()?.split(Regex("\\s+"))?.firstOrNull() ?: "Tatá"} ✨", - fontSize = 34.sp, fontWeight = FontWeight.Bold, color = Color.White, textAlign = TextAlign.Center, - ) - Text( - "Feito com amor pra você 💗", - fontSize = 16.sp, color = Color(0xFFFFE3F1), textAlign = TextAlign.Center, + tr("Tatá, te amo!"), + fontSize = 36.sp, fontWeight = FontWeight.Bold, color = Color.White, textAlign = TextAlign.Center, ) + Text("💗", fontSize = 28.sp, textAlign = TextAlign.Center) } } } diff --git a/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt b/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt index 11881ee8..2cb277d0 100644 --- a/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt +++ b/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -155,7 +157,7 @@ fun ActivityTile( modifier: Modifier = Modifier, onTap: () -> Unit, ) { - TodayTile(label = "Activity", color = PulseColors.steps, modifier = modifier, onTap = onTap) { + TodayTile(label = tr("Activity"), color = PulseColors.steps, modifier = modifier, onTap = onTap) { Row( Modifier.weight(1f).fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, @@ -340,7 +342,7 @@ fun SleepTile( modifier: Modifier = Modifier, onTap: () -> Unit, ) { - TodayTile(label = "Sleep", color = PulseColors.sleep, modifier = modifier, onTap = onTap) { + TodayTile(label = tr("Sleep"), color = PulseColors.sleep, modifier = modifier, onTap = onTap) { if (durationText != null) { Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( @@ -383,7 +385,7 @@ fun SleepTile( ) Spacer(Modifier.height(6.dp)) Text( - "No sleep recorded", + tr("No sleep recorded"), fontSize = 13.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, diff --git a/app/src/main/java/com/pulseloop/ui/dashboard/DashboardCard.kt b/app/src/main/java/com/pulseloop/ui/dashboard/DashboardCard.kt index 4ea7dfa5..05b2a488 100644 --- a/app/src/main/java/com/pulseloop/ui/dashboard/DashboardCard.kt +++ b/app/src/main/java/com/pulseloop/ui/dashboard/DashboardCard.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.dashboard +import com.pulseloop.ui.i18n.tr + /** * Which dashboard the visibility/order preferences apply to. Today and Vitals are fully * independent scopes (a card hidden on Today can still show on Vitals). Ported from iOS @@ -31,18 +33,18 @@ enum class DashboardCard(val key: String) { /** Human label for the Hidden tray / edit-mode affordances. */ val displayName: String get() = when (this) { - ACTIVITY -> "Activity" - SLEEP -> "Sleep" - NUTRITION -> "Nutrition" - DRINKS -> "Drinks" - HEART_RATE -> "Heart Rate" - SPO2 -> "SpO₂" + ACTIVITY -> tr("Activity") + SLEEP -> tr("Sleep") + NUTRITION -> tr("Nutrition") + DRINKS -> tr("Drinks") + HEART_RATE -> tr("Heart Rate") + SPO2 -> tr("SpO₂") HRV -> "HRV" - TEMPERATURE -> "Temperature" - STRESS -> "Stress" - FATIGUE -> "Fatigue" - GLUCOSE -> "Glucose" - BLOOD_PRESSURE -> "Blood Pressure" + TEMPERATURE -> tr("Temperature") + STRESS -> tr("Stress") + FATIGUE -> tr("Fatigue") + GLUCOSE -> tr("Glucose") + BLOOD_PRESSURE -> tr("Blood Pressure") } companion object { diff --git a/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt b/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt index 2b38c53c..8a37788b 100644 --- a/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt +++ b/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.dashboard +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement @@ -221,7 +223,7 @@ fun HiddenMetricsTray(hidden: List, onRestore: (DashboardCard) -> @Composable fun CustomizeCardsButton(onClick: () -> Unit) { TextButton(onClick = onClick) { - Text("Customize", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Customize"), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } } @@ -235,12 +237,12 @@ fun ReorderDoneBar(onDone: () -> Unit) { ) { Row(Modifier.padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) { Text( - "Reorder or hide cards", + tr("Reorder or hide cards"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 8.dp), ) - TextButton(onClick = onDone) { Text("Done") } + TextButton(onClick = onDone) { Text(tr("Done")) } } } } diff --git a/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt b/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt new file mode 100644 index 00000000..909e7772 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt @@ -0,0 +1,97 @@ +package com.pulseloop.ui.i18n + +import android.content.Context +import android.content.res.Configuration +import android.content.res.Resources +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import org.json.JSONObject +import java.util.Locale + +/** The languages PulseLoop speaks. [SYSTEM] follows the phone. */ +enum class AppLanguage(val key: String, val label: String) { + SYSTEM("system", "System default"), + ENGLISH("en", "English"), + PORTUGUESE("pt-BR", "Português (Brasil)"), +} + +/** + * The app's language (Settings → Language). The UI is written in English, and every displayed + * literal goes through [tr], which looks the English text up in the language's catalog + * (`assets/i18n/pt-BR.json`) and falls back to the English when a string has no entry yet. The + * English text *is* the key, so a reworded string simply shows in English until it is translated + * again. + * + * Snapshot state: [tr] reads [language], so a composition re-reads every string when it changes. + * The default [Locale] follows the language too, so dates and numbers format to match. + */ +object L10n { + + var language by mutableStateOf(AppLanguage.SYSTEM) + private set + + @Volatile private var catalog: Map = emptyMap() + private var appContext: Context? = null + private var systemLocale: Locale = Locale.getDefault() + + fun init(context: Context) { + if (appContext != null) return + appContext = context.applicationContext + systemLocale = Resources.getSystem().configuration.locales.get(0) ?: Locale.getDefault() + val saved = prefs(context).getString("language", AppLanguage.SYSTEM.key) + language = AppLanguage.entries.firstOrNull { it.key == saved } ?: AppLanguage.SYSTEM + apply() + } + + fun set(context: Context, value: AppLanguage) { + prefs(context).edit().putString("language", value.key).apply() + language = value + apply() + } + + /** Whether the UI is currently in Portuguese (chosen, or the phone's language under [AppLanguage.SYSTEM]). */ + val isPortuguese: Boolean get() = locale().language == "pt" + + fun locale(): Locale = when (language) { + AppLanguage.ENGLISH -> Locale.ENGLISH + AppLanguage.PORTUGUESE -> Locale("pt", "BR") + AppLanguage.SYSTEM -> systemLocale + } + + private fun apply() { + val locale = locale() + Locale.setDefault(locale) + catalog = if (locale.language == "pt") load("i18n/pt-BR.json") else emptyMap() + } + + private fun load(asset: String): Map = runCatching { + val json = appContext!!.assets.open(asset).bufferedReader().use { it.readText() } + val obj = JSONObject(json) + buildMap { obj.keys().forEach { k -> put(k, obj.getString(k)) } } + }.getOrDefault(emptyMap()) + + fun translate(en: String): String { + @Suppress("UNUSED_VARIABLE") val l = language // read, so composition follows a change + return catalog[en] ?: en + } + + /** Appended to the coach's prompts: the coach answers in the app's language. */ + fun coachInstruction(): String = + if (isPortuguese) "\n\nThe user's app is in Brazilian Portuguese. Always reply in Brazilian Portuguese (pt-BR), " + + "naturally and warmly, keeping metric names the app shows (HRV, SpO2) as they are." + else "" + + /** The Activity's context in the chosen language, so Android resources and system UI follow it. */ + fun wrap(base: Context): Context { + init(base) + val config = Configuration(base.resources.configuration) + config.setLocale(locale()) + return base.createConfigurationContext(config) + } + + private fun prefs(c: Context) = c.applicationContext.getSharedPreferences("language", Context.MODE_PRIVATE) +} + +/** The current language's text for an English UI string. */ +fun tr(en: String): String = L10n.translate(en) diff --git a/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt b/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt index 34feaf0d..8471cbaf 100644 --- a/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt +++ b/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.onboarding +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -70,17 +72,17 @@ fun ProfileEditor( Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(16.dp)) { if (showUnits) { - SectionHeaderCaps("Units") + SectionHeaderCaps(tr("Units")) FormCard { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Text( - "Measurement units", + tr("Measurement units"), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, ) SegmentedRow( - options = listOf("Metric", "Imperial"), + options = listOf(tr("Metric"), tr("Imperial")), selectedIndex = if (draft.units == UnitSystem.METRIC) 0 else 1, onSelect = { index -> onDraftChange(draft.copy(units = if (index == 0) UnitSystem.METRIC else UnitSystem.IMPERIAL)) @@ -90,7 +92,7 @@ fun ProfileEditor( } } - SectionHeaderCaps("Identity") + SectionHeaderCaps(tr("Identity")) FormCard { Column { Row( @@ -99,14 +101,14 @@ fun ProfileEditor( horizontalArrangement = Arrangement.spacedBy(12.dp), ) { Text( - "Name", + tr("Name"), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, ) Box(Modifier.weight(1f), contentAlignment = Alignment.CenterEnd) { if (draft.name.isEmpty()) { - Text("Optional", fontSize = 14.sp, color = PulseColors.textMuted) + Text(tr("Optional"), fontSize = 14.sp, color = PulseColors.textMuted) } BasicTextField( value = draft.name, @@ -119,7 +121,7 @@ fun ProfileEditor( ), cursorBrush = SolidColor(PulseColors.accent), // The "Name" label is a sibling Text, so the field names itself. - modifier = Modifier.fillMaxWidth().semantics { contentDescription = "Name" }, + modifier = Modifier.fillMaxWidth().semantics { contentDescription = tr("Name") }, ) } } @@ -131,13 +133,13 @@ fun ProfileEditor( verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text( - "Sex", + tr("Sex"), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, ) SegmentedRow( - options = listOf("Not set", "Female", "Male", "Other"), + options = listOf(tr("Not set"), tr("Female"), tr("Male"), tr("Other")), selectedIndex = when (draft.sex?.lowercase()) { "female" -> 1 "male" -> 2 @@ -159,25 +161,25 @@ fun ProfileEditor( } } - SectionHeaderCaps("Body metrics", action = { - Text("Optional", fontSize = 12.sp, color = PulseColors.textMuted) + SectionHeaderCaps(tr("Body metrics"), action = { + Text(tr("Optional"), fontSize = 12.sp, color = PulseColors.textMuted) }) FormCard { Column { PickerRow( - title = "Age", + title = tr("Age"), value = draft.age?.let { "$it years" }, onClick = { activePicker = ProfilePickerKind.AGE }, ) HorizontalDivider(color = PulseColors.borderSubtle) PickerRow( - title = "Height", + title = tr("Height"), value = heightLabel(draft), onClick = { activePicker = ProfilePickerKind.HEIGHT }, ) HorizontalDivider(color = PulseColors.borderSubtle) PickerRow( - title = "Weight", + title = tr("Weight"), value = weightLabel(draft), onClick = { activePicker = ProfilePickerKind.WEIGHT }, ) @@ -187,7 +189,7 @@ fun ProfileEditor( when (activePicker) { ProfilePickerKind.AGE -> NumberPickerSheet( - title = "Age", + title = tr("Age"), values = (13..100).toList(), initialValue = draft.age, fallback = 30, @@ -196,7 +198,7 @@ fun ProfileEditor( onDismiss = { activePicker = null }, ) ProfilePickerKind.HEIGHT -> NumberPickerSheet( - title = "Height", + title = tr("Height"), values = if (draft.units == UnitSystem.METRIC) (120..220).toList() else (48..87).toList(), initialValue = draft.heightDisplayValue, fallback = if (draft.units == UnitSystem.METRIC) 175 else 69, @@ -207,7 +209,7 @@ fun ProfileEditor( onDismiss = { activePicker = null }, ) ProfilePickerKind.WEIGHT -> DecimalValueSheet( - title = "Weight", + title = tr("Weight"), initialValue = draft.weightDisplayValue, unit = if (draft.units == UnitSystem.METRIC) "kg" else "lb", validRange = if (draft.units == UnitSystem.METRIC) 35.0..250.0 else 77.0..551.0, @@ -300,7 +302,7 @@ private fun PickerRow(title: String, value: String?, onClick: () -> Unit) { ) Spacer(Modifier.weight(1f)) Text( - value ?: "Not set", + value ?: tr("Not set"), fontSize = 14.sp, color = if (value == null) PulseColors.textMuted else PulseColors.textSecondary, ) @@ -344,7 +346,7 @@ private fun NumberPickerSheet( TextButton(onClick = { onSave(null) onDismiss() - }) { Text("Clear", color = PulseColors.textSecondary) } + }) { Text(tr("Clear"), color = PulseColors.textSecondary) } Spacer(Modifier.weight(1f)) Text( title, @@ -356,7 +358,7 @@ private fun NumberPickerSheet( TextButton(onClick = { onSave(selection) onDismiss() - }) { Text("Done", color = PulseColors.accent, fontWeight = FontWeight.SemiBold) } + }) { Text(tr("Done"), color = PulseColors.accent, fontWeight = FontWeight.SemiBold) } } LazyColumn( state = listState, @@ -418,7 +420,7 @@ private fun DecimalValueSheet( TextButton(onClick = { onSave(null) onDismiss() - }) { Text("Clear", color = PulseColors.textSecondary) } + }) { Text(tr("Clear"), color = PulseColors.textSecondary) } Spacer(Modifier.weight(1f)) Text( title, @@ -435,7 +437,7 @@ private fun DecimalValueSheet( }, ) { Text( - "Done", + tr("Done"), color = if (parsedValue != null) PulseColors.accent else PulseColors.textMuted, fontWeight = FontWeight.SemiBold, ) @@ -498,7 +500,7 @@ private fun DecimalValueSheet( } Text( - "You can use either a comma or a period as the decimal separator.", + tr("You can use either a comma or a period as the decimal separator."), fontSize = 12.sp, color = PulseColors.textMuted, ) @@ -531,9 +533,9 @@ fun GoalEditor( val distanceRange = if (units == UnitSystem.METRIC) 1f..30f else 1f..20f Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(16.dp)) { - SectionHeaderCaps("Daily targets") + SectionHeaderCaps(tr("Daily targets")) GoalSliderCard( - title = "Steps", + title = tr("Steps"), icon = Icons.AutoMirrored.Filled.DirectionsWalk, tint = PulseColors.steps, value = draft.steps.toFloat(), @@ -543,7 +545,7 @@ fun GoalEditor( onValueChange = { onDraftChange(draft.copy(steps = it)) }, ) GoalSliderCard( - title = "Distance", + title = tr("Distance"), icon = Icons.Filled.Place, tint = PulseColors.distance, value = draft.distance.toFloat(), @@ -553,7 +555,7 @@ fun GoalEditor( onValueChange = { onDraftChange(draft.copy(distance = it)) }, ) GoalSliderCard( - title = "Calories", + title = tr("Calories"), icon = Icons.Filled.LocalFireDepartment, tint = PulseColors.calories, value = draft.calories.toFloat(), @@ -563,7 +565,7 @@ fun GoalEditor( onValueChange = { onDraftChange(draft.copy(calories = it)) }, ) GoalSliderCard( - title = "Active minutes", + title = tr("Active minutes"), icon = Icons.Filled.Timer, tint = PulseColors.readiness, value = draft.activeMinutes.toFloat(), @@ -573,7 +575,7 @@ fun GoalEditor( onValueChange = { onDraftChange(draft.copy(activeMinutes = it)) }, ) GoalSliderCard( - title = "Sleep", + title = tr("Sleep"), icon = Icons.Filled.Bedtime, tint = PulseColors.sleep, value = draft.sleepHours.toFloat(), @@ -584,9 +586,9 @@ fun GoalEditor( ) if (includeWeeklyWorkouts) { - SectionHeaderCaps("Weekly target") + SectionHeaderCaps(tr("Weekly target")) GoalSliderCard( - title = "Workouts", + title = tr("Workouts"), icon = Icons.Filled.DirectionsRun, tint = PulseColors.success, value = draft.workouts.toFloat(), diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt index 02c063bc..5f3ea6c8 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import android.content.ClipData import android.content.ClipboardManager import android.content.Context @@ -85,8 +87,8 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { scope.launch { when (val r = runCatching { ReferenceSourceScanner.scan(context) }.getOrNull()) { is ReferenceSourceScanner.Result.Done -> result = r - ReferenceSourceScanner.Result.Unavailable -> note = "Health Connect isn't available on this phone." - null -> note = "The scan failed. Try again in a moment." + ReferenceSourceScanner.Result.Unavailable -> note = tr("Health Connect isn't available on this phone.") + null -> note = tr("The scan failed. Try again in a moment.") } scanning = false } @@ -104,19 +106,19 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { val launcher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { got -> granted = got if (AccuracyCheckPermissions.readable(got).isEmpty()) { - note = "No access granted. You can allow it in Health Connect's settings." + note = tr("No access granted. You can allow it in Health Connect's settings.") } else scan() } val viewingCheck = viewing?.let { id -> history.firstOrNull { it.id == id } } if (viewingCheck != null) { - SettingsSubScreen(title = "Accuracy report", onBack = { viewing = null }) { + SettingsSubScreen(title = tr("Accuracy report"), onBack = { viewing = null }) { AccuracyReportSection(viewingCheck) } return } - SettingsSubScreen(title = "Accuracy check", onBack = onBack) { + SettingsSubScreen(title = tr("Accuracy check"), onBack = onBack) { val current = open when (current?.state) { AccuracyCheckEntity.STATE_RUNNING -> RunningCard(current, scope) @@ -127,24 +129,24 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { if (current == null) { AccuracyCard { - Text("Compare your ring with another device", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Compare your ring with another device"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( - "Wear the ring and a watch or band you trust for a few days. PulseLoop reads that device's data from " + - "Health Connect and shows where the ring agrees and where it falls short.", + tr("Wear the ring and a watch or band you trust for a few days. PulseLoop reads that device's data from " + + "Health Connect and shows where the ring agrees and where it falls short."), fontSize = 13.sp, color = PulseColors.textSecondary, ) Text( - "While a check runs, PulseLoop stops exporting the types the other device also writes, so Health Connect " + - "doesn't count your steps, sleep and heart rate twice.", + tr("While a check runs, PulseLoop stops exporting the types the other device also writes, so Health Connect " + + "doesn't count your steps, sleep and heart rate twice."), fontSize = 12.sp, color = PulseColors.textMuted, ) if (!available) { - Text("Health Connect isn't available on this phone.", fontSize = 12.sp, color = PulseColors.danger) + Text(tr("Health Connect isn't available on this phone."), fontSize = 12.sp, color = PulseColors.danger) } else { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { if (readable.size < ReferenceMetric.entries.size) { Button(onClick = { launcher.launch(AccuracyCheckPermissions.request) }, enabled = !scanning) { - Text(if (readable.isEmpty()) "Allow access" else "Allow more") + Text(if (readable.isEmpty()) tr("Allow access") else tr("Allow more")) } } if (readable.isNotEmpty()) { @@ -153,7 +155,7 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { if (scanning) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) } } - if (!hasRing) Text("Pair your ring first: a check compares it against the other device.", fontSize = 12.sp, color = PulseColors.textMuted) + if (!hasRing) Text(tr("Pair your ring first: a check compares it against the other device."), fontSize = 12.sp, color = PulseColors.textMuted) note?.let { Text(it, fontSize = 12.sp, color = PulseColors.warning) } } @@ -163,7 +165,7 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { AccuracyCard { Text("No other app wrote readable data in the last ${ReferenceSourceScanner.LOOKBACK_DAYS} days.", fontSize = 13.sp, color = PulseColors.textSecondary) Text( - "If your watch syncs through an app like Health Sync, check that it's set to write to Health Connect.", + tr("If your watch syncs through an app like Health Sync, check that it's set to write to Health Connect."), fontSize = 12.sp, color = PulseColors.textMuted, ) } @@ -174,19 +176,19 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { if (r.unreadable.isNotEmpty() || r.failed.isNotEmpty()) { AccuracyCard { if (r.unreadable.isNotEmpty()) { - Text("Not allowed to read: " + r.unreadable.joinToString(", ") { it.label }, fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("Not allowed to read: ") + r.unreadable.joinToString(", ") { it.label }, fontSize = 12.sp, color = PulseColors.textMuted) } if (r.failed.isNotEmpty()) { - Text("Couldn't read: " + r.failed.joinToString(", ") { it.label }, fontSize = 12.sp, color = PulseColors.warning) + Text(tr("Couldn't read: ") + r.failed.joinToString(", ") { it.label }, fontSize = 12.sp, color = PulseColors.warning) } } } OutlinedButton(onClick = { val text = ReferenceSurveyText.render(r.sources, ReferenceSourceScanner.LOOKBACK_DAYS, { ReferenceAppLabels.label(context, it) }, r.unreadable) (context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager) - .setPrimaryClip(ClipData.newPlainText("Accuracy check sources", text)) - note = "Summary copied. It holds counts and timings only, no readings." - }, modifier = Modifier.fillMaxWidth()) { Text("Copy summary") } + .setPrimaryClip(ClipData.newPlainText(tr("Accuracy check sources"), text)) + note = tr("Summary copied. It holds counts and timings only, no readings.") + }, modifier = Modifier.fillMaxWidth()) { Text(tr("Copy summary")) } } } @@ -195,7 +197,7 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { val past = history.filter { it.state == AccuracyCheckEntity.STATE_DONE } if (past.isNotEmpty()) { AccuracyCard { - Text("Past checks", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Past checks"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) past.forEach { c -> Row( Modifier.fillMaxWidth().clickable { viewing = c.id }.padding(vertical = 6.dp), @@ -205,7 +207,7 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { Text("${c.deviceLabel} vs ${c.referenceLabel}", fontSize = 13.sp, color = PulseColors.textPrimary) Text(AccuracyUiText.span(c), fontSize = 12.sp, color = PulseColors.textMuted) } - Text("View", fontSize = 13.sp, color = PulseColors.accent) + Text(tr("View"), fontSize = 13.sp, color = PulseColors.accent) } } } @@ -221,9 +223,9 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { scope.launch { note = when (AccuracyCheckController.start(context, src, label, days)) { is AccuracyCheckController.StartResult.Started -> null - AccuracyCheckController.StartResult.AlreadyOpen -> "A check is already open." - AccuracyCheckController.StartResult.NoRing -> "Pair your ring first." - AccuracyCheckController.StartResult.NothingToCompare -> "That app shares nothing PulseLoop can compare." + AccuracyCheckController.StartResult.AlreadyOpen -> tr("A check is already open.") + AccuracyCheckController.StartResult.NoRing -> tr("Pair your ring first.") + AccuracyCheckController.StartResult.NothingToCompare -> tr("That app shares nothing PulseLoop can compare.") } starting = null } @@ -247,8 +249,8 @@ internal object AccuracyUiText { } fun endReason(c: AccuracyCheckEntity): String = when (c.endReason) { - AccuracyCheckEntity.END_RING_CHANGED -> "Ended early: a different ring was paired." - AccuracyCheckEntity.END_EARLY -> "Ended early." + AccuracyCheckEntity.END_RING_CHANGED -> tr("Ended early: a different ring was paired.") + AccuracyCheckEntity.END_EARLY -> tr("Ended early.") else -> "Finished." } @@ -268,20 +270,20 @@ private fun RunningCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.Co Text("Accuracy check · day $day of $total", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text("${check.deviceLabel} vs ${check.referenceLabel}, until ${AccuracyUiText.date(check.plannedEndAt)}.", fontSize = 13.sp, color = PulseColors.textSecondary) Text("Wear both as usual. Health Connect export paused for: ${AccuracyUiText.units(units)}.", fontSize = 12.sp, color = PulseColors.warning) - OutlinedButton(onClick = { confirmEnd = true }) { Text("End now") } + OutlinedButton(onClick = { confirmEnd = true }) { Text(tr("End now")) } } if (confirmEnd) { AlertDialog( onDismissRequest = { confirmEnd = false }, - title = { Text("End the check now?") }, - text = { Text("The report covers the days so far. You'll then choose what happens to the paused Health Connect export.") }, + title = { Text(tr("End the check now?")) }, + text = { Text(tr("The report covers the days so far. You'll then choose what happens to the paused Health Connect export.")) }, confirmButton = { TextButton(onClick = { confirmEnd = false scope.launch { AccuracyCheckController.end(context, AccuracyCheckEntity.END_EARLY) } - }) { Text("End now") } + }) { Text(tr("End now")) } }, - dismissButton = { TextButton(onClick = { confirmEnd = false }) { Text("Keep going") } }, + dismissButton = { TextButton(onClick = { confirmEnd = false }) { Text(tr("Keep going")) } }, ) } } @@ -291,7 +293,7 @@ private fun ResumeCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.Cor val context = LocalContext.current var busy by remember { mutableStateOf(false) } AccuracyCard { - Text("Check finished: resume Health Connect export", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Check finished: resume Health Connect export"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(AccuracyUiText.endReason(check) + " ${AccuracyUiText.span(check)}.", fontSize = 13.sp, color = PulseColors.textSecondary) Text( "During the check, ${check.referenceLabel} wrote the same types to Health Connect. Exporting the ring's copy " + @@ -301,13 +303,13 @@ private fun ResumeCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.Cor Button(onClick = { busy = true scope.launch { AccuracyCheckController.resolve(context, AccuracyCheckEntity.RESUME_SKIP); busy = false } - }, enabled = !busy, modifier = Modifier.fillMaxWidth()) { Text("Skip these days (recommended)") } + }, enabled = !busy, modifier = Modifier.fillMaxWidth()) { Text(tr("Skip these days (recommended)")) } OutlinedButton(onClick = { busy = true scope.launch { AccuracyCheckController.resolve(context, AccuracyCheckEntity.RESUME_EXPORT); busy = false } - }, enabled = !busy, modifier = Modifier.fillMaxWidth()) { Text("Export them too") } + }, enabled = !busy, modifier = Modifier.fillMaxWidth()) { Text(tr("Export them too")) } Text( - "Export them too if you're taking the other device off and want the ring's full history in Health Connect.", + tr("Export them too if you're taking the other device off and want the ring's full history in Health Connect."), fontSize = 11.sp, color = PulseColors.textMuted, ) } @@ -330,17 +332,17 @@ private fun StartDialog( val units = source.metrics.map { ExportUnit.of(it.metric) } AlertDialog( onDismissRequest = onDismiss, - title = { Text("Start an accuracy check") }, + title = { Text(tr("Start an accuracy check")) }, text = { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { OutlinedTextField( value = label, onValueChange = { label = it }, singleLine = true, - label = { Text("Reference device") }, + label = { Text(tr("Reference device")) }, supportingText = if (source.packageName in ReferenceAppLabels.BRIDGES) { - { Text("A bridge app: name the watch behind it.") } + { Text(tr("A bridge app: name the watch behind it.")) } } else null, ) - Text("How long", fontSize = 13.sp, fontWeight = FontWeight.SemiBold) + Text(tr("How long"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold) Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { AccuracyCheckController.DURATIONS_DAYS.forEach { d -> FilterChip(selected = days == d, onClick = { days = d }, label = { Text("$d days") }) @@ -351,11 +353,11 @@ private fun StartDialog( "and you choose what to do with those days.", fontSize = 12.sp, ) - Text("Wear both devices as you normally would, including at night.", fontSize = 12.sp) + Text(tr("Wear both devices as you normally would, including at night."), fontSize = 12.sp) } }, - confirmButton = { TextButton(onClick = { onStart(label.trim(), days) }) { Text("Start") } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + confirmButton = { TextButton(onClick = { onStart(label.trim(), days) }) { Text(tr("Start")) } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(tr("Cancel")) } }, ) } @@ -366,13 +368,13 @@ private fun SourceCard(context: Context, s: ReferenceSourceSurvey, onUse: (() -> Text(s.packageName, fontSize = 11.sp, color = PulseColors.textMuted) if (s.packageName in ReferenceAppLabels.BRIDGES) { Text( - "A bridge app: it copies another app's data (for example Huawei Health) into Health Connect.", + tr("A bridge app: it copies another app's data (for example Huawei Health) into Health Connect."), fontSize = 12.sp, color = PulseColors.textSecondary, ) } Text( - if (s.devices.isEmpty()) "Device: not recorded" - else "Device: " + s.devices.joinToString("; ") { ReferenceSurveyText.device(it) }, + if (s.devices.isEmpty()) tr("Device: not recorded") + else tr("Device: ") + s.devices.joinToString("; ") { ReferenceSurveyText.device(it) }, fontSize = 12.sp, color = PulseColors.textSecondary, ) s.echo?.takeIf { it.looksLikeEcho }?.let { @@ -383,7 +385,7 @@ private fun SourceCard(context: Context, s: ReferenceSourceSurvey, onUse: (() -> ) } s.metrics.forEach { MetricRow(it) } - if (onUse != null) Button(onClick = onUse, modifier = Modifier.fillMaxWidth()) { Text("Compare my ring with this") } + if (onUse != null) Button(onClick = onUse, modifier = Modifier.fillMaxWidth()) { Text(tr("Compare my ring with this")) } } } @@ -399,8 +401,8 @@ private fun MetricRow(m: MetricSurvey) { ) if (m.metric == ReferenceMetric.SLEEP) { Text( - if (ReferenceSurveyText.hasSleepStages(m)) "With stages: " + m.sleepStageTypes.sorted().joinToString(", ") { ReferenceSurveyText.sleepStage(it) } - else "No sleep stages, only time asleep", + if (ReferenceSurveyText.hasSleepStages(m)) tr("With stages: ") + m.sleepStageTypes.sorted().joinToString(", ") { ReferenceSurveyText.sleepStage(it) } + else tr("No sleep stages, only time asleep"), fontSize = 12.sp, color = PulseColors.textMuted, ) } @@ -445,12 +447,12 @@ internal fun AccuracyCheckBanner(c: AccuracyCheckEntity, onOpen: () -> Unit) { val text = if (c.state == AccuracyCheckEntity.STATE_RUNNING) { val (day, total) = AccuracyUiText.dayOf(c) "Accuracy check · day $day of $total · Health Connect export paused" - } else "Accuracy report ready · choose what to do with the paused export" + } else tr("Accuracy report ready · choose what to do with the paused export") Row( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).clickable(onClick = onOpen).padding(12.dp), verticalAlignment = Alignment.CenterVertically, ) { Text(text, fontSize = 12.sp, color = PulseColors.warning, modifier = Modifier.weight(1f)) - Text("Open", fontSize = 12.sp, color = PulseColors.accent) + Text(tr("Open"), fontSize = 12.sp, color = PulseColors.accent) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt index 96f2ab59..5fa53c04 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement @@ -99,11 +101,11 @@ internal fun AccuracyReportSection( AccuracyCard { Row(verticalAlignment = Alignment.CenterVertically) { Text( - if (check.state == AccuracyCheckEntity.STATE_RUNNING) "So far (preliminary)" else "Report", + if (check.state == AccuracyCheckEntity.STATE_RUNNING) tr("So far (preliminary)") else tr("Report"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, modifier = Modifier.weight(1f), ) if (scoring) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) - else TextButton(onClick = { rescore(force = true) }) { Text("Recompute") } + else TextButton(onClick = { rescore(force = true) }) { Text(tr("Recompute")) } if (summaries.isNotEmpty()) TextButton(onClick = { scope.launch { val ring = db.deviceDao().currentReal()?.takeIf { RingIdentity.keyOf(it) == check.deviceKey } @@ -115,9 +117,9 @@ internal fun AccuracyReportSection( type = "text/plain" putExtra(android.content.Intent.EXTRA_TEXT, text) } - context.startActivity(android.content.Intent.createChooser(send, "Share accuracy report")) + context.startActivity(android.content.Intent.createChooser(send, tr("Share accuracy report"))) } - }) { Text("Share") } + }) { Text(tr("Share")) } } Text( "How your ring compares with ${check.referenceLabel}, the device you chose to trust. This is agreement between two " + @@ -127,8 +129,8 @@ internal fun AccuracyReportSection( if (echo?.looksLikeEcho == true) { Text( "${echo.matching} of ${echo.compared} heart-rate readings from ${check.referenceLabel} match your ring exactly. " + - "That looks like PulseLoop's own data coming back through a sync app, so this report would compare the ring " + - "with itself. Check the sync direction in that app.", + tr("That looks like PulseLoop's own data coming back through a sync app, so this report would compare the ring " + + "with itself. Check the sync direction in that app."), fontSize = 12.sp, color = PulseColors.danger, ) } @@ -141,17 +143,17 @@ internal fun AccuracyReportSection( } status?.let { Text(it, fontSize = 12.sp, color = PulseColors.warning) } if (days.isEmpty() && !scoring) { - Text("Nothing to compare yet. Check back after the first full day and night.", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(tr("Nothing to compare yet. Check back after the first full day and night."), fontSize = 13.sp, color = PulseColors.textSecondary) } val worst = AccuracyReportText.worstFirst(summaries) if (worst.isNotEmpty()) { - Text("Where the ring falls short", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + Text(tr("Where the ring falls short"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) worst.forEach { s -> Text("• ${s.metric.label}: ${AccuracyReportText.signed(s.metric, s.bias)} (${AccuracyReportText.verdictLabel(s.verdict).lowercase()})", fontSize = 12.sp, color = PulseColors.textSecondary) } } else if (summaries.isNotEmpty() && summaries.none { it.verdict == Verdict.NOT_ENOUGH_DATA }) { - Text("Everything compared agrees within its band.", fontSize = 13.sp, color = PulseColors.success) + Text(tr("Everything compared agrees within its band."), fontSize = 13.sp, color = PulseColors.success) } } @@ -211,7 +213,7 @@ private fun MetricCard( correction?.invoke(summary) } if (!expanded) { - Text("Details", fontSize = 12.sp, color = PulseColors.accent, modifier = Modifier.clickable(onClick = onToggle)) + Text(tr("Details"), fontSize = 12.sp, color = PulseColors.accent, modifier = Modifier.clickable(onClick = onToggle)) return@AccuracyCard } if (m.kind != ComparisonMetric.Kind.STAGES && summary.validDays > 0) { @@ -312,13 +314,13 @@ internal fun AccuracyCorrectionControl(check: AccuracyCheckEntity, summary: Accu existing != null && existing.enabled -> Row(verticalAlignment = Alignment.CenterVertically) { Text("Correction on: ${AccuracyCorrections.formatValue(metric, existing.value)}", fontSize = 12.sp, color = PulseColors.success, modifier = Modifier.weight(1f)) - TextButton(onClick = { editing = true }) { Text("Change") } - TextButton(onClick = { scope.launch { AccuracyCorrections.setEnabled(db, existing, false) } }) { Text("Turn off") } + TextButton(onClick = { editing = true }) { Text(tr("Change")) } + TextButton(onClick = { scope.launch { AccuracyCorrections.setEnabled(db, existing, false) } }) { Text(tr("Turn off")) } } existing != null -> Row(verticalAlignment = Alignment.CenterVertically) { Text("Correction off (${AccuracyCorrections.formatValue(metric, existing.value)})", fontSize = 12.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) - TextButton(onClick = { scope.launch { AccuracyCorrections.setEnabled(db, existing, true) } }) { Text("Turn on") } + TextButton(onClick = { scope.launch { AccuracyCorrections.setEnabled(db, existing, true) } }) { Text(tr("Turn on")) } } else -> Button(onClick = { editing = true }, modifier = Modifier.fillMaxWidth()) { Text("Apply correction (${AccuracyCorrections.formatValue(metric, fitted)})") @@ -350,17 +352,17 @@ private fun CorrectionDialog( Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( "Fitted from this check so your ring matches $ref: ${AccuracyCorrections.formatValue(metric, fitted)}. " + - "It changes what PulseLoop shows and what it works out from it (zones, resting baseline, calorie estimate). " + - "Your ring's stored readings and what goes to Health Connect stay as measured.", + tr("It changes what PulseLoop shows and what it works out from it (zones, resting baseline, calorie estimate). " + + "Your ring's stored readings and what goes to Health Connect stay as measured."), fontSize = 12.sp, ) Text(AccuracyCorrections.formatValue(metric, value), fontSize = 20.sp, fontWeight = FontWeight.Bold) Slider(value = value.toFloat(), onValueChange = { value = it.toDouble() }, valueRange = range) - TextButton(onClick = { value = fitted }) { Text("Use the fitted value") } + TextButton(onClick = { value = fitted }) { Text(tr("Use the fitted value")) } } }, - confirmButton = { TextButton(onClick = { onSave(roundCorrection(metric, value)) }) { Text("Apply") } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + confirmButton = { TextButton(onClick = { onSave(roundCorrection(metric, value)) }) { Text(tr("Apply")) } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(tr("Cancel")) } }, ) } @@ -397,8 +399,8 @@ internal fun AccuracyCorrectionsCard() { Text("Corrections for ${RingIdentity.labelOf(r)}", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) if (mine.isEmpty()) { Text( - if (all.isNotEmpty()) "No accuracy check for this ring yet. Corrections from another ring don't carry over." - else "None. A finished check offers one wherever the ring is consistently off.", + if (all.isNotEmpty()) tr("No accuracy check for this ring yet. Corrections from another ring don't carry over.") + else tr("None. A finished check offers one wherever the ring is consistently off."), fontSize = 12.sp, color = PulseColors.textMuted, ) return@AccuracyCard @@ -414,9 +416,9 @@ internal fun AccuracyCorrectionsCard() { } } Switch(checked = c.enabled, onCheckedChange = { on -> scope.launch { AccuracyCorrections.setEnabled(db, c, on) } }) - TextButton(onClick = { scope.launch { AccuracyCorrections.remove(db, c) } }) { Text("Remove") } + TextButton(onClick = { scope.launch { AccuracyCorrections.remove(db, c) } }) { Text(tr("Remove")) } } } - Text("Applied to what PulseLoop shows, never to stored readings or Health Connect.", fontSize = 11.sp, color = PulseColors.textMuted) + Text(tr("Applied to what PulseLoop shows, never to stored readings or Health Connect."), fontSize = 11.sp, color = PulseColors.textMuted) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt index 35019a8f..d685984c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.components.switchRow import com.pulseloop.ui.theme.dither @@ -187,7 +189,7 @@ fun ActivityScreen( .clickable(role = Role.Button) { historyOpen = true }, contentAlignment = Alignment.Center, ) { - Icon(Icons.Filled.CalendarMonth, "Workout history", tint = PulseColors.textSecondary) + Icon(Icons.Filled.CalendarMonth, tr("Workout history"), tint = PulseColors.textSecondary) } } } @@ -214,8 +216,8 @@ fun ActivityScreen( } Spacer(Modifier.width(12.dp)) Column(Modifier.weight(1f)) { - Text("Log Past Activity", fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text("Add a workout you forgot to record", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("Log Past Activity"), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + Text(tr("Add a workout you forgot to record"), fontSize = 12.sp, color = PulseColors.textMuted) } Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, null, tint = PulseColors.textMuted) } @@ -240,8 +242,8 @@ fun ActivityScreen( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Text("No workouts recorded today", fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) - Text("Start one manually when your ring misses an activity.", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("No workouts recorded today"), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) + Text(tr("Start one manually when your ring misses an activity."), fontSize = 12.sp, color = PulseColors.textMuted) } } } else { @@ -270,11 +272,11 @@ fun ActivityScreen( if (permissionDenied) { AlertDialog( onDismissRequest = { permissionDenied = false }, - title = { Text("Permission needed") }, + title = { Text(tr("Permission needed")) }, text = { Text( - "Recording a workout needs the Physical activity permission. " + - "You can allow it in Android Settings › Apps › PulseLoop › Permissions.", + tr("Recording a workout needs the Physical activity permission. " + + "You can allow it in Android Settings › Apps › PulseLoop › Permissions."), ) }, confirmButton = { TextButton(onClick = { permissionDenied = false }) { Text("OK") } }, @@ -346,14 +348,14 @@ private fun ActivityDayNavHeader(state: ActivityViewModel.ActivityState, viewMod verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, ) { - ActivityNavChevron(Icons.Filled.ChevronLeft, "Previous day", canOlder) { viewModel?.stepDay(older = true) } + ActivityNavChevron(Icons.Filled.ChevronLeft, tr("Previous day"), canOlder) { viewModel?.stepDay(older = true) } Text( dayHeaderLabel(shownDayStart(state)), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, modifier = Modifier.weight(1f), textAlign = androidx.compose.ui.text.style.TextAlign.Center, ) - ActivityNavChevron(Icons.Filled.ChevronRight, "Next day", canNewer) { viewModel?.stepDay(older = false) } + ActivityNavChevron(Icons.Filled.ChevronRight, tr("Next day"), canNewer) { viewModel?.stepDay(older = false) } } } @@ -384,8 +386,8 @@ private fun dayHeaderLabel(dayMillis: Long): String { val daysAgo = ((today - dayMillis) / 86_400_000L).toInt() val date = Instant.ofEpochMilli(dayMillis).atZone(ZoneId.systemDefault()) return when { - daysAgo <= 0 -> "Today" - daysAgo == 1 -> "Yesterday" + daysAgo <= 0 -> tr("Today") + daysAgo == 1 -> tr("Yesterday") daysAgo < 7 -> date.format(DateTimeFormatter.ofPattern("EEEE")) date.year == java.time.Year.now().value -> date.format(DateTimeFormatter.ofPattern("EEE, MMM d")) else -> date.format(DateTimeFormatter.ofPattern("MMM d, yyyy")) @@ -414,12 +416,12 @@ private fun DailyActivitySummaryCard(state: ActivityViewModel.ActivityState, uni ) { Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(18.dp)) { Row { - SummaryMetric("Steps", today?.steps?.let { Formats.count(it) } ?: "—", null, PulseColors.steps, Modifier.weight(1f)) - SummaryMetric("Distance", distValue ?: "—", if (distValue != null) UnitConverter.distanceUnit(units) else null, PulseColors.distance, Modifier.weight(1f)) + SummaryMetric(tr("Steps"), today?.steps?.let { Formats.count(it) } ?: "—", null, PulseColors.steps, Modifier.weight(1f)) + SummaryMetric(tr("Distance"), distValue ?: "—", if (distValue != null) UnitConverter.distanceUnit(units) else null, PulseColors.distance, Modifier.weight(1f)) } // The same figure the Today screen shows, not the row's raw `calories` (issue #101). val calories = state.dayCalories - SummaryMetric("Calories", calories?.let { Formats.count(it.toInt()) } ?: "—", if (calories != null) "cal" else null, PulseColors.calories) + SummaryMetric(tr("Calories"), calories?.let { Formats.count(it.toInt()) } ?: "—", if (calories != null) "cal" else null, PulseColors.calories) } ActivityRings( rings = listOf( @@ -548,7 +550,7 @@ private fun WeeklyGoalCard(state: ActivityViewModel.ActivityState, days: List Unit, onStart: (String, Bool var useGps by remember { mutableStateOf(true) } AlertDialog( onDismissRequest = onDismiss, - title = { Text("Record activity") }, + title = { Text(tr("Record activity")) }, text = { // Scrolls: eight types plus the GPS row overflow a landscape or large-font dialog. Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(4.dp)) { @@ -686,9 +688,9 @@ private fun RecordTypePickerDialog(onDismiss: () -> Unit, onStart: (String, Bool } }, confirmButton = { - TextButton(onClick = { onStart(selected, useGps && ActivityMeta.gpsCapable(selected)) }) { Text("Start") } + TextButton(onClick = { onStart(selected, useGps && ActivityMeta.gpsCapable(selected)) }) { Text(tr("Start")) } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(tr("Cancel")) } }, ) } @@ -719,10 +721,10 @@ private fun WorkoutHistoryDialog( AlertDialog( onDismissRequest = onDismiss, - title = { Text("Workout history") }, + title = { Text(tr("Workout history")) }, text = { if (groups.isEmpty()) { - Text("No workouts yet — recorded workouts will appear here.") + Text(tr("No workouts yet — recorded workouts will appear here.")) } else { LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.heightIn(max = 420.dp)) { groups.forEachIndexed { index, (day, daySessions) -> @@ -745,7 +747,7 @@ private fun WorkoutHistoryDialog( } } }, - confirmButton = { TextButton(onClick = onDismiss) { Text("Done") } }, + confirmButton = { TextButton(onClick = onDismiss) { Text(tr("Done")) } }, ) } @@ -762,21 +764,21 @@ private fun GoalEditorDialog( var workouts by remember { mutableStateOf(state.workoutsPerWeekGoal.toFloat()) } AlertDialog( onDismissRequest = onDismiss, - title = { Text("Edit goals") }, + title = { Text(tr("Edit goals")) }, text = { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - GoalSlider("Steps", Formats.count((steps / 500).toInt() * 500), steps, 2000f..20000f) { steps = it } - GoalSlider("Active minutes", "${active.toInt()} min", active, 10f..180f) { active = it } + GoalSlider(tr("Steps"), Formats.count((steps / 500).toInt() * 500), steps, 2000f..20000f) { steps = it } + GoalSlider(tr("Active minutes"), "${active.toInt()} min", active, 10f..180f) { active = it } GoalSlider("Sleep", "%.1f h".format((sleepH * 2).toInt() / 2f), sleepH, 5f..10f) { sleepH = it } - GoalSlider("Workouts / week", "${workouts.toInt()}", workouts, 1f..7f) { workouts = it } + GoalSlider(tr("Workouts / week"), "${workouts.toInt()}", workouts, 1f..7f) { workouts = it } } }, confirmButton = { TextButton(onClick = { onSave((steps / 500).toInt() * 500, active.toInt(), ((sleepH * 2).toInt() * 30), workouts.toInt()) - }) { Text("Save") } + }) { Text(tr("Save")) } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(tr("Cancel")) } }, ) } @@ -832,9 +834,9 @@ private fun ActivityRecordsCard( Modifier.fillMaxWidth() .clickable( role = Role.Button, - onClickLabel = if (expanded) "Hide activity records" else "Show activity records", + onClickLabel = if (expanded) tr("Hide activity records") else tr("Show activity records"), ) { expanded = !expanded } - .semantics { stateDescription = if (expanded) "Expanded" else "Collapsed" } + .semantics { stateDescription = if (expanded) tr("Expanded") else tr("Collapsed") } .padding(16.dp), verticalAlignment = Alignment.CenterVertically, ) { @@ -859,7 +861,7 @@ private fun ActivityRecordsCard( val rows = buckets when { rows == null -> Text( - "Loading…", + tr("Loading…"), fontSize = 13.sp, color = PulseColors.textMuted, modifier = Modifier.padding(start = 16.dp, bottom = 12.dp), ) @@ -893,7 +895,7 @@ private fun ActivityRecordsCard( IconButton(onClick = { pending = bucket }) { Icon( Icons.Filled.DeleteOutline, - contentDescription = "Delete this activity record", + contentDescription = tr("Delete this activity record"), tint = PulseColors.textMuted, modifier = Modifier.size(18.dp), ) @@ -917,12 +919,12 @@ private fun ActivityRecordsCard( pending?.let { bucket -> AlertDialog( onDismissRequest = { pending = null }, - title = { Text("Delete this activity record?") }, + title = { Text(tr("Delete this activity record?")) }, text = { Text( "${Formats.count(bucket.steps)} steps at ${timeOf(bucket.startEpoch)}." + - "\n\nThe day's total drops by that much. This can't be undone, and the record " + - "stays deleted the next time this day syncs.", + tr("\n\nThe day's total drops by that much. This can't be undone, and the record " + + "stays deleted the next time this day syncs."), ) }, confirmButton = { @@ -930,9 +932,9 @@ private fun ActivityRecordsCard( val target = bucket pending = null scope.launch { buckets = viewModel?.deleteBucket(target.startEpoch) ?: buckets } - }) { Text("Delete", color = MaterialTheme.colorScheme.error) } + }) { Text(tr("Delete"), color = MaterialTheme.colorScheme.error) } }, - dismissButton = { TextButton(onClick = { pending = null }) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = { pending = null }) { Text(tr("Cancel")) } }, ) } } @@ -963,7 +965,7 @@ private fun DetectedActivityCard() { .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Text("DETECTED · REVIEW", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("DETECTED · REVIEW"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) proposals.forEach { p -> val defaultType = when (p.kind) { com.pulseloop.service.ActivityDetection.Proposal.Kind.WALK -> "walk" @@ -974,7 +976,7 @@ private fun DetectedActivityCard() { val isNap = p.kind == com.pulseloop.service.ActivityDetection.Proposal.Kind.NAP Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { Text( - (if (isNap) "Possible nap" else "Possible ${ActivityMeta.label(type).lowercase()}") + " · ${p.minutes} min", + (if (isNap) tr("Possible nap") else "Possible ${ActivityMeta.label(type).lowercase()}") + " · ${p.minutes} min", fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Text( @@ -997,13 +999,13 @@ private fun DetectedActivityCard() { } Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { Text( - if (isNap) "Yes, a nap" else "Add workout", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, + if (isNap) tr("Yes, a nap") else tr("Add workout"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, modifier = Modifier.clickable { scope.launch { runCatching { com.pulseloop.service.ActivityDetection.accept(context, db, p, type) }; tick++ } }.padding(vertical = 4.dp), ) Text( - "Not this", fontSize = 13.sp, color = PulseColors.textMuted, + tr("Not this"), fontSize = 13.sp, color = PulseColors.textMuted, modifier = Modifier.clickable { com.pulseloop.service.ActivityDetection.answer(context, p); tick++ }.padding(vertical = 4.dp), ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt index c34961ac..31d29fc1 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import android.Manifest import android.content.Context import android.content.Intent @@ -218,13 +220,13 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { verticalAlignment = Alignment.CenterVertically, ) { Text( - "Scan barcode", + tr("Scan barcode"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, modifier = Modifier.weight(1f), ) - TextButton(onClick = onDismiss) { Text("Cancel") } + TextButton(onClick = onDismiss) { Text(tr("Cancel")) } } when (availability) { ScanAvailability.Granted -> @@ -250,14 +252,14 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { ) Spacer(Modifier.height(10.dp)) Text( - "Scanning unavailable", + tr("Scanning unavailable"), fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Spacer(Modifier.height(6.dp)) Text( - "Barcode scanning needs a working device camera. Enter the food manually instead.", + tr("Barcode scanning needs a working device camera. Enter the food manually instead."), fontSize = 12.sp, color = PulseColors.textMuted, textAlign = TextAlign.Center, @@ -278,14 +280,14 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { ) Spacer(Modifier.height(10.dp)) Text( - "Camera access needed", + tr("Camera access needed"), fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Spacer(Modifier.height(6.dp)) Text( - "Allow camera access in Settings to scan barcodes, or enter the food manually instead.", + tr("Allow camera access in Settings to scan barcodes, or enter the food manually instead."), fontSize = 12.sp, color = PulseColors.textMuted, textAlign = TextAlign.Center, @@ -298,7 +300,7 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { .setData(Uri.fromParts("package", context.packageName, null)), ) } - }) { Text("Open settings") } + }) { Text(tr("Open settings")) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt b/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt index faaba08e..e650ff5d 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.components.switchRow import androidx.activity.compose.rememberLauncherForActivityResult @@ -85,7 +87,7 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { scope.launch { val n = runCatching { HealthConnectBodyImport.run(context) }.getOrDefault(0) busy = false - note = if (n == 0) "No body measurements found in Health Connect yet." else null + note = if (n == 0) tr("No body measurements found in Health Connect yet.") else null refresh++ onUpdated() } @@ -95,7 +97,7 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { val any = granted.any { it in HealthConnectBodyImport.permissions } enabled = any HealthConnectBodyImport.setEnabled(context, any) - if (any) importNow() else note = "No access granted. You can allow it in Health Connect's settings." + if (any) importNow() else note = tr("No access granted. You can allow it in Health Connect's settings.") } Column( @@ -107,16 +109,16 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { else { enabled = false; HealthConnectBodyImport.setEnabled(context, false) } }), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Sync from your scale", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Sync from your scale"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( - "Weight, height and body composition from Health Connect (Fitdays and other scale apps).", + tr("Weight, height and body composition from Health Connect (Fitdays and other scale apps)."), fontSize = 12.sp, color = PulseColors.textSecondary, ) } Switch(checked = enabled, enabled = available && !busy, onCheckedChange = null) } if (!available) { - Text("Health Connect isn't available on this phone.", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("Health Connect isn't available on this phone."), fontSize = 12.sp, color = PulseColors.textMuted) } val s = snapshot @@ -139,7 +141,7 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { } note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textMuted) } if (enabled) { - TextButton(onClick = { importNow() }, enabled = !busy) { Text(if (busy) "Syncing…" else "Sync now") } + TextButton(onClick = { importNow() }, enabled = !busy) { Text(if (busy) tr("Syncing…") else tr("Sync now")) } } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt index e7a54f58..181ec821 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowDropDown @@ -62,7 +64,7 @@ fun CoachModelPicker( val presetSlugs = presets.map { it.first }.toSet() val others = success?.entries?.filter { it.id !in presetSlugs }.orEmpty() - Text("Model", style = MaterialTheme.typography.labelMedium) + Text(tr("Model"), style = MaterialTheme.typography.labelMedium) Spacer(Modifier.height(4.dp)) var expanded by remember { mutableStateOf(false) } var filter by remember(provider) { mutableStateOf("") } @@ -83,7 +85,7 @@ fun CoachModelPicker( onClick = { onPick(slug); expanded = false }, ) - if (presets.isNotEmpty()) MenuHeader("Recommended") + if (presets.isNotEmpty()) MenuHeader(tr("Recommended")) presets.forEach { (slug, blurb) -> Item(slug, blurb) } if (others.isNotEmpty()) { @@ -95,8 +97,8 @@ fun CoachModelPicker( OutlinedTextField( value = filter, onValueChange = { filter = it }, - label = { Text("Filter models") }, - placeholder = { Text("Filter, e.g. claude") }, + label = { Text(tr("Filter models")) }, + placeholder = { Text(tr("Filter, e.g. claude")) }, singleLine = true, modifier = Modifier.padding(horizontal = 12.dp).fillMaxWidth(), ) @@ -133,7 +135,7 @@ fun CoachModelPicker( Text(status, style = MaterialTheme.typography.bodySmall, color = color, modifier = Modifier.weight(1f)) if (savedKey.isNotBlank() && !loading) { TextButton(onClick = { load(force = true) }) { - Text(if (listing is CoachModelCatalog.Result.Failure) "Retry" else "Refresh") + Text(if (listing is CoachModelCatalog.Result.Failure) tr("Retry") else tr("Refresh")) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt index 8cb1181f..70a9a2d7 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import android.content.res.Configuration import androidx.activity.compose.rememberLauncherForActivityResult @@ -117,8 +119,8 @@ fun CoachScreen( plan = goalPlan, hasGoal = activeGoal != null, enabled = !state.isThinking, - onSetGoal = { viewModel?.sendMessage("I'd like to set a goal. Ask me what I want and help me make it realistic for my data.", emptyList()) }, - onCheckIn = { viewModel?.sendMessage("How am I doing on my goal? What should I focus on this week?", emptyList()) }, + onSetGoal = { viewModel?.sendMessage(tr("I'd like to set a goal. Ask me what I want and help me make it realistic for my data."), emptyList()) }, + onCheckIn = { viewModel?.sendMessage(tr("How am I doing on my goal? What should I focus on this week?"), emptyList()) }, ) } // Persisted rows key by id; the greeting and this session's unsaved turns have none. @@ -128,7 +130,7 @@ fun CoachScreen( if (state.isThinking) { item { Text( - "Coach is thinking…", + tr("Coach is thinking…"), fontSize = 12.sp, color = PulseColors.textMuted, modifier = Modifier.padding(start = 8.dp), ) @@ -193,16 +195,16 @@ fun CoachHeader(onNewChat: () -> Unit, onOpenUsage: (() -> Unit)? = null) { ) } Column(Modifier.weight(1f)) { - Text("PulseLoop Coach", fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text("Using your latest ring sync", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("PulseLoop Coach"), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + Text(tr("Using your latest ring sync"), fontSize = 12.sp, color = PulseColors.textMuted) } if (onOpenUsage != null) { RoundIconTarget(visualSize = 36.dp, onClick = onOpenUsage) { - Icon(Icons.Filled.Info, "Usage & cost", tint = PulseColors.textSecondary, modifier = Modifier.size(16.dp)) + Icon(Icons.Filled.Info, tr("Usage & cost"), tint = PulseColors.textSecondary, modifier = Modifier.size(16.dp)) } } RoundIconTarget(visualSize = 36.dp, onClick = onNewChat) { - Icon(Icons.Filled.Add, "New chat", tint = PulseColors.textSecondary, modifier = Modifier.size(18.dp)) + Icon(Icons.Filled.Add, tr("New chat"), tint = PulseColors.textSecondary, modifier = Modifier.size(18.dp)) } } } @@ -273,7 +275,7 @@ private fun MessageBubble(msg: CoachViewModel.ChatMessage, viewModel: CoachViewM bmp?.let { Image( bitmap = it.asImageBitmap(), - contentDescription = "Attached photo", + contentDescription = tr("Attached photo"), modifier = Modifier.size(96.dp).clip(RoundedCornerShape(4.dp)), contentScale = ContentScale.Crop, ) @@ -300,10 +302,10 @@ private fun MessageBubble(msg: CoachViewModel.ChatMessage, viewModel: CoachViewM // ─────────────────────────── Composer ─────────────────────────── private val SUGGESTIONS = listOf( - "How am I doing today?", - "Explain my heart rate trend", - "Summarize my week", - "How can I sleep better?", + tr("How am I doing today?"), + tr("Explain my heart rate trend"), + tr("Summarize my week"), + tr("How can I sleep better?"), ) @Composable @@ -401,7 +403,7 @@ private fun Composer( bmp?.let { Image( bitmap = it.asImageBitmap(), - contentDescription = "Staged photo", + contentDescription = tr("Staged photo"), modifier = Modifier.size(56.dp).clip(RoundedCornerShape(4.dp)), contentScale = ContentScale.Crop, ) @@ -418,7 +420,7 @@ private fun Composer( }, contentAlignment = Alignment.TopEnd, ) { - Icon(Icons.Filled.Close, "Remove photo", Modifier.padding(3.dp).size(14.dp), tint = Color.White) + Icon(Icons.Filled.Close, tr("Remove photo"), Modifier.padding(3.dp).size(14.dp), tint = Color.White) } } } @@ -434,7 +436,7 @@ private fun Composer( // input. Bordered circle + "+" glyph mirrors the header's affordance exactly so the // control reads the same in both orientations. RoundIconTarget(visualSize = 40.dp, onClick = onNewChat) { - Icon(Icons.Filled.Add, "New chat", tint = PulseColors.textSecondary, modifier = Modifier.size(18.dp)) + Icon(Icons.Filled.Add, tr("New chat"), tint = PulseColors.textSecondary, modifier = Modifier.size(18.dp)) } } if (imageInputEnabled) { @@ -444,7 +446,7 @@ private fun Composer( enabled = !isThinking, onClick = { pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) }, ) { - Icon(Icons.Filled.Add, "Attach photo", tint = PulseColors.textMuted, modifier = Modifier.size(20.dp)) + Icon(Icons.Filled.Add, tr("Attach photo"), tint = PulseColors.textMuted, modifier = Modifier.size(20.dp)) } } // Pill text field (iOS composer): filled capsule, no outline. @@ -456,7 +458,7 @@ private fun Composer( .padding(horizontal = 16.dp, vertical = 12.dp), ) { if (inputText.isEmpty()) { - Text("Ask the coach...", fontSize = 14.sp, color = PulseColors.textMuted) + Text(tr("Ask the coach..."), fontSize = 14.sp, color = PulseColors.textMuted) } BasicTextField( value = inputText, @@ -474,7 +476,7 @@ private fun Composer( keyboardActions = KeyboardActions(onSend = { send() }), // The placeholder is a sibling Text that disappears once typing starts, so // the field carries its own label. - modifier = Modifier.fillMaxWidth().semantics { contentDescription = "Message the coach" }, + modifier = Modifier.fillMaxWidth().semantics { contentDescription = tr("Message the coach") }, ) } RoundIconTarget( @@ -485,7 +487,7 @@ private fun Composer( onClick = ::send, ) { Icon( - Icons.Filled.ArrowUpward, "Send", + Icons.Filled.ArrowUpward, tr("Send"), tint = if (canSend) PulseColors.onAccent else PulseColors.textMuted, modifier = Modifier.size(20.dp), ) @@ -518,12 +520,12 @@ private fun GoalBanner( Text("◎", fontSize = 18.sp, color = PulseColors.accent) Column(Modifier.weight(1f)) { if (hasGoal && plan != null) { - Text("YOUR GOAL", fontSize = 10.sp, letterSpacing = 1.4.sp, color = PulseColors.accent) + Text(tr("YOUR GOAL"), fontSize = 10.sp, letterSpacing = 1.4.sp, color = PulseColors.accent) Text(com.pulseloop.service.GoalPlan.headline(plan), fontSize = 14.sp, color = PulseColors.textPrimary, maxLines = 2) - Text(com.pulseloop.service.GoalPlan.focusLine(plan) + " · tap for this week's plan", fontSize = 12.sp, color = PulseColors.textSecondary, maxLines = 2) + Text(com.pulseloop.service.GoalPlan.focusLine(plan) + tr(" · tap for this week's plan"), fontSize = 12.sp, color = PulseColors.textSecondary, maxLines = 2) } else { - Text("What's your goal?", fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("Tell the coach, and it plans with your scale, ring and food data.", fontSize = 12.sp, color = PulseColors.textSecondary) + Text(tr("What's your goal?"), fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Tell the coach, and it plans with your scale, ring and food data."), fontSize = 12.sp, color = PulseColors.textSecondary) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt index c1bac44a..a7c82d4c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import androidx.compose.foundation.background import androidx.compose.foundation.clickable @@ -71,7 +73,7 @@ fun CoachUsageSheet( .padding(bottom = 24.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Text("Usage & cost", fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + Text(tr("Usage & cost"), fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) SummaryCard(providerLabel, models, totalInputTokens, totalOutputTokens, totalCost) if (showsCostNote) CostNote() if (accounted.isNotEmpty()) BreakdownCard(accounted) @@ -91,13 +93,13 @@ private fun SummaryCard( .background(PulseColors.card) .padding(horizontal = 16.dp), ) { - UsageRow("Provider", providerLabel) + UsageRow(tr("Provider"), providerLabel) Divider() - UsageRow(if (models.size > 1) "Models" else "Model", models.joinToString(", ")) + UsageRow(if (models.size > 1) tr("Models") else tr("Model"), models.joinToString(", ")) Divider() - UsageRow("Input tokens", formatTokens(totalInputTokens), mono = true) + UsageRow(tr("Input tokens"), formatTokens(totalInputTokens), mono = true) Divider() - UsageRow("Output tokens", formatTokens(totalOutputTokens), mono = true) + UsageRow(tr("Output tokens"), formatTokens(totalOutputTokens), mono = true) Divider() UsageRow("Estimated cost", totalCost?.let { "$" + "%.4f".format(it) } ?: "—", mono = true) } @@ -115,7 +117,7 @@ private fun CostNote() { ) { Icon(Icons.Filled.Info, null, tint = PulseColors.textMuted, modifier = Modifier.size(14.dp)) Text( - "Cost estimates aren't available for on-device or custom models.", + tr("Cost estimates aren't available for on-device or custom models."), fontSize = 12.sp, color = PulseColors.textMuted, ) } @@ -137,10 +139,10 @@ private fun BreakdownCard(accounted: List) { verticalAlignment = Alignment.CenterVertically, ) { Text( - "Per-message breakdown", fontSize = 13.sp, fontWeight = FontWeight.Medium, + tr("Per-message breakdown"), fontSize = 13.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, ) - Text(if (expanded) "Hide" else "Show", fontSize = 12.sp, color = PulseColors.textSecondary) + Text(if (expanded) tr("Hide") else tr("Show"), fontSize = 12.sp, color = PulseColors.textSecondary) } if (expanded) { Column(Modifier.padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { diff --git a/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt b/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt index 725aed24..5216559f 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* @@ -55,8 +57,8 @@ fun CycleScreen(onBack: () -> Unit) { Column(Modifier.fillMaxSize().background(PulseColors.background)) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { - IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } - Text("Cycle", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } + Text(tr("Cycle"), modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) } Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), @@ -67,8 +69,8 @@ fun CycleScreen(onBack: () -> Unit) { verticalArrangement = Arrangement.spacedBy(6.dp), ) { if (status == null) { - Text("Log your period to start", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("PulseLoop shows the day of your cycle and its phase from the dates you log, next to your sleep and recovery.", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(tr("Log your period to start"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("PulseLoop shows the day of your cycle and its phase from the dates you log, next to your sleep and recovery."), fontSize = 13.sp, color = PulseColors.textSecondary) } else { Text("Day ${status.cycleDay} · ${status.phase.label}", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(status.phase.note, fontSize = 13.sp, color = PulseColors.textSecondary) @@ -85,14 +87,14 @@ fun CycleScreen(onBack: () -> Unit) { val open = periods.firstOrNull()?.takeIf { it.endDay == null && status?.inPeriod == true } if (open != null) { Button(onClick = { scope.launch { db.periodDao().upsert(open.copy(endDay = today.toEpochDay())) } }, modifier = Modifier.fillMaxWidth()) { - Text("Period ended today") + Text(tr("Period ended today")) } } else { Button(onClick = { scope.launch { db.periodDao().upsert(PeriodEntity(startDay = today.toEpochDay())) } }, modifier = Modifier.fillMaxWidth()) { - Text("Period started today") + Text(tr("Period started today")) } } - OutlinedButton(onClick = { picking = "start" }, modifier = Modifier.fillMaxWidth()) { Text("Log a past period") } + OutlinedButton(onClick = { picking = "start" }, modifier = Modifier.fillMaxWidth()) { Text(tr("Log a past period")) } if (periods.isNotEmpty()) { Text("HISTORY", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) @@ -112,13 +114,13 @@ fun CycleScreen(onBack: () -> Unit) { next?.let { Text("Cycle of ${it - p.startDay} days", fontSize = 12.sp, color = PulseColors.textMuted) } } IconButton(onClick = { scope.launch { db.periodDao().delete(p.id) } }) { - Icon(Icons.Filled.Delete, "Delete", tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) + Icon(Icons.Filled.Delete, tr("Delete"), tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) } } } } Text( - "Phases come only from the dates you log. PulseLoop doesn't predict fertile days, and this isn't contraception or a medical tool.", + tr("Phases come only from the dates you log. PulseLoop doesn't predict fertile days, and this isn't contraception or a medical tool."), fontSize = 11.sp, color = PulseColors.textMuted, ) Spacer(Modifier.height(24.dp)) @@ -141,11 +143,11 @@ fun CycleScreen(onBack: () -> Unit) { picking = null; pastStart = null } } - }) { Text(if (picking == "start") "Next: end date" else "Save") } + }) { Text(if (picking == "start") tr("Next: end date") else tr("Save")) } }, - dismissButton = { TextButton(onClick = { picking = null; pastStart = null }) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = { picking = null; pastStart = null }) { Text(tr("Cancel")) } }, ) { - Text(if (picking == "start") "When did it start?" else "When did it end?", modifier = Modifier.padding(start = 24.dp, top = 16.dp), fontSize = 16.sp, fontWeight = FontWeight.SemiBold) + Text(if (picking == "start") tr("When did it start?") else tr("When did it end?"), modifier = Modifier.padding(start = 24.dp, top = 16.dp), fontSize = 16.sp, fontWeight = FontWeight.SemiBold) DatePicker(state = state, showModeToggle = false) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt index c6b44e98..0c38a623 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.components.switchRow import androidx.compose.foundation.layout.* @@ -54,10 +56,10 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { contentWindowInsets = WindowInsets(0, 0, 0, 0), topBar = { TopAppBar( - title = { Text("Debug") }, + title = { Text(tr("Debug")) }, navigationIcon = { IconButton(onClick = onBack) { - Icon(Icons.Filled.ArrowBack, contentDescription = "Back") + Icon(Icons.Filled.ArrowBack, contentDescription = tr("Back")) } }, windowInsets = WindowInsets(0, 0, 0, 0), @@ -67,9 +69,9 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { LazyColumn(Modifier.fillMaxSize().padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { // ── Ring Event Log ────────────────────────────────────────── item { - DebugCard("Ring Events", trailing = "${events.size} recent") { + DebugCard(tr("Ring Events"), trailing = "${events.size} recent") { Text( - "Connection, command and reply events, stored as they happen. Times are local.", + tr("Connection, command and reply events, stored as they happen. Times are local."), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 4.dp), @@ -80,28 +82,28 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { onClick = { viewModel.sync(connect = false) }, contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp), ) { - Text("Sync Now", style = MaterialTheme.typography.labelSmall) + Text(tr("Sync Now"), style = MaterialTheme.typography.labelSmall) } OutlinedButton( enabled = !busy, onClick = { viewModel.sync(connect = true) }, contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp), ) { - Text("Connect + Query", style = MaterialTheme.typography.labelSmall) + Text(tr("Connect + Query"), style = MaterialTheme.typography.labelSmall) } } if (status.isNotBlank()) { Text(status, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } if (events.isEmpty()) { - Text("No events yet. Sync the ring or trigger a measurement to see data.", + Text(tr("No events yet. Sync the ring or trigger a measurement to see data."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp)) } else { events.take(if (showAllEvents) 40 else 5).forEach { EventRow(it, timeFmt) } TextButton(onClick = { showAllEvents = !showAllEvents }) { - Text(if (showAllEvents) "Show fewer events" else "Show more events") + Text(if (showAllEvents) tr("Show fewer events") else tr("Show more events")) } } } @@ -109,12 +111,12 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { // ── Raw Packets ───────────────────────────────────────────── item { - DebugCard("Raw Packets") { + DebugCard(tr("Raw Packets")) { Text("$packetCount packets captured", style = MaterialTheme.typography.bodyMedium) Text("↓ = ring → app (response) ↑ = app → ring (command)", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) TextButton(onClick = { showPackets = !showPackets }) { - Text(if (showPackets) "Hide packets" else "Show recent packets") + Text(if (showPackets) tr("Hide packets") else tr("Show recent packets")) } if (showPackets) packets.forEach { PacketRow(it, timeFmt) } } @@ -122,9 +124,9 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { // ── Database ──────────────────────────────────────────────── item { - DebugCard("Database") { - Text("Row counts include demo and real rows. Tap a table to see its newest rows. " + - "Stored health rows are never included in a diagnostics export.", + DebugCard(tr("Database")) { + Text(tr("Row counts include demo and real rows. Tap a table to see its newest rows. " + + "Stored health rows are never included in a diagnostics export."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) counts.forEach { count -> Row( @@ -143,11 +145,11 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { } if (expandedTable == count.name) { when (count.name) { - "raw_packets" -> Text("See Raw Packets above.", style = MaterialTheme.typography.bodySmall) - "wearable_logs" -> Text("See Ring Events above.", style = MaterialTheme.typography.bodySmall) + "raw_packets" -> Text(tr("See Raw Packets above."), style = MaterialTheme.typography.bodySmall) + "wearable_logs" -> Text(tr("See Ring Events above."), style = MaterialTheme.typography.bodySmall) else -> { val selected = rows.filter { it.tableName == count.name } - if (selected.isEmpty()) Text("No rows to display.", style = MaterialTheme.typography.bodySmall) + if (selected.isEmpty()) Text(tr("No rows to display."), style = MaterialTheme.typography.bodySmall) selected.forEach { row -> Text("${timeFmt.format(Date(row.timestamp))} · ${row.detail}", style = MaterialTheme.typography.bodySmall) @@ -165,17 +167,17 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { // explicitly opts out for this export. Never persists "off". var maskSensitive by remember { mutableStateOf(true) } var exportError by remember { mutableStateOf(null) } - DebugCard("Diagnostics") { - Text("Export app, device, and wearable logs as JSON.", + DebugCard(tr("Diagnostics")) { + Text(tr("Export app, device, and wearable logs as JSON."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) Row(Modifier.switchRow(checked = maskSensitive, onCheckedChange = { maskSensitive = it }), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Mask sensitive data", style = MaterialTheme.typography.bodyMedium) + Text(tr("Mask sensitive data"), style = MaterialTheme.typography.bodyMedium) Text( if (maskSensitive) - "Removes health values, ring serial & MAC addresses. Keeps models, opcodes & errors." + tr("Removes health values, ring serial & MAC addresses. Keeps models, opcodes & errors.") else - "OFF — includes full unmasked BLE frames (for protocol debugging only).", + tr("OFF — includes full unmasked BLE frames (for protocol debugging only)."), style = MaterialTheme.typography.bodySmall, color = if (maskSensitive) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.error, @@ -193,7 +195,7 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { } catch (e: CancellationException) { throw e } catch (_: Exception) { - exportError = "Could not export diagnostics." + exportError = tr("Could not export diagnostics.") } } }, @@ -201,7 +203,7 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { ) { Icon(Icons.Filled.Share, null) Spacer(Modifier.width(8.dp)) - Text(if (maskSensitive) "Export Diagnostics" else "Export Full (Unmasked)") + Text(if (maskSensitive) tr("Export Diagnostics") else tr("Export Full (Unmasked)")) } exportError?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) } } @@ -209,9 +211,9 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { // ── App Info ──────────────────────────────────────────────── item { - DebugCard("App Info") { + DebugCard(tr("App Info")) { Text("PulseLoop ${BuildConfig.VERSION_NAME} (Android)", style = MaterialTheme.typography.bodyMedium) - Text("Port from iOS · Open Source", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Port from iOS · Open Source"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt index a33642a8..248fed6c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -94,14 +96,14 @@ private fun std(v: Double) = DrinkInsights.fmt(v) /** Short names for the one-tap buttons; the full label is on the "More" sheet. */ private val DrinkType.short: String get() = when (this) { - DrinkType.BEER -> "Beer" - DrinkType.BEER_600 -> "600 ml" - DrinkType.DRAFT -> "Chopp" - DrinkType.WINE -> "Wine" - DrinkType.SPIRIT -> "Shot" - DrinkType.CAIPIRINHA -> "Caipirinha" - DrinkType.COCKTAIL -> "Cocktail" - DrinkType.OTHER -> "Other" + DrinkType.BEER -> tr("Beer") + DrinkType.BEER_600 -> tr("600 ml") + DrinkType.DRAFT -> tr("Chopp") + DrinkType.WINE -> tr("Wine") + DrinkType.SPIRIT -> tr("Shot") + DrinkType.CAIPIRINHA -> tr("Caipirinha") + DrinkType.COCKTAIL -> tr("Cocktail") + DrinkType.OTHER -> tr("Other") } private val DrinkType.icon: ImageVector @@ -217,11 +219,11 @@ fun DrinksScreen(onBack: () -> Unit, onBreathe: () -> Unit, onCoach: ((String) - Column(Modifier.fillMaxSize().background(PulseColors.background)) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { - IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } - Text("Drinks", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } + Text(tr("Drinks"), modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) if (enabled) { IconButton(onClick = { settingsOpen = true }, modifier = Modifier.align(Alignment.CenterEnd)) { - Icon(Icons.Filled.Settings, "Drinks settings", tint = PulseColors.textSecondary) + Icon(Icons.Filled.Settings, tr("Drinks settings"), tint = PulseColors.textSecondary) } } } @@ -232,10 +234,10 @@ fun DrinksScreen(onBack: () -> Unit, onBreathe: () -> Unit, onCoach: ((String) - if (!enabled) { DrinksWelcome { enabled = true } } else { - Segments(listOf("This week", "Trends", "Support"), tab) { tab = it } + Segments(listOf(tr("This week"), tr("Trends"), tr("Support")), tab) { tab = it } val s = snap if (s == null) { - Text("Reading your drinks…", color = PulseColors.textMuted, fontSize = 13.sp) + Text(tr("Reading your drinks…"), color = PulseColors.textMuted, fontSize = 13.sp) } else when (tab) { 0 -> { WeekHero(s) @@ -285,25 +287,25 @@ private fun DrinksWelcome(onStart: () -> Unit) { var showSize by remember { mutableStateOf(false) } Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { - Text("Drink less, sleep better", fontSize = 24.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Benefit(Icons.Filled.LocalBar, "Log a drink in one tap") - Benefit(Icons.Filled.EventAvailable, "A weekly limit and dry days you choose") - Benefit(Icons.Filled.Bedtime, "See what drinking does to your own nights") + Text(tr("Drink less, sleep better"), fontSize = 24.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Benefit(Icons.Filled.LocalBar, tr("Log a drink in one tap")) + Benefit(Icons.Filled.EventAvailable, tr("A weekly limit and dry days you choose")) + Benefit(Icons.Filled.Bedtime, tr("See what drinking does to your own nights")) } - DrinkCard("Set up · under a minute") { + DrinkCard(tr("Set up · under a minute")) { Stepper( - "A typical week now", "$typical", + tr("A typical week now"), "$typical", { typical = (typical - 1).coerceAtLeast(0); if (!limitTouched) limit = suggestedLimit(typical) }, { typical = (typical + 1).coerceAtMost(80); if (!limitTouched) limit = suggestedLimit(typical) }, - note = "In drinks, roughly", + note = tr("In drinks, roughly"), ) Stepper( - "Weekly limit", "$limit", + tr("Weekly limit"), "$limit", { limit = (limit - 1).coerceAtLeast(0); limitTouched = true }, { limit = (limit + 1).coerceAtMost(60); limitTouched = true }, - note = "We suggest a quarter less to start", + note = tr("We suggest a quarter less to start"), ) - Stepper("Dry days a week", "$dry", { dry = (dry - 1).coerceAtLeast(0) }, { dry = (dry + 1).coerceAtMost(7) }) + Stepper(tr("Dry days a week"), "$dry", { dry = (dry - 1).coerceAtLeast(0) }, { dry = (dry + 1).coerceAtMost(7) }) Row(Modifier.fillMaxWidth().clickable { showSize = !showSize }, verticalAlignment = Alignment.CenterVertically) { Text("Standard drink: ${grams.roundToInt()} g of alcohol", fontSize = 13.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) Icon(if (showSize) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, null, tint = PulseColors.textMuted) @@ -326,9 +328,9 @@ private fun DrinksWelcome(onStart: () -> Unit) { onStart() }, modifier = Modifier.fillMaxWidth().height(48.dp), - ) { Text("Start tracking") } + ) { Text(tr("Start tracking")) } Text( - "Private to this phone. If you drink most days, cut down gradually and talk to a doctor: stopping suddenly can be dangerous.", + tr("Private to this phone. If you drink most days, cut down gradually and talk to a doctor: stopping suddenly can be dangerous."), fontSize = 12.sp, color = PulseColors.textMuted, ) } @@ -412,7 +414,7 @@ private fun WeekStrip(s: DrinksRepository.Snapshot) { ) { when { drank -> Text(std(DrinkInsights.standardDrinks(grams, s.gramsPerStandard)), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = PulseColors.onAccent) - !future && known && !isToday -> Icon(Icons.Filled.Check, "Dry", tint = PulseColors.accent, modifier = Modifier.size(16.dp)) + !future && known && !isToday -> Icon(Icons.Filled.Check, tr("Dry"), tint = PulseColors.accent, modifier = Modifier.size(16.dp)) } } } @@ -431,9 +433,9 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang var lastLogged by remember { mutableStateOf>?>(null) } var toDelete by remember { mutableStateOf(null) } - DrinkCard("Log a drink", action = { + DrinkCard(tr("Log a drink"), action = { Text( - "More", + tr("More"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, modifier = Modifier.clickable { more = true }.padding(4.dp), ) @@ -465,7 +467,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang Row(verticalAlignment = Alignment.CenterVertically) { Text("Logged $text", fontSize = 13.sp, color = PulseColors.accent, modifier = Modifier.weight(1f)) Text( - "Undo", + tr("Undo"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, modifier = Modifier.clickable { scope.launch { ids.forEach { DrinksRepository.delete(db, it) }; lastLogged = null; onChange() } @@ -483,7 +485,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) if (s.recent.isNotEmpty()) { - Text(if (showTonight) "Hide" else "See and edit recent drinks", fontSize = 12.sp, color = PulseColors.textMuted) + Text(if (showTonight) tr("Hide") else tr("See and edit recent drinks"), fontSize = 12.sp, color = PulseColors.textMuted) } } PlanChip(s) { planOpen = true } @@ -500,15 +502,15 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang toDelete?.let { e -> AlertDialog( onDismissRequest = { toDelete = null }, - title = { Text("Delete drink?") }, + title = { Text(tr("Delete drink?")) }, text = { Text("This ${DrinkType.of(e.type).label.lowercase()} will be removed from your log.") }, confirmButton = { TextButton(onClick = { toDelete = null scope.launch { DrinksRepository.delete(db, e); onChange() } - }) { Text("Delete", color = PulseColors.danger) } + }) { Text(tr("Delete"), color = PulseColors.danger) } }, - dismissButton = { TextButton(onClick = { toDelete = null }) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = { toDelete = null }) { Text(tr("Cancel")) } }, ) } @@ -544,8 +546,8 @@ private fun PlanChip(s: DrinksRepository.Snapshot, onClick: () -> Unit) { val planned = s.planToday val shape = RoundedCornerShape(16.dp) val label = when { - planned == null -> "Plan tonight" - planned == 0 -> "Plan: dry night" + planned == null -> tr("Plan tonight") + planned == 0 -> tr("Plan: dry night") else -> "Plan: $planned" } Text( @@ -563,12 +565,12 @@ private fun PlanChip(s: DrinksRepository.Snapshot, onClick: () -> Unit) { private fun PlanSheet(s: DrinksRepository.Snapshot, onDone: () -> Unit) { var plan by remember { mutableIntStateOf(s.planToday ?: 2) } Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { - Text("Plan tonight", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("Pick the number before the first drink. It's easier to keep a number you chose beforehand.", fontSize = 13.sp, color = PulseColors.textSecondary) - Stepper("Drinks tonight", if (plan == 0) "none" else "$plan", { plan = (plan - 1).coerceAtLeast(0) }, { plan = (plan + 1).coerceAtMost(12) }) - Button(onClick = { DrinkPrefs.setPlan(s.today, plan); onDone() }, modifier = Modifier.fillMaxWidth()) { Text("Save plan") } + Text(tr("Plan tonight"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Pick the number before the first drink. It's easier to keep a number you chose beforehand."), fontSize = 13.sp, color = PulseColors.textSecondary) + Stepper(tr("Drinks tonight"), if (plan == 0) "none" else "$plan", { plan = (plan - 1).coerceAtLeast(0) }, { plan = (plan + 1).coerceAtMost(12) }) + Button(onClick = { DrinkPrefs.setPlan(s.today, plan); onDone() }, modifier = Modifier.fillMaxWidth()) { Text(tr("Save plan")) } if (s.planToday != null) { - TextButton(onClick = { DrinkPrefs.setPlan(s.today, null); onDone() }, modifier = Modifier.fillMaxWidth()) { Text("Clear plan") } + TextButton(onClick = { DrinkPrefs.setPlan(s.today, null); onDone() }, modifier = Modifier.fillMaxWidth()) { Text(tr("Clear plan")) } } } } @@ -582,7 +584,7 @@ private fun RecentDrinkRow(e: DrinkEntryEntity, gramsPerStd: Double, fmt: DateTi Text(DrinkType.of(e.type).label, fontSize = 14.sp, color = PulseColors.textPrimary) Text( "${Instant.ofEpochMilli(e.timestamp).atZone(zone).format(fmt)} · ${std(DrinkInsights.standardDrinks(e.grams, gramsPerStd))} drink" + - if (e.mealId != null) " · from food log" else "", + if (e.mealId != null) tr(" · from food log") else "", fontSize = 12.sp, color = PulseColors.textMuted, ) } @@ -598,12 +600,12 @@ private fun MoreDrinkSheet(onLog: (DrinkType, Int, Long, Double?) -> Unit) { var hoursAgo by remember { mutableLongStateOf(0L) } var price by remember { mutableStateOf(DrinkPrefs.pricePerDrink.takeIf { it > 0 }?.let { "%.2f".format(it) } ?: "") } Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { - Text("Log drinks", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Log drinks"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { DrinkType.entries.forEach { t -> Pill(t.label, type == t, PulseColors.drinks) { type = t } } } Text("${type.volumeMl.roundToInt()} ml at ${type.abvPct}% · about ${type.kcal.roundToInt()} kcal", fontSize = 12.sp, color = PulseColors.textMuted) - Stepper("How many", "$count", { count = (count - 1).coerceAtLeast(1) }, { count = (count + 1).coerceAtMost(12) }) + Stepper(tr("How many"), "$count", { count = (count - 1).coerceAtLeast(1) }, { count = (count + 1).coerceAtMost(12) }) FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { listOf(0L to "Now", 1L to "1 h ago", 3L to "3 h ago", 12L to "Last night").forEach { (h, l) -> Pill(l, hoursAgo == h, PulseColors.drinks) { hoursAgo = h } @@ -611,7 +613,7 @@ private fun MoreDrinkSheet(onLog: (DrinkType, Int, Long, Double?) -> Unit) { } OutlinedTextField( value = price, onValueChange = { price = it.filter { c -> c.isDigit() || c == '.' || c == ',' }.take(7) }, - label = { Text("Price each (optional)") }, + label = { Text(tr("Price each (optional)")) }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), singleLine = true, modifier = Modifier.fillMaxWidth(), ) @@ -632,8 +634,8 @@ private fun InsightCard(s: DrinksRepository.Snapshot) { ?: d.heavier?.hrvPct?.let { "After 3 or more drinks, your HRV runs ${kotlin.math.abs(it)}% ${if (it < 0) "lower" else "higher"} than on dry nights." } ?: d.light?.hrvPct?.let { "After 1–2 drinks, your HRV runs ${kotlin.math.abs(it)}% ${if (it < 0) "lower" else "higher"} than on dry nights." } ?: if (learning) "Learning your dry nights: ${d.dryNights} of ${DrinkInsights.MIN_NIGHTS}. Then PulseLoop shows what each drink does to your sleep." - else "Log a few evenings with drinks and PulseLoop will compare those nights with your dry ones." - DrinkCard("Your nights") { + else tr("Log a few evenings with drinks and PulseLoop will compare those nights with your dry ones.") + DrinkCard(tr("Your nights")) { Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(12.dp)) { Icon(Icons.Filled.Bedtime, null, tint = PulseColors.sleep, modifier = Modifier.size(20.dp)) Text(headline, fontSize = 14.sp, color = PulseColors.textPrimary, modifier = Modifier.weight(1f)) @@ -642,12 +644,12 @@ private fun InsightCard(s: DrinksRepository.Snapshot) { Bar(d.dryNights.toFloat() / DrinkInsights.MIN_NIGHTS, PulseColors.sleep) } else { Row(Modifier.fillMaxWidth().clickable { open = !open }, verticalAlignment = Alignment.CenterVertically) { - Text(if (open) "Less" else "Details", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, modifier = Modifier.weight(1f)) + Text(if (open) tr("Less") else tr("Details"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, modifier = Modifier.weight(1f)) Icon(if (open) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, null, tint = PulseColors.accent) } if (open) { - ImpactRow("After 1–2 drinks", d.light) - ImpactRow("After 3 or more", d.heavier) + ImpactRow(tr("After 1–2 drinks"), d.light) + ImpactRow(tr("After 3 or more"), d.heavier) s.recoveryNights?.let { Text("HRV usually takes ${"%.1f".format(it)} night${if (it > 1.05) "s" else ""} to come back.", fontSize = 13.sp, color = PulseColors.textSecondary) } @@ -661,11 +663,11 @@ private fun InsightCard(s: DrinksRepository.Snapshot) { private fun ImpactRow(label: String, i: DrinkInsights.Impact?) { Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { Text(label, fontSize = 13.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) - val text = if (i == null) "Not enough nights yet" else buildList { + val text = if (i == null) tr("Not enough nights yet") else buildList { i.hrvPct?.let { add("HRV ${if (it >= 0) "+" else "−"}${kotlin.math.abs(it)}%") } i.restingHr?.let { add("resting HR ${if (it >= 0) "+" else "−"}${kotlin.math.abs(it)}") } i.asleepMinutes?.let { add("sleep ${if (it >= 0) "+" else "−"}${kotlin.math.abs(it)} min") } - }.joinToString(" · ").ifEmpty { "No clear difference" } + " · ${i.nights} nights" + }.joinToString(" · ").ifEmpty { tr("No clear difference") } + " · ${i.nights} nights" Text(text, fontSize = 12.sp, color = PulseColors.textSecondary) } } @@ -693,7 +695,7 @@ private fun TrendsTab(s: DrinksRepository.Snapshot) { Stat("${s.streaks.best}", "best dry streak", Modifier.weight(1f).fillMaxHeight()) Stat("${s.streaks.current}", "dry days now", Modifier.weight(1f).fillMaxHeight()) } - DrinkCard("Last 8 weeks") { + DrinkCard(tr("Last 8 weeks")) { WeeksChart(s) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { Box(Modifier.width(16.dp).height(2.dp).background(PulseColors.textMuted)) @@ -701,7 +703,7 @@ private fun TrendsTab(s: DrinksRepository.Snapshot) { } } s.savings?.takeIf { it.drinksAvoided >= 0.5 }?.let { sv -> - DrinkCard("Compared with your typical week") { + DrinkCard(tr("Compared with your typical week")) { Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(8.dp)) { Stat(std(sv.drinksAvoided), "fewer drinks", Modifier.weight(1f).fillMaxHeight()) sv.money?.let { Stat("%.0f".format(it), "saved", Modifier.weight(1f).fillMaxHeight()) } @@ -710,7 +712,7 @@ private fun TrendsTab(s: DrinksRepository.Snapshot) { } } ?: run { if (DrinkPrefs.baselinePerWeek <= 0) { - Text("Set your typical week in settings to see drinks, money and calories saved.", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("Set your typical week in settings to see drinks, money and calories saved."), fontSize = 12.sp, color = PulseColors.textMuted) } } } @@ -769,20 +771,20 @@ private fun SupportRow(icon: ImageVector, title: String, subtitle: String, onCli @Composable private fun SupportTab(s: DrinksRepository.Snapshot, onBreathe: () -> Unit, onCoach: ((String) -> Unit)?, onAuditDone: () -> Unit) { - DrinkCard("When you want a drink") { - SupportRow(Icons.Filled.Air, "Ride it out", "3 minutes of slow breathing. An urge usually passes within 20 minutes.", onBreathe) + DrinkCard(tr("When you want a drink")) { + SupportRow(Icons.Filled.Air, tr("Ride it out"), tr("3 minutes of slow breathing. An urge usually passes within 20 minutes."), onBreathe) if (onCoach != null) { - SupportRow(Icons.Filled.AutoAwesome, "Talk it through", "Plan the next few days with the coach.") { + SupportRow(Icons.Filled.AutoAwesome, tr("Talk it through"), tr("Plan the next few days with the coach.")) { onCoach("I'd like help with my drinking. This week I'm at ${std(s.week.standardDrinks)} of my ${std(s.weeklyLimit)}-drink limit, with ${s.week.dryDays} dry days. Can you help me plan the next few days?") } } } AuditCard(s, onAuditDone) - DrinkCard("Support in Brazil") { - SupportRow(Icons.Filled.Phone, "CVV · 188", "Free emotional support, any time, by phone or chat.", null) - SupportRow(Icons.Filled.LocalHospital, "CAPS AD", "Free public care for alcohol use. Ask at your local health unit.", null) - SupportRow(Icons.Filled.EventAvailable, "Alcoólicos Anônimos", "Meetings across the country: aa.org.br", null) - Text("Anywhere: your doctor. If you drink most days, don't stop all at once; a doctor can help you cut down safely.", fontSize = 12.sp, color = PulseColors.textMuted) + DrinkCard(tr("Support in Brazil")) { + SupportRow(Icons.Filled.Phone, tr("CVV · 188"), tr("Free emotional support, any time, by phone or chat."), null) + SupportRow(Icons.Filled.LocalHospital, tr("CAPS AD"), tr("Free public care for alcohol use. Ask at your local health unit."), null) + SupportRow(Icons.Filled.EventAvailable, tr("Alcoólicos Anônimos"), tr("Meetings across the country: aa.org.br"), null) + Text(tr("Anywhere: your doctor. If you drink most days, don't stop all at once; a doctor can help you cut down safely."), fontSize = 12.sp, color = PulseColors.textMuted) } } @@ -793,18 +795,18 @@ private fun AuditCard(s: DrinksRepository.Snapshot, onDone: () -> Unit) { var sex by remember { mutableStateOf(null) } LaunchedEffect(Unit) { sex = runCatching { PulseLoopDatabase.getInstance(context).userProfileDao().get()?.sex }.getOrNull() } val score = DrinkPrefs.auditScore - DrinkCard("3-question check") { + DrinkCard(tr("3-question check")) { if (score != null) { val level = AuditC.level(score, sex) Text(level.label, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = if (level == AuditC.Level.LOW) PulseColors.accent else PulseColors.warning) Text(AuditC.advice(level), fontSize = 13.sp, color = PulseColors.textSecondary) Text("Score $score of 12 · ${DrinkPrefs.auditDate}", fontSize = 11.sp, color = PulseColors.textMuted) } else { - Text("The WHO's short alcohol check (AUDIT-C). Three questions, under a minute. A screen, not a diagnosis.", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(tr("The WHO's short alcohol check (AUDIT-C). Three questions, under a minute. A screen, not a diagnosis."), fontSize = 13.sp, color = PulseColors.textSecondary) } if (s.auditDue) { OutlinedButton(onClick = { taking = true }, modifier = Modifier.fillMaxWidth()) { - Text(if (score == null) "Take the check" else "Retake (every 3 months)") + Text(if (score == null) tr("Take the check") else tr("Retake (every 3 months)")) } } } @@ -812,7 +814,7 @@ private fun AuditCard(s: DrinksRepository.Snapshot, onDone: () -> Unit) { val answers = remember { mutableStateListOf(-1, -1, -1) } AlertDialog( onDismissRequest = { taking = false }, - title = { Text("3-question check") }, + title = { Text(tr("3-question check")) }, text = { Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp)) { AuditC.QUESTIONS.forEachIndexed { qi, (q, options) -> @@ -838,9 +840,9 @@ private fun AuditCard(s: DrinksRepository.Snapshot, onDone: () -> Unit) { DrinkPrefs.setAudit(LocalDate.now(), AuditC.score(answers)) taking = false onDone() - }) { Text("See result") } + }) { Text(tr("See result")) } }, - dismissButton = { TextButton(onClick = { taking = false }) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = { taking = false }) { Text(tr("Cancel")) } }, ) } } @@ -860,15 +862,15 @@ private fun DrinkSettings(onChange: () -> Unit, onTurnedOff: () -> Unit) { Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp).padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Text("Drinks settings", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Stepper("Weekly limit", "$limit", { limit = (limit - 1).coerceAtLeast(0); DrinkPrefs.weeklyLimit = limit.toDouble(); onChange() }, + Text(tr("Drinks settings"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Stepper(tr("Weekly limit"), "$limit", { limit = (limit - 1).coerceAtLeast(0); DrinkPrefs.weeklyLimit = limit.toDouble(); onChange() }, { limit = (limit + 1).coerceAtMost(60); DrinkPrefs.weeklyLimit = limit.toDouble(); onChange() }) - Stepper("Dry days a week", "$dry", { dry = (dry - 1).coerceAtLeast(0); DrinkPrefs.dryDaysTarget = dry; onChange() }, + Stepper(tr("Dry days a week"), "$dry", { dry = (dry - 1).coerceAtLeast(0); DrinkPrefs.dryDaysTarget = dry; onChange() }, { dry = (dry + 1).coerceAtMost(7); DrinkPrefs.dryDaysTarget = dry; onChange() }) - Stepper("Typical week before", "$typical", { typical = (typical - 1).coerceAtLeast(0); DrinkPrefs.baselinePerWeek = typical.toDouble(); onChange() }, + Stepper(tr("Typical week before"), "$typical", { typical = (typical - 1).coerceAtLeast(0); DrinkPrefs.baselinePerWeek = typical.toDouble(); onChange() }, { typical = (typical + 1).coerceAtMost(80); DrinkPrefs.baselinePerWeek = typical.toDouble(); onChange() }, - note = "For drinks, money and calories saved") - Text("Standard drink", fontSize = 14.sp, color = PulseColors.textPrimary) + note = tr("For drinks, money and calories saved")) + Text(tr("Standard drink"), fontSize = 14.sp, color = PulseColors.textPrimary) FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { listOf(10.0 to "10 g (WHO)", 8.0 to "8 g (UK)", 14.0 to "14 g (US)").forEach { (g, l) -> Pill(l, grams == g, PulseColors.drinks) { grams = g; DrinkPrefs.gramsPerStandard = g; onChange() } @@ -881,23 +883,23 @@ private fun DrinkSettings(onChange: () -> Unit, onTurnedOff: () -> Unit) { DrinkPrefs.pricePerDrink = price.replace(',', '.').toDoubleOrNull() ?: 0.0 onChange() }, - label = { Text("Usual price of a drink (optional)") }, + label = { Text(tr("Usual price of a drink (optional)")) }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), singleLine = true, modifier = Modifier.fillMaxWidth(), ) - Text("Your drinks stay on this phone. They aren't sent to Health Connect or included in diagnostics.", fontSize = 11.sp, color = PulseColors.textMuted) + Text(tr("Your drinks stay on this phone. They aren't sent to Health Connect or included in diagnostics."), fontSize = 11.sp, color = PulseColors.textMuted) TextButton(onClick = { confirmOff = true }) { Icon(Icons.Filled.Close, null, tint = PulseColors.danger, modifier = Modifier.size(16.dp)) Spacer(Modifier.width(6.dp)) - Text("Turn off Drinks", color = PulseColors.danger) + Text(tr("Turn off Drinks"), color = PulseColors.danger) } } if (confirmOff) AlertDialog( onDismissRequest = { confirmOff = false }, - title = { Text("Turn off Drinks?") }, - text = { Text("The tile and the morning-after line disappear. Your logged drinks stay on this phone until you delete them or clear your data.") }, - confirmButton = { TextButton(onClick = { DrinkPrefs.setEnabled(false); confirmOff = false; onTurnedOff() }) { Text("Turn off") } }, - dismissButton = { TextButton(onClick = { confirmOff = false }) { Text("Keep") } }, + title = { Text(tr("Turn off Drinks?")) }, + text = { Text(tr("The tile and the morning-after line disappear. Your logged drinks stay on this phone until you delete them or clear your data.")) }, + confirmButton = { TextButton(onClick = { DrinkPrefs.setEnabled(false); confirmOff = false; onTurnedOff() }) { Text(tr("Turn off")) } }, + dismissButton = { TextButton(onClick = { confirmOff = false }) { Text(tr("Keep")) } }, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt b/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt index 14804354..a130a4f1 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import android.content.Context import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -87,7 +89,7 @@ fun FoodCard( Text("FOOD", fontSize = 12.sp, letterSpacing = 1.8.sp, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) if (!f.enabled) { Text( - "Hide", fontSize = 12.sp, color = PulseColors.textMuted, + tr("Hide"), fontSize = 12.sp, color = PulseColors.textMuted, modifier = Modifier.clickable(role = Role.Button) { hidden = true hiddenPrefs(context).edit().putBoolean("hidden", true).apply() @@ -112,15 +114,15 @@ fun FoodCard( } } else { Text( - "Log meals to see food next to the calories you burn, and to link late meals and drinks to your sleep.", + tr("Log meals to see food next to the calories you burn, and to link late meals and drinks to your sleep."), fontSize = 13.sp, color = PulseColors.textSecondary, ) } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - FoodAction("Photo", Icons.Filled.CameraAlt, Modifier.weight(1f)) { onLog("photo") } - FoodAction("Barcode", Icons.Filled.QrCodeScanner, Modifier.weight(1f)) { onLog("barcode") } - FoodAction("Add", Icons.Filled.Add, Modifier.weight(1f)) { onLog("add") } + FoodAction(tr("Photo"), Icons.Filled.CameraAlt, Modifier.weight(1f)) { onLog("photo") } + FoodAction(tr("Barcode"), Icons.Filled.QrCodeScanner, Modifier.weight(1f)) { onLog("barcode") } + FoodAction(tr("Add"), Icons.Filled.Add, Modifier.weight(1f)) { onLog("add") } } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt b/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt index 0a2c6fdf..76f40f85 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import androidx.compose.foundation.background import androidx.compose.foundation.layout.* @@ -50,12 +52,12 @@ fun UnusualSignalsCard(signals: List) { .dither(PulseColors.warning, 0.12f).padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { - Text("Some signals look unusual", fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.warning) + Text(tr("Some signals look unusual"), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.warning) signals.forEach { Text("${it.title}: ${it.detail}", fontSize = 13.sp, color = PulseColors.textPrimary) } Text( - "Compared with your own recent nights. This can follow illness, stress, alcohol or a hard day. It isn't a diagnosis; consider an easier day.", + tr("Compared with your own recent nights. This can follow illness, stress, alcohol or a hard day. It isn't a diagnosis; consider an easier day."), fontSize = 12.sp, color = PulseColors.textSecondary, ) } @@ -80,9 +82,9 @@ fun TonightCard(g: BedtimeGuidance.Result, sleepGoalMinutes: Int) { ) } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text("LAST CAFFEINE", fontSize = 11.sp, fontWeight = FontWeight.Medium, color = PulseColors.calories) + Text(tr("LAST CAFFEINE"), fontSize = 11.sp, fontWeight = FontWeight.Medium, color = PulseColors.calories) Text(BedtimeGuidance.fmt(g.caffeineCutoff), fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text("8 hours before bed", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("8 hours before bed"), fontSize = 12.sp, color = PulseColors.textMuted) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt b/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt index a62619f4..45bd7d3f 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.activity.compose.rememberLauncherForActivityResult import androidx.compose.foundation.background import androidx.compose.foundation.clickable @@ -48,7 +50,7 @@ import java.time.format.DateTimeFormatter /** Settings → Health Connect as your data source (docs/health-connect-source.md). */ @Composable fun HealthConnectSourceScreen(onBack: () -> Unit) { - SettingsSubScreen(title = "Use without a ring", onBack = onBack) { + SettingsSubScreen(title = tr("Use without a ring"), onBack = onBack) { HealthConnectSourceContent() } } @@ -80,8 +82,8 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { scope.launch { when (val r = runCatching { ReferenceSourceScanner.scan(context) }.getOrNull()) { is ReferenceSourceScanner.Result.Done -> scan = r - ReferenceSourceScanner.Result.Unavailable -> note = "Health Connect isn't available on this phone." - null -> note = "Couldn't read Health Connect. Try again in a moment." + ReferenceSourceScanner.Result.Unavailable -> note = tr("Health Connect isn't available on this phone.") + null -> note = tr("Couldn't read Health Connect. Try again in a moment.") } scanning = false } @@ -94,9 +96,9 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { note = when (val r = runCatching { HealthConnectSourceImporter.run(context) }.getOrNull()) { is HealthConnectSourceImporter.Outcome.Done -> "Imported ${"%,d".format(r.stored)} readings." is HealthConnectSourceImporter.Outcome.Failed -> r.message - HealthConnectSourceImporter.Outcome.NoPermission -> "PulseLoop isn't allowed to read Health Connect any more." - HealthConnectSourceImporter.Outcome.Unavailable -> "Health Connect isn't available on this phone." - else -> "The import failed. Try again in a moment." + HealthConnectSourceImporter.Outcome.NoPermission -> tr("PulseLoop isn't allowed to read Health Connect any more.") + HealthConnectSourceImporter.Outcome.Unavailable -> tr("Health Connect isn't available on this phone.") + else -> tr("The import failed. Try again in a moment.") } importing = false refresh++ @@ -111,7 +113,7 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { val launcher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { got -> granted = got if (got.none { it in HealthConnectSource.readPermissions }) { - note = "No access granted. You can allow it in Health Connect's settings." + note = tr("No access granted. You can allow it in Health Connect's settings.") } else if (!enabled) doScan() } val canRead = granted.any { it in HealthConnectSource.readPermissions } @@ -119,26 +121,26 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { AccuracyCard { - Text("Use the device you already wear", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Use the device you already wear"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( - "No PulseLoop ring? If your Oura, Galaxy Ring, Fitbit or watch app writes to Health Connect, PulseLoop can " + + tr("No PulseLoop ring? If your Oura, Galaxy Ring, Fitbit or watch app writes to Health Connect, PulseLoop can " + "read it from there: sleep, heart rate, HRV, blood oxygen, steps, calories, workouts and periods. " + - "Every screen, the coach and your insights then work from that data.", + "Every screen, the coach and your insights then work from that data."), fontSize = 13.sp, color = PulseColors.textSecondary, ) Text( - "PulseLoop reads only the app you choose, and doesn't write that data back to Health Connect.", + tr("PulseLoop reads only the app you choose, and doesn't write that data back to Health Connect."), fontSize = 12.sp, color = PulseColors.textMuted, ) if (!available) { - Text("Health Connect isn't available on this phone.", fontSize = 12.sp, color = PulseColors.danger) + Text(tr("Health Connect isn't available on this phone."), fontSize = 12.sp, color = PulseColors.danger) } else if (hasRing && !enabled) { Text( - "A ring is paired. Forget it in Settings → Wearable first: the two would count the same steps and nights.", + tr("A ring is paired. Forget it in Settings → Wearable first: the two would count the same steps and nights."), fontSize = 12.sp, color = PulseColors.warning, ) } else if (!canRead) { - Button(onClick = { launcher.launch(HealthConnectSource.request) }) { Text("Allow access") } + Button(onClick = { launcher.launch(HealthConnectSource.request) }) { Text(tr("Allow access")) } } } @@ -152,21 +154,21 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { last?.let { "Last import " + DateTimeFormatter.ofPattern("EEE d MMM, HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault())) + " · ${"%,d".format(count)} readings" - } ?: "Not imported yet", + } ?: tr("Not imported yet"), fontSize = 13.sp, color = PulseColors.textSecondary, ) Text( - "PulseLoop checks for new data every hour and whenever you open the app. A night usually appears once " + + tr("PulseLoop checks for new data every hour and whenever you open the app. A night usually appears once ") + "${HealthConnectSource.label(context, pkg)} has synced it in the morning.", fontSize = 12.sp, color = PulseColors.textMuted, ) if (canRead && !HealthConnectSource.canReadInBackground(granted)) { - Text("Allow background access so imports also run while PulseLoop is closed.", fontSize = 12.sp, color = PulseColors.warning) + Text(tr("Allow background access so imports also run while PulseLoop is closed."), fontSize = 12.sp, color = PulseColors.warning) } Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { - Button(onClick = { importNow() }, enabled = !importing && canRead) { Text("Import now") } + Button(onClick = { importNow() }, enabled = !importing && canRead) { Text(tr("Import now")) } if (missing.isNotEmpty()) { - OutlinedButton(onClick = { launcher.launch(HealthConnectSource.request) }) { Text("Allow more") } + OutlinedButton(onClick = { launcher.launch(HealthConnectSource.request) }) { Text(tr("Allow more")) } } if (importing) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) } @@ -174,14 +176,14 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { HealthConnectSource.disable(context) enabled = false doScan() - }) { Text("Stop using Health Connect", color = PulseColors.danger) } + }) { Text(tr("Stop using Health Connect"), color = PulseColors.danger) } } } else if (canRead && !hasRing) { val r = scan if (scanning) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) - Text("Looking for apps writing to Health Connect…", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(tr("Looking for apps writing to Health Connect…"), fontSize = 13.sp, color = PulseColors.textSecondary) } } else if (r != null) { val usable = r.sources.filter { it.echo?.looksLikeEcho != true } @@ -189,10 +191,10 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { AccuracyCard { Text("No app wrote health data in the last ${ReferenceSourceScanner.LOOKBACK_DAYS} days.", fontSize = 13.sp, color = PulseColors.textSecondary) Text( - "In the Oura app: Settings → Health Connect, and turn on sharing. Then come back and look again.", + tr("In the Oura app: Settings → Health Connect, and turn on sharing. Then come back and look again."), fontSize = 12.sp, color = PulseColors.textMuted, ) - OutlinedButton(onClick = { doScan() }) { Text("Look again") } + OutlinedButton(onClick = { doScan() }) { Text(tr("Look again")) } } } usable.forEach { src -> @@ -226,11 +228,11 @@ fun HealthConnectSourceHeroCard(onOpen: () -> Unit) { .clickable(onClick = onOpen).padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Text("DATA SOURCE", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("DATA SOURCE"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) Text("${HealthConnectSource.label(context, pkg)} via Health Connect", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( last?.let { "Last import " + DateTimeFormatter.ofPattern("EEE HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault())) } - ?: "Waiting for the first import", + ?: tr("Waiting for the first import"), fontSize = 13.sp, color = PulseColors.textSecondary, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt index 04c119fa..d29383a4 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable @@ -67,7 +69,7 @@ fun JournalTagsCard( ) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Text( - if (allowYesterday && onYesterday) "Tag yesterday" else title, + if (allowYesterday && onYesterday) tr("Tag yesterday") else title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, modifier = Modifier.weight(1f), ) @@ -162,10 +164,10 @@ fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenDrinks: (() - Column(Modifier.fillMaxSize()) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.Filled.ArrowBack, "Back") + Icon(Icons.Filled.ArrowBack, tr("Back")) } Text( - "Journal", modifier = Modifier.align(Alignment.Center), + tr("Journal"), modifier = Modifier.align(Alignment.Center), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, ) } @@ -173,19 +175,19 @@ fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenDrinks: (() - Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(16.dp), ) { - JournalTagsCard(db, today, "Today") - JournalTagsCard(db, today.minusDays(1), "Yesterday") + JournalTagsCard(db, today, tr("Today")) + JournalTagsCard(db, today.minusDays(1), tr("Yesterday")) // The Alcohol tag is a yes/no; Drinks counts them, sets a limit and shows the dose. if (onOpenDrinks != null) { Text( - if (com.pulseloop.service.DrinkPrefs.enabled) "Open Drinks: this week, your plan and what drinking does to your nights" - else "Want to drink less? Track drinks, set a weekly limit and see what each drink does to your nights", + if (com.pulseloop.service.DrinkPrefs.enabled) tr("Open Drinks: this week, your plan and what drinking does to your nights") + else tr("Want to drink less? Track drinks, set a weekly limit and see what each drink does to your nights"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.drinks, modifier = Modifier.clickable(onClick = onOpenDrinks).padding(vertical = 4.dp), ) } - Text("What affects you", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textMuted) + Text(tr("What affects you"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textMuted) val list = effects when { list == null -> Unit @@ -212,7 +214,7 @@ fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenDrinks: (() - } } Text( - "These are patterns in your own data, not proof of cause and effect. Every tag is checked against your sleep, HRV and resting heart rate together, so a difference that could easily be chance isn't shown. They get more reliable the more days you tag.", + tr("These are patterns in your own data, not proof of cause and effect. Every tag is checked against your sleep, HRV and resting heart rate together, so a difference that could easily be chance isn't shown. They get more reliable the more days you tag."), fontSize = 12.sp, color = PulseColors.textMuted, ) Spacer(Modifier.height(24.dp)) diff --git a/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt new file mode 100644 index 00000000..af906fc7 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt @@ -0,0 +1,59 @@ +package com.pulseloop.ui.screens + +import android.app.Activity +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +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.foundation.shape.RoundedCornerShape +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.pulseloop.ui.i18n.AppLanguage +import com.pulseloop.ui.i18n.L10n +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.theme.PulseColors + +/** Settings → Language. Each option names itself in its own language, so anyone can find theirs. */ +@Composable +fun LanguageSettingsScreen(onBack: () -> Unit) { + val context = LocalContext.current + SettingsSubScreen(title = tr("Language"), onBack = onBack) { + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card), + ) { + AppLanguage.entries.forEach { lang -> + Row( + Modifier.fillMaxWidth().clickable { + if (lang != L10n.language) { + L10n.set(context, lang) + // Rebuild the Activity so dates, numbers and Android's own text follow too. + (context as? Activity)?.recreate() + } + }.padding(horizontal = 12.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = L10n.language == lang, onClick = null) + Text( + if (lang == AppLanguage.SYSTEM) tr("System default") else lang.label, + fontSize = 15.sp, color = PulseColors.textPrimary, + modifier = Modifier.padding(start = 12.dp), + ) + } + } + } + Text( + tr("The coach also replies in the language you choose."), + fontSize = 12.sp, color = PulseColors.textMuted, + ) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/LogPastActivityScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/LogPastActivityScreen.kt index 60bc9740..2927ce58 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/LogPastActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/LogPastActivityScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -69,22 +71,22 @@ fun LogPastActivityScreen(onBack: () -> Unit, onSaved: (String) -> Unit) { ) { item { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, "Back", tint = PulseColors.textSecondary, onTap = onBack) + CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, tr("Back"), tint = PulseColors.textSecondary, onTap = onBack) Spacer(Modifier.width(12.dp)) - Text("Log Past Activity", fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Log Past Activity"), fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) } } item { Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { - Text("What did you do?", fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("What did you do?"), fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( - "Choose an activity, when it started, and how long it lasted.", + tr("Choose an activity, when it started, and how long it lasted."), fontSize = 14.sp, color = PulseColors.textMuted, ) } } - item { SectionLabel("Activity type") } + item { SectionLabel(tr("Activity type")) } item { ActivityTypeGrid(selectedType) { type -> selectedType = type @@ -92,14 +94,14 @@ fun LogPastActivityScreen(onBack: () -> Unit, onSaved: (String) -> Unit) { } } - item { SectionLabel("When") } + item { SectionLabel(tr("When")) } item { - EditFieldRow("Started") { + EditFieldRow(tr("Started")) { DateTimeButton(startedAt) { startedAt = it; saveError = null } } } item { - EditFieldRow("Ends") { + EditFieldRow(tr("Ends")) { Text( formatDateTime(endedAt), fontSize = 14.sp, @@ -108,7 +110,7 @@ fun LogPastActivityScreen(onBack: () -> Unit, onSaved: (String) -> Unit) { } } - item { SectionLabel("Duration") } + item { SectionLabel(tr("Duration")) } item { PastActivityDurationCard(durationMinutes) { newValue -> durationMinutes = newValue @@ -117,7 +119,7 @@ fun LogPastActivityScreen(onBack: () -> Unit, onSaved: (String) -> Unit) { } if (!isValid) { - item { Text("The workout must finish before now.", fontSize = 12.sp, color = PulseColors.warning) } + item { Text(tr("The workout must finish before now."), fontSize = 12.sp, color = PulseColors.warning) } } saveError?.let { error -> item { Text(error, fontSize = 12.sp, color = PulseColors.danger) } @@ -151,7 +153,7 @@ fun LogPastActivityScreen(onBack: () -> Unit, onSaved: (String) -> Unit) { ) { Icon(Icons.Filled.Check, null) Spacer(Modifier.width(8.dp)) - Text("Log Activity", fontWeight = FontWeight.SemiBold) + Text(tr("Log Activity"), fontWeight = FontWeight.SemiBold) } } item { Spacer(Modifier.height(24.dp)) } @@ -232,12 +234,12 @@ private fun PastActivityDurationCard(minutes: Int, onChange: (Int) -> Unit) { verticalArrangement = Arrangement.spacedBy(16.dp), ) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - DurationStepButton(Icons.Filled.Remove, "Decrease duration by 5 minutes", enabled = !atFloor) { onChange(maxOf(5, minutes - 5)) } + DurationStepButton(Icons.Filled.Remove, tr("Decrease duration by 5 minutes"), enabled = !atFloor) { onChange(maxOf(5, minutes - 5)) } Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) { Text(durationText(minutes), fontSize = 28.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text("DURATION", fontSize = 11.sp, letterSpacing = 1.1.sp, color = PulseColors.textMuted) } - DurationStepButton(Icons.Filled.Add, "Increase duration by 5 minutes", enabled = true) { onChange(minutes + 5) } + DurationStepButton(Icons.Filled.Add, tr("Increase duration by 5 minutes"), enabled = true) { onChange(minutes + 5) } } Row(Modifier.fillMaxWidth().selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { listOf(15, 30, 45, 60, 90).forEach { value -> diff --git a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt index c57ce407..5806b5a5 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import android.content.Context import android.graphics.Bitmap @@ -282,13 +284,13 @@ fun MealAnalysisDialog( verticalAlignment = Alignment.CenterVertically, ) { Text( - "AI meal log", + tr("AI meal log"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, modifier = Modifier.weight(1f), ) - TextButton(onClick = onDismiss) { Text("Cancel") } + TextButton(onClick = onDismiss) { Text(tr("Cancel")) } } Column( Modifier @@ -329,7 +331,7 @@ fun MealAnalysisDialog( onClick = { image = null }, modifier = Modifier.align(Alignment.TopEnd), ) { - Icon(Icons.Filled.Close, "Remove photo", tint = Color.White) + Icon(Icons.Filled.Close, tr("Remove photo"), tint = Color.White) } } } else { @@ -337,7 +339,7 @@ fun MealAnalysisDialog( OutlinedButton(onClick = { launchCamera() }, modifier = Modifier.weight(1f)) { Icon(Icons.Filled.PhotoCamera, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - Text("Camera") + Text(tr("Camera")) } OutlinedButton( onClick = { @@ -349,14 +351,14 @@ fun MealAnalysisDialog( ) { Icon(Icons.Filled.PhotoLibrary, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - Text("Library") + Text(tr("Library")) } } } Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( - if (image == null) "OR DESCRIBE IT" else "ADD DETAIL (OPTIONAL)", + if (image == null) tr("OR DESCRIBE IT") else tr("ADD DETAIL (OPTIONAL)"), fontSize = 12.sp, letterSpacing = 1.4.sp, color = PulseColors.textMuted, @@ -364,7 +366,7 @@ fun MealAnalysisDialog( OutlinedTextField( value = describeText, onValueChange = { describeText = it }, - label = { Text(if (image == null) "Describe your meal" else "Meal details") }, + label = { Text(if (image == null) tr("Describe your meal") else tr("Meal details")) }, placeholder = { Text("e.g. two eggs, toast with butter, black coffee") }, modifier = Modifier.fillMaxWidth(), minLines = 2, @@ -379,12 +381,12 @@ fun MealAnalysisDialog( ) { Icon(Icons.Filled.AutoAwesome, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - Text("Analyze") + Text(tr("Analyze")) } // iOS disclaimer, verbatim (:145-148). Text( - "Sent to your configured AI provider only when you tap Analyze. Estimates are labeled and editable.", + tr("Sent to your configured AI provider only when you tap Analyze. Estimates are labeled and editable."), fontSize = 12.sp, color = PulseColors.textMuted, textAlign = TextAlign.Center, @@ -402,7 +404,7 @@ fun MealAnalysisDialog( ) } CircularProgressIndicator(color = PulseColors.accent, modifier = Modifier.size(28.dp)) - Text("Estimating nutrition…", fontSize = 14.sp, color = PulseColors.textSecondary) + Text(tr("Estimating nutrition…"), fontSize = 14.sp, color = PulseColors.textSecondary) } AnalysisPhase.Review -> { @@ -421,7 +423,7 @@ fun MealAnalysisDialog( Icon(Icons.Filled.AutoAwesome, null, tint = PulseColors.accent, modifier = Modifier.size(12.dp)) Spacer(Modifier.width(4.dp)) Text( - "AI estimate", + tr("AI estimate"), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, @@ -451,12 +453,12 @@ fun MealAnalysisDialog( ) } Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { - Text("Review & adjust", fontWeight = FontWeight.SemiBold, color = PulseColors.calories) + Text(tr("Review & adjust"), fontWeight = FontWeight.SemiBold, color = PulseColors.calories) // The name is text, full width, and may wrap: a dish name is often long. OutlinedTextField( value = name, onValueChange = { name = it }, - label = { Text("Meal name") }, + label = { Text(tr("Meal name")) }, modifier = Modifier.fillMaxWidth(), minLines = 1, maxLines = 3, @@ -466,11 +468,11 @@ fun MealAnalysisDialog( imeAction = ImeAction.Next, ), ) - NumberField("Calories", "kcal", calories, Modifier.fillMaxWidth()) { calories = it } + NumberField(tr("Calories"), "kcal", calories, Modifier.fillMaxWidth()) { calories = it } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - NumberField("Protein", "g", protein, Modifier.weight(1f)) { protein = it } - NumberField("Carbs", "g", carbs, Modifier.weight(1f)) { carbs = it } - NumberField("Fat", "g", fat, Modifier.weight(1f)) { fat = it } + NumberField(tr("Protein"), "g", protein, Modifier.weight(1f)) { protein = it } + NumberField(tr("Carbs"), "g", carbs, Modifier.weight(1f)) { carbs = it } + NumberField(tr("Fat"), "g", fat, Modifier.weight(1f)) { fat = it } } } val canSave = MealAnalysisLogic.canSave(name, calories) @@ -482,7 +484,7 @@ fun MealAnalysisDialog( ) { Icon(Icons.Filled.Check, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - Text("Log meal") + Text(tr("Log meal")) } TextButton( onClick = { phase = AnalysisPhase.Input }, @@ -490,7 +492,7 @@ fun MealAnalysisDialog( ) { Icon(Icons.Filled.Refresh, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Re-analyze", color = PulseColors.accent) + Text(tr("Re-analyze"), color = PulseColors.accent) } } @@ -515,7 +517,7 @@ fun MealAnalysisDialog( ) { Icon(Icons.Filled.Refresh, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Try again") + Text(tr("Try again")) } } } @@ -653,11 +655,11 @@ object MealAnalysisLogic { /** Verbatim system prompt (MealAnalysisSheet.swift:338-342). */ val systemPrompt: String = - "You are a nutrition estimator. Given a meal description and/or photo, " + + tr("You are a nutrition estimator. Given a meal description and/or photo, " + "identify the food and estimate total calories and macros for the portion shown or described. " + "Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. " + "Use confidence \"high\" only for clearly identifiable, standard portions. " + - "Return only JSON matching the schema." + "Return only JSON matching the schema.") /** * The verbatim strict meal_estimate json_schema (MealAnalysisSheet.swift:344-362), built @@ -667,12 +669,12 @@ object MealAnalysisLogic { fun described(value: String) = JsonObject(mapOf("type" to JsonPrimitive("string"), "description" to JsonPrimitive(value))) fun number() = JsonObject(mapOf("type" to JsonPrimitive("number"))) val props = JsonObject(mapOf( - "name" to described("Short display name for the meal"), + "name" to described(tr("Short display name for the meal")), "calories" to number(), "protein_g" to number(), "carbs_g" to number(), "fat_g" to number(), - "assumptions" to described("Portion/preparation assumptions, one short sentence, or empty string"), + "assumptions" to described(tr("Portion/preparation assumptions, one short sentence, or empty string")), "confidence" to JsonObject(mapOf( "type" to JsonPrimitive("string"), "enum" to JsonArray(listOf(JsonPrimitive("low"), JsonPrimitive("medium"), JsonPrimitive("high"))), @@ -721,8 +723,8 @@ object MealEstimator { val resolution = CoachClientResolver.resolve(providerStore, keyStore) if (!keyStore.coachEnabled || resolution.key == null) { return@withContext Result.Failure( - "AI analysis needs the coach enabled with a configured provider (Settings → AI Coach). " + - "You can still search the database or enter the meal manually.", + tr("AI analysis needs the coach enabled with a configured provider (Settings → AI Coach). " + + "You can still search the database or enter the meal manually."), ) } val model = CoachClientResolver.activeModel(providerStore.snapshot(), keyStore.model) @@ -737,12 +739,12 @@ object MealEstimator { CoachAttachmentStore.delete(appContext, ref) } if (images.isEmpty()) { - return@withContext Result.Failure("Couldn't process that photo. Try again or describe the meal.") + return@withContext Result.Failure(tr("Couldn't process that photo. Try again or describe the meal.")) } } // iOS :392 — the description, or the photo-only prompt. - val prompt = description.trim().ifEmpty { "Estimate the nutrition of the meal in the photo." } + val prompt = description.trim().ifEmpty { tr("Estimate the nutrition of the meal in the photo.") } val input = JsonArray(listOf( OpenAIRequestBuilder.message("system", MealAnalysisLogic.systemPrompt), OpenAIRequestBuilder.message("user", prompt, images), @@ -759,7 +761,7 @@ object MealEstimator { val response = resolution.client.send(requestBody.toString().toByteArray()) val estimate = MealAnalysisLogic.decode(response.outputText) ?: return@withContext Result.Failure( - "The AI didn't return a usable estimate. Try again or enter the meal manually.", + tr("The AI didn't return a usable estimate. Try again or enter the meal manually."), ) Result.Success(estimate) } catch (e: CancellationException) { diff --git a/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt index 128df720..651251f1 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable @@ -57,15 +59,15 @@ fun MedsScreen(onBack: () -> Unit) { Column(Modifier.fillMaxSize().background(PulseColors.background)) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { - IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } - Text("Medications & supplements", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } + Text(tr("Medications & supplements"), modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) } Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { if (meds.isEmpty()) { - Text("Add what you take on a schedule. PulseLoop asks once per dose and keeps a week's record, and the coach can see it.", fontSize = 14.sp, color = PulseColors.textSecondary) + Text(tr("Add what you take on a schedule. PulseLoop asks once per dose and keeps a week's record, and the coach can see it."), fontSize = 14.sp, color = PulseColors.textSecondary) } if (doses.isNotEmpty()) { Column( @@ -89,10 +91,10 @@ fun MedsScreen(onBack: () -> Unit) { } when (d.state) { Meds.State.TAKEN, Meds.State.SKIPPED -> - TextButton(onClick = { answer(d, null) }) { Text("Undo") } + TextButton(onClick = { answer(d, null) }) { Text(tr("Undo")) } else -> { - TextButton(onClick = { answer(d, "skipped") }) { Text("Skip", color = PulseColors.textMuted) } - TextButton(onClick = { answer(d, "taken") }) { Text("Taken") } + TextButton(onClick = { answer(d, "skipped") }) { Text(tr("Skip"), color = PulseColors.textMuted) } + TextButton(onClick = { answer(d, "taken") }) { Text(tr("Taken")) } } } } @@ -110,16 +112,16 @@ fun MedsScreen(onBack: () -> Unit) { color = if (m.active) PulseColors.textPrimary else PulseColors.textMuted) val adherence = Meds.adherence(m, answers, today) Text( - (if (m.kind == "supplement") "Supplement" else "Medication") + " · " + Meds.times(m).joinToString(", ") + - (adherence?.let { " · $it% taken this week" } ?: "") + if (!m.active) " · paused" else "", + (if (m.kind == "supplement") tr("Supplement") else tr("Medication")) + " · " + Meds.times(m).joinToString(", ") + + (adherence?.let { " · $it% taken this week" } ?: "") + if (!m.active) tr(" · paused") else "", fontSize = 12.sp, color = PulseColors.textMuted, ) } } } - Button(onClick = { adding = true }, modifier = Modifier.fillMaxWidth()) { Text("Add medication or supplement") } + Button(onClick = { adding = true }, modifier = Modifier.fillMaxWidth()) { Text(tr("Add medication or supplement")) } Text( - "A record for you and your doctor. PulseLoop doesn't check interactions or doses; ask your pharmacist.", + tr("A record for you and your doctor. PulseLoop doesn't check interactions or doses; ask your pharmacist."), fontSize = 11.sp, color = PulseColors.textMuted, ) Spacer(Modifier.height(24.dp)) @@ -158,16 +160,16 @@ private fun MedDialog(initial: MedEntity?, onDismiss: () -> Unit, onSave: (MedEn } AlertDialog( onDismissRequest = onDismiss, - title = { Text(if (initial == null) "Add" else "Edit") }, + title = { Text(if (initial == null) tr("Add") else tr("Edit")) }, text = { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - OutlinedTextField(name, { name = it.take(60) }, label = { Text("Name") }, singleLine = true, modifier = Modifier.fillMaxWidth()) - OutlinedTextField(dose, { dose = it.take(40) }, label = { Text("Dose (optional)") }, singleLine = true, modifier = Modifier.fillMaxWidth()) + OutlinedTextField(name, { name = it.take(60) }, label = { Text(tr("Name")) }, singleLine = true, modifier = Modifier.fillMaxWidth()) + OutlinedTextField(dose, { dose = it.take(40) }, label = { Text(tr("Dose (optional)")) }, singleLine = true, modifier = Modifier.fillMaxWidth()) FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { - chip("Medication", kind == "medication") { kind = "medication" } - chip("Supplement", kind == "supplement") { kind = "supplement" } + chip(tr("Medication"), kind == "medication") { kind = "medication" } + chip(tr("Supplement"), kind == "supplement") { kind = "supplement" } } - Text("Times", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(tr("Times"), fontSize = 13.sp, color = PulseColors.textSecondary) FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { (PRESET_TIMES + times).distinct().sorted().forEach { t -> chip(t, t in times) { times = if (t in times) times - t else times + t } @@ -175,12 +177,12 @@ private fun MedDialog(initial: MedEntity?, onDismiss: () -> Unit, onSave: (MedEn } if (initial != null) { Row(verticalAlignment = Alignment.CenterVertically) { - Text("Active", fontSize = 14.sp, modifier = Modifier.weight(1f)) + Text(tr("Active"), fontSize = 14.sp, modifier = Modifier.weight(1f)) androidx.compose.material3.Switch(checked = active, onCheckedChange = { active = it }) } onDelete?.let { del -> TextButton(onClick = del) { Icon(Icons.Filled.Delete, null, tint = PulseColors.danger, modifier = Modifier.size(16.dp)) - Text(" Delete", color = PulseColors.danger) + Text(tr(" Delete"), color = PulseColors.danger) } } } } @@ -191,8 +193,8 @@ private fun MedDialog(initial: MedEntity?, onDismiss: () -> Unit, onSave: (MedEn name = name.trim(), dose = dose.trim().ifEmpty { null }, kind = kind, timesCsv = times.sorted().joinToString(","), active = active, )) - }) { Text("Save") } + }) { Text(tr("Save")) } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(tr("Cancel")) } }, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt index c38af3e3..861b6704 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.components.rememberReduceMotion import com.pulseloop.ui.components.switchRow import androidx.activity.compose.BackHandler @@ -142,8 +144,8 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () Column(Modifier.fillMaxSize().background(PulseColors.background)) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { - IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } - Text("My Health", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } + Text(tr("My Health"), modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) val shareScope = rememberCoroutineScope() IconButton( onClick = { @@ -156,12 +158,12 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () putExtra(android.content.Intent.EXTRA_STREAM, uri) addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION) } - context.startActivity(android.content.Intent.createChooser(intent, "Share my week")) + context.startActivity(android.content.Intent.createChooser(intent, tr("Share my week"))) } } }, modifier = Modifier.align(Alignment.CenterEnd), - ) { Icon(androidx.compose.material.icons.Icons.Filled.Share, "Share my week", tint = PulseColors.textSecondary) } + ) { Icon(androidx.compose.material.icons.Icons.Filled.Share, tr("Share my week"), tint = PulseColors.textSecondary) } } Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), @@ -170,7 +172,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () val s = snap if (s == null) { Text( - if (loadFailed) "Couldn't load your health history." else "Reading your history…", + if (loadFailed) tr("Couldn't load your health history.") else tr("Reading your history…"), color = if (loadFailed) PulseColors.warning else PulseColors.textMuted, fontSize = 13.sp, ) } else { @@ -180,8 +182,8 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { - Text("What changed", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("Your nights against your own normal, kept as a log", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("What changed"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Your nights against your own normal, kept as a log"), fontSize = 12.sp, color = PulseColors.textMuted) } Text("›", fontSize = 22.sp, color = PulseColors.textMuted) } @@ -194,7 +196,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () ) { Column(Modifier.weight(1f)) { Text(cycle?.let { "Cycle · day ${it.cycleDay} · ${it.phase.label}" } ?: "Cycle", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text(cycle?.phase?.note ?: "Log your period to see its phase beside your sleep and recovery", fontSize = 12.sp, color = PulseColors.textMuted) + Text(cycle?.phase?.note ?: tr("Log your period to see its phase beside your sleep and recovery"), fontSize = 12.sp, color = PulseColors.textMuted) } Text("›", fontSize = 22.sp, color = PulseColors.textMuted) } @@ -204,8 +206,8 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { - Text("Medications & supplements", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("Your schedule, today's doses and a week's record", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("Medications & supplements"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Your schedule, today's doses and a week's record"), fontSize = 12.sp, color = PulseColors.textMuted) } Text("›", fontSize = 22.sp, color = PulseColors.textMuted) } @@ -213,7 +215,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () RestMode.set(context, days); restUntil = RestMode.until(context) } if (s.areas.isNotEmpty()) { - Section("Health areas · last 60–90 days") { + Section(tr("Health areas · last 60–90 days")) { s.areas.forEach { a -> Row(verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { @@ -233,7 +235,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () StepCalibrationCard(db) TrendsSection(db) Text( - "Estimates from your ring compared with your own recent normal, not medical measurements.", + tr("Estimates from your ring compared with your own recent normal, not medical measurements."), fontSize = 11.sp, color = PulseColors.textMuted, ) Spacer(Modifier.height(24.dp)) @@ -244,7 +246,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () @Composable private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate?, onRest: (Int?) -> Unit) { - Section("Symptom Radar") { + Section(tr("Symptom Radar")) { if (r == null || r.baselineNights < SymptomRadar.MIN_BASELINE) { Text("Learning your normal: ${r?.baselineNights ?: 0} of ${SymptomRadar.MIN_BASELINE} nights.", fontSize = 13.sp, color = PulseColors.textSecondary) } else { @@ -256,19 +258,19 @@ private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate Text(r.level.label, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = color) Text(r.level.summary, fontSize = 13.sp, color = PulseColors.textSecondary) r.signals.forEach { sig -> - Fact(sig.metric.title, if (sig.flagged) "Elevated" else "Normal", sig.detail, + Fact(sig.metric.title, if (sig.flagged) tr("Elevated") else tr("Normal"), sig.detail, if (sig.flagged) PulseColors.warning else PulseColors.textSecondary) } if (r.level != SymptomRadar.Level.NONE) { - Text("Not a diagnosis. Rest, fluids and an easier day help; see a doctor if you feel unwell.", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("Not a diagnosis. Rest, fluids and an easier day help; see a doctor if you feel unwell."), fontSize = 12.sp, color = PulseColors.textMuted) } } Row(Modifier.switchRow(checked = restUntil != null, onCheckedChange = { on -> onRest(if (on) 3 else null) }), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Rest Mode", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Rest Mode"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( restUntil?.let { "On until ${it.dayOfMonth}/${it.monthValue}: activity nudges paused, the coach eases off." } - ?: "Feeling unwell? Pause activity nudges for 3 days.", + ?: tr("Feeling unwell? Pause activity nudges for 3 days."), fontSize = 12.sp, color = PulseColors.textMuted, ) } @@ -279,18 +281,18 @@ private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate @Composable private fun SleepSection(s: HealthInsightsRepository.Snapshot) { - Section("Sleep") { - Fact("Sleep need", SleepFormat.duration(s.need.minutes), - if (s.need.isLearned) "Learned from nights you woke recovered" else "Your goal, until 5 recovered nights teach the app yours") + Section(tr("Sleep")) { + Fact(tr("Sleep need"), SleepFormat.duration(s.need.minutes), + if (s.need.isLearned) tr("Learned from nights you woke recovered") else tr("Your goal, until 5 recovered nights teach the app yours")) s.debt?.let { d -> val color = when (d.level) { SleepDebt.Level.NONE -> PulseColors.success; SleepDebt.Level.LOW -> PulseColors.info SleepDebt.Level.MODERATE -> PulseColors.warning; SleepDebt.Level.HIGH -> PulseColors.danger } - Fact("Sleep debt", "${d.level.label} · ${SleepFormat.duration(d.minutes)}", "Last 14 nights, recent nights weigh more", color) - } ?: Fact("Sleep debt", "—", "Needs 5 nights in the last 2 weeks") + Fact(tr("Sleep debt"), "${d.level.label} · ${SleepFormat.duration(d.minutes)}", "Last 14 nights, recent nights weigh more", color) + } ?: Fact(tr("Sleep debt"), "—", tr("Needs 5 nights in the last 2 weeks")) s.bodyClock?.let { c -> - Fact("Body clock", c.chronotype.label, "Usual sleep midpoint ${c.midpointLabel()} · this week ${c.alignment.label.lowercase()}" + + Fact(tr("Body clock"), c.chronotype.label, "Usual sleep midpoint ${c.midpointLabel()} · this week ${c.alignment.label.lowercase()}" + if (c.alignment != BodyClock.Alignment.ALIGNED) " (${if (c.recentShiftMin > 0) "+" else ""}${c.recentShiftMin} min)" else "") } } @@ -299,10 +301,10 @@ private fun SleepSection(s: HealthInsightsRepository.Snapshot) { @Composable private fun StressSection(s: HealthInsightsRepository.Snapshot, onBreathe: () -> Unit) { val context = LocalContext.current - Section("Stress") { + Section(tr("Stress")) { val z = s.todayStress if (z == null) { - Text("No daytime stress readings today yet.", fontSize = 13.sp, color = PulseColors.textMuted) + Text(tr("No daytime stress readings today yet."), fontSize = 13.sp, color = PulseColors.textMuted) } else { Text("Today: ${z.summary.label}", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) val total = z.totalMin.coerceAtLeast(1).toFloat() @@ -315,46 +317,46 @@ private fun StressSection(s: HealthInsightsRepository.Snapshot, onBreathe: () -> Text("Restored ${SleepFormat.duration(z.restoredMin)} · relaxed ${SleepFormat.duration(z.relaxedMin)} · engaged ${SleepFormat.duration(z.engagedMin)} · stressed ${SleepFormat.duration(z.stressedMin)}", fontSize = 12.sp, color = PulseColors.textMuted) } - s.resilience?.let { Fact("Resilience", it.level.label, "Daytime recovery against stress, and how well nights restore you (${it.daysUsed} days)") } + s.resilience?.let { Fact(tr("Resilience"), it.level.label, "Daytime recovery against stress, and how well nights restore you (${it.daysUsed} days)") } val sessions = remember { MindfulSessions.all(context) } val week = sessions.filter { it.startAt >= System.currentTimeMillis() - 7 * 86_400_000L } - Fact("Breathing sessions this week", "${week.size} · ${week.sumOf { it.minutes }} min") + Fact(tr("Breathing sessions this week"), "${week.size} · ${week.sumOf { it.minutes }} min") val effectDb = remember { PulseLoopDatabase.getInstance(context) } val effect by produceState(null) { value = runCatching { MindfulSessions.effect(context, effectDb) }.getOrNull() } effect?.let { e -> Fact( - "After a session", "HRV ${if (e.hrvChangePct >= 0) "+" else ""}${e.hrvChangePct}%", + tr("After a session"), "HRV ${if (e.hrvChangePct >= 0) "+" else ""}${e.hrvChangePct}%", "Two hours after against two hours before, over ${e.sessions} sessions. Readings during a session aren't counted: slow breathing raises HRV while it lasts.", ) } - OutlinedButton(onClick = onBreathe, modifier = Modifier.fillMaxWidth()) { Text("Start a breathing session") } + OutlinedButton(onClick = onBreathe, modifier = Modifier.fillMaxWidth()) { Text(tr("Start a breathing session")) } } } @Composable private fun HeartSection(s: HealthInsightsRepository.Snapshot) { - Section("Heart") { + Section(tr("Heart")) { if (s.hrToday.size >= 2) { - Text("Heart rate since last night", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(tr("Heart rate since last night"), fontSize = 13.sp, color = PulseColors.textSecondary) HeartRateContextChart(s.hrToday, s.sleepWindows, s.workoutWindows) Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Legend(PulseColors.sleep, "Sleep"); Legend(PulseColors.steps, "Workout"); Legend(PulseColors.heartRate, "Day") + Legend(PulseColors.sleep, tr("Sleep")); Legend(PulseColors.steps, tr("Workout")); Legend(PulseColors.heartRate, tr("Day")) } } s.cardioLoad?.let { l -> Fact( - "Cardio load today", "${l.load}" + (l.band?.let { " · ${it.label}" } ?: ""), + tr("Cardio load today"), "${l.load}" + (l.band?.let { " · ${it.label}" } ?: ""), "Heart rate above your quiet waking ${l.quietHr} bpm, ${l.elevatedMinutes} min well above it" + (l.usual?.let { ". Your usual day: $it" } ?: ""), ) } s.cardio?.let { c -> Fact("Cardio capacity (VO₂max)", "%.0f · %s".format(c.vo2max, c.level.label), - if (c.fromRing) "Measured by your ring" else "Estimated from resting heart rate and age") + if (c.fromRing) tr("Measured by your ring") else tr("Estimated from resting heart rate and age")) // No "cardiovascular age": from a ring it would only restate resting heart rate and age // as a number of years, which reads as far more than it is (OpenStrap Edge dropped its // own for the same reason). - } ?: Text("Add your age in Settings → User Profile for cardio capacity.", fontSize = 12.sp, color = PulseColors.textMuted) + } ?: Text(tr("Add your age in Settings → User Profile for cardio capacity."), fontSize = 12.sp, color = PulseColors.textMuted) } } @@ -395,15 +397,15 @@ fun HeartRateContextChart(samples: List, sleep: List, wo @Composable private fun HabitsSection(h: HealthInsightsRepository.Habits) { - Section("Habits & routines · 30-day averages") { - h.bedtime?.let { Fact("Bedtime", it) } - h.wake?.let { Fact("Wake-up", it) } - h.sleepMin?.let { Fact("Sleep", SleepFormat.duration(it)) } + Section(tr("Habits & routines · 30-day averages")) { + h.bedtime?.let { Fact(tr("Bedtime"), it) } + h.wake?.let { Fact(tr("Wake-up"), it) } + h.sleepMin?.let { Fact(tr("Sleep"), SleepFormat.duration(it)) } h.steps?.let { Fact("Steps", "%,d".format(it)) } - h.activeMin?.let { Fact("Active minutes", "$it min") } - h.restingHr?.let { Fact("Resting heart rate", "${it.roundToInt()} bpm") } + h.activeMin?.let { Fact(tr("Active minutes"), "$it min") } + h.restingHr?.let { Fact(tr("Resting heart rate"), "${it.roundToInt()} bpm") } if (listOf(h.bedtime, h.steps, h.restingHr).all { it == null }) { - Text("A few more days of data and your routines show up here.", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("A few more days of data and your routines show up here."), fontSize = 12.sp, color = PulseColors.textMuted) } } } @@ -419,7 +421,7 @@ private fun TrendsSection(db: PulseLoopDatabase) { value = runCatching { Trends.aggregate(HealthInsightsRepository.daily(db, metric, period.days), period) } .onFailure { trendFailed = true }.getOrNull() } - Section("Trends") { + Section(tr("Trends")) { Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { TrendMetric.entries.forEach { m -> val on = m == metric @@ -444,7 +446,7 @@ private fun TrendsSection(db: PulseLoopDatabase) { val pts = points when { pts == null && trendFailed -> Text("Couldn't load ${metric.label.lowercase()} trends.", fontSize = 12.sp, color = PulseColors.warning) - pts == null -> Text("Loading…", fontSize = 12.sp, color = PulseColors.textMuted) + pts == null -> Text(tr("Loading…"), fontSize = 12.sp, color = PulseColors.textMuted) pts.size < 2 -> Text("Not enough ${metric.label.lowercase()} data for this view yet.", fontSize = 12.sp, color = PulseColors.textMuted) else -> { val shown = pts.takeLast(if (period == Trends.Period.DAY) 30 else 26) @@ -515,9 +517,9 @@ fun BreatheScreen(onBack: () -> Unit) { Column(Modifier.fillMaxSize().background(PulseColors.background).padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) { Box(Modifier.fillMaxWidth()) { IconButton(onClick = { if (startedAt != null) finish(); onBack() }, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") + Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } - Text("Breathe", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + Text(tr("Breathe"), modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) } Spacer(Modifier.weight(1f)) val r = result @@ -538,27 +540,27 @@ fun BreatheScreen(onBack: () -> Unit) { Box(Modifier.size(220.dp).scale(s).clip(CircleShape).dither(PulseColors.accent, 0.35f, CircleShape).border(2.dp, PulseColors.accent, CircleShape)) Spacer(Modifier.height(24.dp)) Text( - if (inhaling) "Breathe in" else "Breathe out", fontSize = 18.sp, color = PulseColors.textPrimary, + if (inhaling) tr("Breathe in") else tr("Breathe out"), fontSize = 18.sp, color = PulseColors.textPrimary, modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, ) Text("%d:%02d".format(remaining / 60, remaining % 60), fontSize = 28.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Spacer(Modifier.height(16.dp)) - OutlinedButton(onClick = { finish() }) { Text("End session") } + OutlinedButton(onClick = { finish() }) { Text(tr("End session")) } } r != null -> { - Text("Session saved", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Session saved"), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text("${r.minutes} min" + (r.avgHr?.let { " · average $it bpm" } ?: ""), fontSize = 15.sp, color = PulseColors.textSecondary) if (r.startHr != null && r.endHr != null) { Text("Heart rate ${r.startHr} → ${r.endHr} bpm", fontSize = 15.sp, color = PulseColors.textSecondary) } else { - Text("Your ring logs heart rate every few minutes, so short sessions may show none.", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("Your ring logs heart rate every few minutes, so short sessions may show none."), fontSize = 12.sp, color = PulseColors.textMuted) } - Text("Tagged as \"Meditation or relaxing\" in today's journal.", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("Tagged as \"Meditation or relaxing\" in today's journal."), fontSize = 12.sp, color = PulseColors.textMuted) Spacer(Modifier.height(16.dp)) - Button(onClick = onBack) { Text("Done") } + Button(onClick = onBack) { Text(tr("Done")) } } else -> { - Text("Slow breathing: in for 4 seconds, out for 6.", fontSize = 15.sp, color = PulseColors.textSecondary) + Text(tr("Slow breathing: in for 4 seconds, out for 6."), fontSize = 15.sp, color = PulseColors.textSecondary) Spacer(Modifier.height(16.dp)) Row(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { listOf(1, 3, 5, 10).forEach { m -> @@ -570,7 +572,7 @@ fun BreatheScreen(onBack: () -> Unit) { } } Spacer(Modifier.height(24.dp)) - Button(onClick = { result = null; elapsedMs = 0L; startedAt = System.currentTimeMillis() }) { Text("Start") } + Button(onClick = { result = null; elapsedMs = 0L; startedAt = System.currentTimeMillis() }) { Text(tr("Start")) } } } Spacer(Modifier.weight(1f)) @@ -591,10 +593,10 @@ fun MyHealthEntryCard(onClick: () -> Unit) { verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { - Text("My Health & Trends", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("My Health & Trends"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( if (restUntil != null) "Rest Mode on until ${restUntil.dayOfWeek.getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.getDefault())}" - else "Symptom radar, sleep debt, stress, body clock, cardio capacity", + else tr("Symptom radar, sleep debt, stress, body clock, cardio capacity"), fontSize = 12.sp, color = if (restUntil != null) PulseColors.accent else PulseColors.textMuted, ) } @@ -623,13 +625,13 @@ private fun StepCalibrationCard(db: PulseLoopDatabase) { com.pulseloop.service.StepCalibration.factor(com.pulseloop.service.StepCalibration.phoneDays(context), ring, java.time.LocalDate.now()) }.getOrNull() } - Section("Ring steps vs your phone") { + Section(tr("Ring steps vs your phone")) { when { !granted -> { - Text("Your phone counts steps too. Comparing the two over a few days shows whether your ring over- or under-counts.", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(tr("Your phone counts steps too. Comparing the two over a few days shows whether your ring over- or under-counts."), fontSize = 13.sp, color = PulseColors.textSecondary) OutlinedButton(onClick = { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) launcher.launch(android.Manifest.permission.ACTIVITY_RECOGNITION) - }, modifier = Modifier.fillMaxWidth()) { Text("Compare with my phone") } + }, modifier = Modifier.fillMaxWidth()) { Text(tr("Compare with my phone")) } } result == null -> Text( "Collecting: needs ${com.pulseloop.service.StepCalibration.MIN_DAYS} days with at least ${com.pulseloop.service.StepCalibration.MIN_STEPS} steps on both. Carry your phone as usual.", @@ -647,10 +649,10 @@ private fun StepCalibrationCard(db: PulseLoopDatabase) { fontSize = 14.sp, color = PulseColors.textPrimary, ) Row(verticalAlignment = Alignment.CenterVertically) { - Text("Show phone-calibrated steps on Today", fontSize = 13.sp, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) + Text(tr("Show phone-calibrated steps on Today"), fontSize = 13.sp, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) Switch(checked = applied, onCheckedChange = { applied = it; com.pulseloop.service.StepCalibration.setApplied(context, it) }) } - Text("Goals, scores and Health Connect keep the ring's own count.", fontSize = 11.sp, color = PulseColors.textMuted) + Text(tr("Goals, scores and Health Connect keep the ring's own count."), fontSize = 11.sp, color = PulseColors.textMuted) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt index 1cd0ed19..0a677ca4 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll @@ -106,10 +108,10 @@ fun NutritionScreen( contentWindowInsets = WindowInsets(0, 0, 0, 0), topBar = { TopAppBar( - title = { Text("Nutrition") }, + title = { Text(tr("Nutrition")) }, navigationIcon = { IconButton(onClick = onBack) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") + Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } }, windowInsets = WindowInsets(0, 0, 0, 0), @@ -125,9 +127,9 @@ fun NutritionScreen( // Day navigation — left goes to older dates (higher offset), right goes to today (offset 0). item { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) { - IconButton(onClick = { dayOffset++ }) { Icon(Icons.Filled.ChevronLeft, "Previous day") } + IconButton(onClick = { dayOffset++ }) { Icon(Icons.Filled.ChevronLeft, tr("Previous day")) } Text(dateLabel, fontWeight = FontWeight.SemiBold, fontSize = 16.sp) - IconButton(onClick = { if (dayOffset > 0) dayOffset-- }, enabled = dayOffset > 0) { Icon(Icons.Filled.ChevronRight, "Next day") } + IconButton(onClick = { if (dayOffset > 0) dayOffset-- }, enabled = dayOffset > 0) { Icon(Icons.Filled.ChevronRight, tr("Next day")) } } } @@ -149,9 +151,9 @@ fun NutritionScreen( ) Spacer(Modifier.height(8.dp)) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) { - MacroBar("Protein", totals.sumOf { it.totalP }, goal?.intakeProteinG ?: 150.0, PulseColors.heartRate) - MacroBar("Carbs", totals.sumOf { it.totalC }, goal?.intakeCarbsG ?: 250.0, PulseColors.calories) - MacroBar("Fat", totals.sumOf { it.totalF }, goal?.intakeFatG ?: 65.0, PulseColors.warning) + MacroBar(tr("Protein"), totals.sumOf { it.totalP }, goal?.intakeProteinG ?: 150.0, PulseColors.heartRate) + MacroBar(tr("Carbs"), totals.sumOf { it.totalC }, goal?.intakeCarbsG ?: 250.0, PulseColors.calories) + MacroBar(tr("Fat"), totals.sumOf { it.totalF }, goal?.intakeFatG ?: 65.0, PulseColors.warning) } } } @@ -176,7 +178,7 @@ fun NutritionScreen( carbsG = idea.items.sumOf { it.carbsG }.toDouble(), fatG = idea.items.sumOf { it.fatG }.toDouble(), sourceRaw = NutritionTools.sourceRawManual, - notes = "From the next-meal suggestion", + notes = tr("From the next-meal suggestion"), ) db.mealEntryDao().upsert(entry) com.pulseloop.service.MealJournal.afterLog(db, entry) @@ -231,7 +233,7 @@ fun NutritionScreen( ) { Icon(Icons.Filled.PhotoCamera, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - Text("Photo") + Text(tr("Photo")) } OutlinedButton( onClick = { analysisRequest = AnalysisRequest(startWithCamera = false) }, @@ -239,7 +241,7 @@ fun NutritionScreen( ) { Icon(Icons.Filled.AutoAwesome, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - Text("Describe") + Text(tr("Describe")) } } } @@ -253,7 +255,7 @@ fun NutritionScreen( ) { Icon(Icons.Filled.Add, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - Text("Log Meal") + Text(tr("Log Meal")) } } } @@ -262,7 +264,7 @@ fun NutritionScreen( mealToDelete?.let { meal -> AlertDialog( onDismissRequest = { mealToDelete = null }, - title = { Text("Delete meal?") }, + title = { Text(tr("Delete meal?")) }, text = { Text("\"${meal.name}\" will be removed from this day's log.") }, confirmButton = { TextButton(onClick = { @@ -272,9 +274,9 @@ fun NutritionScreen( com.pulseloop.service.DrinksRepository.onMealDeleted(db, meal.id) reload() } - }) { Text("Delete", color = PulseColors.danger) } + }) { Text(tr("Delete"), color = PulseColors.danger) } }, - dismissButton = { TextButton(onClick = { mealToDelete = null }) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = { mealToDelete = null }) { Text(tr("Cancel")) } }, ) } @@ -404,7 +406,7 @@ fun MealLogDialog( } if (product == null) { // iOS MealLogSheet.swift:128-130. - scanNotice = "Product not found for that barcode. Enter it manually instead." + scanNotice = tr("Product not found for that barcode. Enter it manually instead.") } else { // Clear on success too: two scans in quick succession run two lookups, and // an earlier-started "not found" completing after a later success would @@ -433,7 +435,7 @@ fun MealLogDialog( throw e } catch (e: Exception) { // iOS MealLogSheet.swift:258-260 catch-all. - scanNotice = "Couldn't look up that barcode. Check your connection or enter the meal manually." + scanNotice = tr("Couldn't look up that barcode. Check your connection or enter the meal manually.") } finally { lookingUp = false } @@ -442,7 +444,7 @@ fun MealLogDialog( AlertDialog( onDismissRequest = onDismiss, - title = { Text("Log Meal") }, + title = { Text(tr("Log Meal")) }, text = { // Scrolls so the fields stay reachable on short screens and with the keyboard up. Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { @@ -458,14 +460,14 @@ fun MealLogDialog( TextButton(onClick = { showScanner = true }, enabled = !lookingUp) { Icon(Icons.Filled.QrCodeScanner, null, Modifier.size(18.dp)) Spacer(Modifier.width(4.dp)) - Text("Scan barcode") + Text(tr("Scan barcode")) } } scanNotice?.let { // iOS inlineNotice copy (MealLogSheet.swift:128-130 / :259). Text(it, fontSize = 12.sp, color = PulseColors.warning) } - OutlinedTextField(value = name, onValueChange = { name = it }, label = { Text("Name") }, modifier = Modifier.fillMaxWidth(), maxLines = 3, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(capitalization = androidx.compose.ui.text.input.KeyboardCapitalization.Sentences)) + OutlinedTextField(value = name, onValueChange = { name = it }, label = { Text(tr("Name")) }, modifier = Modifier.fillMaxWidth(), maxLines = 3, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(capitalization = androidx.compose.ui.text.input.KeyboardCapitalization.Sentences)) FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { listOf("breakfast", "lunch", "dinner", "snack").forEach { t -> FilterChip(selected = type == t, onClick = { type = t }, label = { Text(t.replaceFirstChar { it.uppercase() }) }) @@ -473,11 +475,11 @@ fun MealLogDialog( } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { OutlinedTextField(value = cal, onValueChange = { cal = decimalInput(it) ?: cal }, label = { Text("kcal", maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) - OutlinedTextField(value = protein, onValueChange = { protein = decimalInput(it) ?: protein }, label = { Text("Protein (g)", maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = protein, onValueChange = { protein = decimalInput(it) ?: protein }, label = { Text(tr("Protein (g)"), maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField(value = carbs, onValueChange = { carbs = decimalInput(it) ?: carbs }, label = { Text("Carbs (g)", maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) - OutlinedTextField(value = fat, onValueChange = { fat = decimalInput(it) ?: fat }, label = { Text("Fat (g)", maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = carbs, onValueChange = { carbs = decimalInput(it) ?: carbs }, label = { Text(tr("Carbs (g)"), maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = fat, onValueChange = { fat = decimalInput(it) ?: fat }, label = { Text(tr("Fat (g)"), maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) } } }, @@ -512,9 +514,9 @@ fun MealLogDialog( userEdited = edited, ) }) - }, enabled = valid) { Text("Save") } + }, enabled = valid) { Text(tr("Save")) } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(tr("Cancel")) } }, ) if (showScanner) { @@ -583,13 +585,13 @@ private fun NextMealCard( fontSize = 13.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, ) if (idea.fromPreferences.isNotEmpty()) { - Text("Your preference: " + idea.fromPreferences.joinToString("; "), fontSize = 12.sp, color = PulseColors.accent) + Text(tr("Your preference: ") + idea.fromPreferences.joinToString("; "), fontSize = 12.sp, color = PulseColors.accent) } idea.note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textSecondary) } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Button(onClick = onLog, modifier = Modifier.weight(1f)) { Text("Log this") } + Button(onClick = onLog, modifier = Modifier.weight(1f)) { Text(tr("Log this")) } if (onDiscuss != null) { - OutlinedButton(onClick = onDiscuss, modifier = Modifier.weight(1f)) { Text("Other ideas") } + OutlinedButton(onClick = onDiscuss, modifier = Modifier.weight(1f)) { Text(tr("Other ideas")) } } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt index 64b164f9..618650c7 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import android.Manifest import android.content.Context @@ -259,7 +261,7 @@ private fun OnboardingTopBar( IconButton(onClick = onBack) { Icon( Icons.AutoMirrored.Filled.ArrowBack, - contentDescription = "Back", + contentDescription = tr("Back"), tint = PulseColors.textSecondary, ) } @@ -277,7 +279,7 @@ private fun OnboardingTopBar( Box(Modifier.size(width = 60.dp, height = 44.dp), contentAlignment = Alignment.CenterEnd) { if (showsSkip) { Text( - "Skip", + tr("Skip"), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textSecondary, @@ -321,12 +323,12 @@ private fun WelcomeStep( openAppSettings: () -> Unit = {}, ) { val features = listOf( - WelcomeFeature(Icons.Filled.Paid, "No subscription", "Own your ring data", PulseColors.success), - WelcomeFeature(Icons.Filled.Lock, "Privacy first", "Data stays on device", PulseColors.info), - WelcomeFeature(Icons.Filled.AutoAwesome, "AI health coach", "Learns your baseline", PulseColors.accent), - WelcomeFeature(Icons.Filled.MonitorHeart, "See your vitals", "HR, SpO₂, HRV & stress", PulseColors.heartRate), - WelcomeFeature(Icons.Filled.Bedtime, "Sleep tracking", "Stages and trends", PulseColors.sleep), - WelcomeFeature(Icons.Filled.DirectionsRun, "Activity recording", "Live workout tracking", PulseColors.steps), + WelcomeFeature(Icons.Filled.Paid, tr("No subscription"), tr("Own your ring data"), PulseColors.success), + WelcomeFeature(Icons.Filled.Lock, tr("Privacy first"), tr("Data stays on device"), PulseColors.info), + WelcomeFeature(Icons.Filled.AutoAwesome, tr("AI health coach"), tr("Learns your baseline"), PulseColors.accent), + WelcomeFeature(Icons.Filled.MonitorHeart, tr("See your vitals"), tr("HR, SpO₂, HRV & stress"), PulseColors.heartRate), + WelcomeFeature(Icons.Filled.Bedtime, tr("Sleep tracking"), tr("Stages and trends"), PulseColors.sleep), + WelcomeFeature(Icons.Filled.DirectionsRun, tr("Activity recording"), tr("Live workout tracking"), PulseColors.steps), ) StepScaffold( @@ -334,8 +336,8 @@ private fun WelcomeStep( Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { if (permissionDenied) { Text( - "PulseLoop needs Bluetooth permission to find and connect to your ring. " + - "Allow it in Settings, or continue without a ring and pair one later.", + tr("PulseLoop needs Bluetooth permission to find and connect to your ring. " + + "Allow it in Settings, or continue without a ring and pair one later."), fontSize = 13.sp, color = PulseColors.textSecondary, textAlign = TextAlign.Center, @@ -343,13 +345,13 @@ private fun WelcomeStep( ) // "Try again" re-checks the grant first, so it also carries on after the user // allowed Bluetooth in Settings; without it a denial had no way back to pairing. - PrimaryButton("Try again", icon = Icons.Filled.ArrowForward, onClick = getStarted) - SecondaryButton("Open settings", onClick = openAppSettings) - SecondaryButton("Continue without ring", icon = Icons.Filled.GridView, onClick = exploreWithoutRing) + PrimaryButton(tr("Try again"), icon = Icons.Filled.ArrowForward, onClick = getStarted) + SecondaryButton(tr("Open settings"), onClick = openAppSettings) + SecondaryButton(tr("Continue without ring"), icon = Icons.Filled.GridView, onClick = exploreWithoutRing) } else { - PrimaryButton("Get started", icon = Icons.Filled.ArrowForward, onClick = getStarted) - SecondaryButton("I wear an Oura or another device", icon = Icons.Filled.Watch, onClick = useOtherDevice) - SecondaryButton("Explore without ring", icon = Icons.Filled.GridView, onClick = exploreWithoutRing) + PrimaryButton(tr("Get started"), icon = Icons.Filled.ArrowForward, onClick = getStarted) + SecondaryButton(tr("I wear an Oura or another device"), icon = Icons.Filled.Watch, onClick = useOtherDevice) + SecondaryButton(tr("Explore without ring"), icon = Icons.Filled.GridView, onClick = exploreWithoutRing) } } }, @@ -368,8 +370,8 @@ private fun WelcomeStep( .clip(RoundedCornerShape(8.dp)), ) StepHeader( - title = "Set up PulseLoop", - subtitle = "Your health, on your terms — no subscription, no cloud.", + title = tr("Set up PulseLoop"), + subtitle = tr("Your health, on your terms — no subscription, no cloud."), ) // Two-column feature grid (rows of two, since we're inside a scroll column). @@ -444,7 +446,7 @@ private fun ProfileStep( StepScaffold( footer = { - PrimaryButton("Continue", icon = Icons.Filled.ArrowForward, enabled = draft != null) { + PrimaryButton(tr("Continue"), icon = Icons.Filled.ArrowForward, enabled = draft != null) { val current = draft ?: return@PrimaryButton scope.launch { val existing = db.userProfileDao().get() @@ -458,8 +460,8 @@ private fun ProfileStep( }, ) { StepHeader( - title = "Profile", - subtitle = "Used to tune calories, activity goals, and summaries.", + title = tr("Profile"), + subtitle = tr("Used to tune calories, activity goals, and summaries."), ) draft?.let { current -> ProfileEditor(draft = current, onDraftChange = { draft = it }) @@ -488,7 +490,7 @@ private fun GoalsStep( StepScaffold( footer = { - PrimaryButton("Save goals", icon = Icons.Filled.Check, enabled = draft != null) { + PrimaryButton(tr("Save goals"), icon = Icons.Filled.Check, enabled = draft != null) { val current = draft ?: return@PrimaryButton scope.launch { val existing = db.userGoalDao().get() @@ -502,8 +504,8 @@ private fun GoalsStep( }, ) { StepHeader( - title = "Daily goals", - subtitle = "Start with recommended targets. You can change these anytime.", + title = tr("Daily goals"), + subtitle = tr("Start with recommended targets. You can change these anytime."), ) draft?.let { current -> GoalEditor( @@ -529,9 +531,9 @@ private data class BaselineMilestone( private fun BaselineStep(finish: () -> Unit) { // iOS #75 finale copy: Today / First sync / Days 3–7. val milestones = listOf( - BaselineMilestone(null, "Today", "Activity and live vitals, right away", PulseColors.info), - BaselineMilestone(Icons.Filled.Bedtime, "First sync", "Sleep stages and nightly trends", PulseColors.sleep), - BaselineMilestone(Icons.AutoMirrored.Filled.TrendingUp, "Days 3–7", "Your personalized baseline unlocks", PulseColors.success), + BaselineMilestone(null, tr("Today"), tr("Activity and live vitals, right away"), PulseColors.info), + BaselineMilestone(Icons.Filled.Bedtime, tr("First sync"), tr("Sleep stages and nightly trends"), PulseColors.sleep), + BaselineMilestone(Icons.AutoMirrored.Filled.TrendingUp, tr("Days 3–7"), tr("Your personalized baseline unlocks"), PulseColors.success), ) // Celebratory finale (iOS #75): the medallion scales in on appear. reduceMotion-equivalent @@ -546,14 +548,14 @@ private fun BaselineStep(finish: () -> Unit) { StepScaffold( footer = { - PrimaryButton("Start using PulseLoop", icon = Icons.Filled.ArrowForward, onClick = finish) + PrimaryButton(tr("Start using PulseLoop"), icon = Icons.Filled.ArrowForward, onClick = finish) }, ) { SuccessMedallion(scale = medallionScale) SetupCompleteEyebrow() StepHeader( - title = "You're all set", - subtitle = "Wear your ring today. Your baseline builds from here.", + title = tr("You're all set"), + subtitle = tr("Wear your ring today. Your baseline builds from here."), ) Column( @@ -568,13 +570,13 @@ private fun BaselineStep(finish: () -> Unit) { ) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( - "PulseLoop learns your baseline over time", + tr("PulseLoop learns your baseline over time"), fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Text( - "Wear your ring during the day and sync after sleep. Trends become more personal after a few days.", + tr("Wear your ring during the day and sync after sleep. Trends become more personal after a few days."), fontSize = 14.sp, color = PulseColors.textSecondary, lineHeight = 20.sp, @@ -634,7 +636,7 @@ private fun SuccessMedallion(scale: Float) { ) { Icon( Icons.Filled.Verified, - contentDescription = "Setup complete", + contentDescription = tr("Setup complete"), tint = PulseColors.accent, modifier = Modifier.size(56.dp), ) @@ -654,7 +656,7 @@ private fun SetupCompleteEyebrow() { .padding(horizontal = 12.dp, vertical = 6.dp), ) { Icon(Icons.Filled.Verified, contentDescription = null, Modifier.size(14.dp), tint = PulseColors.accent) - Text("Setup complete", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent) + Text(tr("Setup complete"), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent) } } @@ -665,10 +667,10 @@ private fun SetupCompleteEyebrow() { @Composable private fun HealthConnectSourceStep(next: () -> Unit) { StepScaffold( - footer = { SecondaryButton("Skip for now", modifier = Modifier.fillMaxWidth(), onClick = next) }, + footer = { SecondaryButton(tr("Skip for now"), modifier = Modifier.fillMaxWidth(), onClick = next) }, ) { Text( - "Use your device's data", + tr("Use your device's data"), fontSize = 26.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, diff --git a/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt index 25b445e9..a2c533c9 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import android.Manifest import android.app.Activity import android.content.Context @@ -213,8 +215,8 @@ fun PairingScreen( horizontalAlignment = Alignment.CenterHorizontally, ) { PairingHeader( - title = "Add your ring", - subtitle = "Swipe to find your model, then tap to connect.\nYou can also explore first and pair later.", + title = tr("Add your ring"), + subtitle = tr("Swipe to find your model, then tap to connect.\nYou can also explore first and pair later."), ) if (!btReady) { @@ -269,7 +271,7 @@ fun PairingScreen( if (!connected && (isLooking || state.diagnostics.isNotEmpty())) { Text( - if (showDiagnostics) "Hide connection details" else "Show connection details", + if (showDiagnostics) tr("Hide connection details") else tr("Show connection details"), fontSize = 12.sp, color = PulseColors.textSecondary, modifier = Modifier @@ -287,7 +289,7 @@ fun PairingScreen( val trace = buildList { addAll(state.diagnostics.takeLast(4)) state.lastError?.let { if (it !in this) add(it) } - }.joinToString("\n").ifBlank { "Waiting for BLE connection events…" } + }.joinToString("\n").ifBlank { tr("Waiting for BLE connection events…") } Box( Modifier .fillMaxWidth() @@ -317,11 +319,11 @@ fun PairingScreen( horizontalAlignment = Alignment.CenterHorizontally, ) { if (!isLooking && btReady) { - PrimaryButton("Connect ring", icon = Icons.Filled.Sensors) { startLooking() } + PrimaryButton(tr("Connect ring"), icon = Icons.Filled.Sensors) { startLooking() } if (bleClient.hasLastKnownRing && state.connectionState != RingConnectionState.RECONNECTING ) { - SecondaryButton("Reconnect last ring", icon = Icons.Filled.Refresh) { + SecondaryButton(tr("Reconnect last ring"), icon = Icons.Filled.Refresh) { // See SettingsScreen's onConnect (issue #72): a user-initiated // reconnect must clear the stay-off flag a manual Disconnect set, // or it is silently suppressed. @@ -330,9 +332,9 @@ fun PairingScreen( } } if (onSkip != null) { - SecondaryButton("Skip for now", icon = Icons.Filled.ArrowForward, onClick = onSkip) + SecondaryButton(tr("Skip for now"), icon = Icons.Filled.ArrowForward, onClick = onSkip) Text( - "You can pair a ring later from Settings.", + tr("You can pair a ring later from Settings."), fontSize = 12.sp, color = PulseColors.textMuted, textAlign = TextAlign.Center, @@ -535,13 +537,13 @@ private fun ScanningCard( if (matchingRings.isEmpty()) { InlineEmptyState( - title = "No rings found yet", - message = "Wake the ring by tapping or moving it, and keep it close.", + title = tr("No rings found yet"), + message = tr("Wake the ring by tapping or moving it, and keep it close."), modifier = Modifier.padding(top = 8.dp), ) } - SecondaryButton("Stop scanning", icon = Icons.Filled.StopCircle, onClick = onStop) + SecondaryButton(tr("Stop scanning"), icon = Icons.Filled.StopCircle, onClick = onStop) } } @@ -666,7 +668,7 @@ private fun ConnectedCard( ) } if (onContinue != null) { - PrimaryButton("Continue", icon = Icons.Filled.Check, onClick = onContinue) + PrimaryButton(tr("Continue"), icon = Icons.Filled.Check, onClick = onContinue) } } } @@ -690,18 +692,18 @@ private fun BluetoothOffCard() { tint = PulseColors.textMuted, ) Text( - "Bluetooth is off", + tr("Bluetooth is off"), fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Text( - "Turn on Bluetooth to find and connect your ring.", + tr("Turn on Bluetooth to find and connect your ring."), fontSize = 14.sp, color = PulseColors.textSecondary, textAlign = TextAlign.Center, ) - SecondaryButton("Open Settings", icon = Icons.Filled.Settings) { + SecondaryButton(tr("Open Settings"), icon = Icons.Filled.Settings) { try { context.startActivity(Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS)) } catch (_: Exception) { @@ -731,27 +733,27 @@ private fun BluetoothPermissionCard(permanentlyDenied: Boolean, onRequest: () -> tint = PulseColors.textMuted, ) Text( - "Bluetooth access needed", + tr("Bluetooth access needed"), fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Text( if (permanentlyDenied) { - "PulseLoop uses Bluetooth to find and connect your ring. " + - "Allow " + - (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) "\"Nearby devices\"" else "Location") + + tr("PulseLoop uses Bluetooth to find and connect your ring. " + + "Allow ") + + (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) tr("\"Nearby devices\"") else tr("Location")) + " for PulseLoop in Settings." } else { - "PulseLoop uses Bluetooth to find and connect your ring. " + - "Nothing is shared off your phone." + tr("PulseLoop uses Bluetooth to find and connect your ring. " + + "Nothing is shared off your phone.") }, fontSize = 14.sp, color = PulseColors.textSecondary, textAlign = TextAlign.Center, ) if (permanentlyDenied) { - SecondaryButton("Open Settings", icon = Icons.Filled.Settings) { + SecondaryButton(tr("Open Settings"), icon = Icons.Filled.Settings) { try { context.startActivity( Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS) @@ -762,7 +764,7 @@ private fun BluetoothPermissionCard(permanentlyDenied: Boolean, onRequest: () -> } } } else { - SecondaryButton("Allow Bluetooth access", icon = Icons.Filled.Bluetooth, onClick = onRequest) + SecondaryButton(tr("Allow Bluetooth access"), icon = Icons.Filled.Bluetooth, onClick = onRequest) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt index 42fa5617..7b703d5c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import androidx.compose.foundation.Canvas import androidx.compose.foundation.background @@ -80,7 +82,7 @@ fun ScoreRing( Box( Modifier.size(size).clearAndSetSemantics { // One spoken value instead of a bare number; an empty ring says so. - contentDescription = value?.let { "Score $it out of 100" } ?: "No score" + contentDescription = value?.let { "Score $it out of 100" } ?: tr("No score") if (value != null) progressBarRangeInfo = ProgressBarRangeInfo(value.coerceIn(0, 100).toFloat(), 0f..100f) }, contentAlignment = Alignment.Center, @@ -148,13 +150,13 @@ fun ScoreHeader( ) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) { HeaderRing( - label = "Readiness", + label = tr("Readiness"), value = score?.value, caption = when (readiness) { is Readiness.Result.Score -> readiness.band.label - is Readiness.Result.Learning -> "Learning" - Readiness.Result.NoSleep -> "No sleep yet" - is Readiness.Result.Withheld -> "Not measured" + is Readiness.Result.Learning -> tr("Learning") + Readiness.Result.NoSleep -> tr("No sleep yet") + is Readiness.Result.Withheld -> tr("Not measured") null -> " " }, color = score?.let { bandColor(it.band) } ?: PulseColors.readiness, @@ -162,17 +164,17 @@ fun ScoreHeader( modifier = Modifier.weight(1f), ) HeaderRing( - label = "Sleep", + label = tr("Sleep"), value = sleepScore, - caption = sleepScore?.let { Readiness.Band.of(it).label } ?: "No data", + caption = sleepScore?.let { Readiness.Band.of(it).label } ?: tr("No data"), color = PulseColors.sleep, onTap = onSleep, modifier = Modifier.weight(1f), ) HeaderRing( - label = "Activity", + label = tr("Activity"), value = activity?.value, - caption = activity?.band?.label ?: "No data", + caption = activity?.band?.label ?: tr("No data"), color = PulseColors.steps, onTap = onActivity, modifier = Modifier.weight(1f), @@ -211,10 +213,10 @@ fun ReadinessScreen(db: PulseLoopDatabase, onBack: () -> Unit) { Column(Modifier.fillMaxSize()) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") + Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } Text( - "Readiness", modifier = Modifier.align(Alignment.Center), + tr("Readiness"), modifier = Modifier.align(Alignment.Center), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, ) } @@ -256,7 +258,7 @@ fun ReadinessScreen(db: PulseLoopDatabase, onBack: () -> Unit) { ContributorsCard(score.contributors.map { it.asScoreContributor() }) if (score.missing.isNotEmpty()) { Text( - "Not enough data yet: " + score.missing.joinToString { it.title.lowercase() } + ".", + tr("Not enough data yet: ") + score.missing.joinToString { it.title.lowercase() } + ".", fontSize = 12.sp, color = PulseColors.textMuted, ) } @@ -267,7 +269,7 @@ fun ReadinessScreen(db: PulseLoopDatabase, onBack: () -> Unit) { Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { - Text("Why there's no score today", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textMuted) + Text(tr("Why there's no score today"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textMuted) result.reasons.forEach { Text("• $it", fontSize = 13.sp, color = PulseColors.textSecondary) } } } @@ -282,7 +284,7 @@ fun ReadinessScreen(db: PulseLoopDatabase, onBack: () -> Unit) { /** "Contributors" heading and a card of tappable rows; shared by Readiness, Sleep and Activity. */ @Composable -fun ContributorsCard(contributors: List, title: String = "Contributors") { +fun ContributorsCard(contributors: List, title: String = tr("Contributors")) { if (contributors.isEmpty()) return var expanded by remember(contributors) { mutableStateOf(null) } Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { @@ -303,7 +305,7 @@ private fun ContributorRow(c: ScoreContributor, expanded: Boolean, onTap: () -> Column( Modifier.fillMaxWidth() .clickable(role = Role.Button, onClick = onTap) - .semantics { stateDescription = if (expanded) "Expanded" else "Collapsed" } + .semantics { stateDescription = if (expanded) tr("Expanded") else tr("Collapsed") } .padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { @@ -335,10 +337,10 @@ fun ActivityScoreScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenActivit Column(Modifier.fillMaxSize()) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") + Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } Text( - "Activity", modifier = Modifier.align(Alignment.Center), + tr("Activity"), modifier = Modifier.align(Alignment.Center), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, ) } @@ -362,12 +364,12 @@ fun ActivityScoreScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenActivit } result?.let { ContributorsCard(it.contributors) } Text( - "Open today's activity", + tr("Open today's activity"), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.steps, modifier = Modifier.clip(RoundedCornerShape(4.dp)).clickable(onClick = onOpenActivity).padding(8.dp), ) Text( - "Activity is estimated by PulseLoop from your ring's steps and the workouts you log. It is not a medical measurement.", + tr("Activity is estimated by PulseLoop from your ring's steps and the workouts you log. It is not a medical measurement."), fontSize = 12.sp, color = PulseColors.textMuted, ) Spacer(Modifier.height(24.dp)) @@ -379,8 +381,8 @@ fun activityHeadline(result: com.pulseloop.service.ActivityScore.Result?): Strin if (result == null) return "No activity recorded yet. Sync your ring to see today's score." val weakest = result.contributors.minByOrNull { it.score }?.takeIf { it.score < 70 }?.title?.lowercase() return when (result.band) { - Readiness.Band.OPTIMAL -> "Great balance of movement and recovery. Keep it up." - Readiness.Band.GOOD -> "A solid active day so far." + Readiness.Band.OPTIMAL -> tr("Great balance of movement and recovery. Keep it up.") + Readiness.Band.GOOD -> tr("A solid active day so far.") Readiness.Band.FAIR, Readiness.Band.PAY_ATTENTION -> if (weakest != null) "There's room to move more. Start with your $weakest." else "There's room to move more today." } @@ -403,22 +405,22 @@ private fun DataBehindScore(db: PulseLoopDatabase, result: Readiness.Result?) { verticalArrangement = Arrangement.spacedBy(6.dp), ) { Row(verticalAlignment = Alignment.CenterVertically) { - Text("Data behind this score", fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, modifier = Modifier.weight(1f)) - Text(if (open) "Hide" else "Show", fontSize = 13.sp, color = PulseColors.accent) + Text(tr("Data behind this score"), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, modifier = Modifier.weight(1f)) + Text(if (open) tr("Hide") else tr("Show"), fontSize = 13.sp, color = PulseColors.accent) } if (open) { val night = inputs?.lastNight fun line(label: String, value: String) = label to value val rows = buildList { if (night != null) { - add(line("Night covered by the ring", "${(night.coverage * 100).roundToInt()}%")) - add(line("Heart-rate readings", "${night.hrSamples}")) - add(line("HRV readings", "${night.hrvSamples}")) - add(line("Resting heart rate", night.restingHr?.let { "${it.roundToInt()} bpm" } ?: "not measured")) + add(line(tr("Night covered by the ring"), "${(night.coverage * 100).roundToInt()}%")) + add(line(tr("Heart-rate readings"), "${night.hrSamples}")) + add(line(tr("HRV readings"), "${night.hrvSamples}")) + add(line(tr("Resting heart rate"), night.restingHr?.let { "${it.roundToInt()} bpm" } ?: "not measured")) add(line("HRV", night.hrv?.let { "${it.roundToInt()} ms" } ?: "not measured")) - } else add(line("Last night", "no sleep recorded")) - inputs?.let { add(line("Nights in your baseline", "${it.history.count { n -> n.restingHr != null || n.hrv != null }}")) } - add(line("Formula version", "${com.pulseloop.service.Algorithms.VERSION}")) + } else add(line(tr("Last night"), "no sleep recorded")) + inputs?.let { add(line(tr("Nights in your baseline"), "${it.history.count { n -> n.restingHr != null || n.hrv != null }}")) } + add(line(tr("Formula version"), "${com.pulseloop.service.Algorithms.VERSION}")) } rows.forEach { (k, v) -> Row(Modifier.fillMaxWidth()) { diff --git a/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt index 8c00a414..9cfad8c0 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.PulseColors import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.* @@ -26,7 +28,7 @@ import kotlinx.coroutines.delay */ @Composable fun RecordScreen( - activityName: String = "Workout", + activityName: String = tr("Workout"), elapsedSeconds: Int = 0, distanceMeters: Double = 0.0, heartRate: Int? = null, @@ -49,10 +51,10 @@ fun RecordScreen( val paceOrSpeedLabel: String val paceOrSpeedValue: String if (metricSet.showsSpeed) { - paceOrSpeedLabel = "Speed" + paceOrSpeedLabel = tr("Speed") paceOrSpeedValue = ActivityMeta.speed(distanceMeters, elapsedSeconds, units) ?: "—" } else { - paceOrSpeedLabel = "Pace" + paceOrSpeedLabel = tr("Pace") paceOrSpeedValue = ActivityMeta.pace(distanceMeters, elapsedSeconds, units) ?.let { it + ActivityMeta.paceUnit(units) } ?: "—" } @@ -64,13 +66,13 @@ fun RecordScreen( if (showLeaveDialog) { AlertDialog( onDismissRequest = { showLeaveDialog = false }, - title = { Text("Workout in progress") }, - text = { Text("Your workout is still recording. Finish it now, or keep recording?") }, + title = { Text(tr("Workout in progress")) }, + text = { Text(tr("Your workout is still recording. Finish it now, or keep recording?")) }, confirmButton = { - TextButton(onClick = { showLeaveDialog = false; onFinish() }) { Text("Finish") } + TextButton(onClick = { showLeaveDialog = false; onFinish() }) { Text(tr("Finish")) } }, dismissButton = { - TextButton(onClick = { showLeaveDialog = false }) { Text("Keep recording") } + TextButton(onClick = { showLeaveDialog = false }) { Text(tr("Keep recording")) } }, ) } @@ -103,7 +105,7 @@ fun RecordScreen( if (heartRateAdjusted) { Text("adjusted by your accuracy check", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } - Text(hrZone.label, style = MaterialTheme.typography.labelMedium, color = zoneColor) + Text(tr(hrZone.label), style = MaterialTheme.typography.labelMedium, color = zoneColor) } } Spacer(Modifier.height(12.dp)) @@ -118,13 +120,13 @@ fun RecordScreen( } else { "%.2f %s".format(UnitConverter.distance(distanceMeters, units), UnitConverter.distanceUnit(units)) } - StatTile("Distance", distText) + StatTile(tr("Distance"), distText) } } if (useGps && (metricSet.showsPace || metricSet.showsSpeed)) { item { StatTile(paceOrSpeedLabel, paceOrSpeedValue) } } - item { StatTile("SpO₂", spO2?.let { "$it%" } ?: "--") } + item { StatTile(tr("SpO₂"), spO2?.let { "$it%" } ?: "--") } } Spacer(Modifier.weight(1f)) @@ -135,19 +137,19 @@ fun RecordScreen( Button(onClick = onResume, Modifier.weight(1f).height(52.dp)) { Icon(Icons.Filled.PlayArrow, null) Spacer(Modifier.width(8.dp)) - Text("Resume") + Text(tr("Resume")) } } else { OutlinedButton(onClick = onPause, Modifier.weight(1f).height(52.dp)) { Icon(Icons.Filled.Pause, null) Spacer(Modifier.width(8.dp)) - Text("Pause") + Text(tr("Pause")) } } Button(onClick = onFinish, Modifier.weight(1f).height(52.dp), colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error)) { Icon(Icons.Filled.Stop, null) Spacer(Modifier.width(8.dp)) - Text("Finish") + Text(tr("Finish")) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt index 4f54bbdc..d13b767a 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -156,11 +158,11 @@ fun VitalsScreen( ZoneLineChart( samples = c.samples, zones = c.zones, yDomain = c.yDomain, accent = ZonePalette.accent(MetricKind.HEART_RATE), - label = "Heart rate", + label = tr("Heart rate"), referenceBands = c.referenceBands, dashedRules = c.dashedRules, ) } else { - Text("No HR samples yet — sync your ring to start your trend.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("No HR samples yet — sync your ring to start your trend."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } } DashboardCard.SPO2 -> VitalCard( @@ -172,12 +174,12 @@ fun VitalsScreen( ZoneLineChart( samples = c.samples, zones = c.zones, yDomain = c.yDomain, accent = ZonePalette.accent(MetricKind.SPO2), - label = "Blood oxygen", + label = tr("Blood oxygen"), referenceBands = c.referenceBands, dashedRules = c.dashedRules, showPoints = true, ) } else { - Text("No SpO₂ samples yet — take a reading to start your trend.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("No SpO₂ samples yet — take a reading to start your trend."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } } DashboardCard.BLOOD_PRESSURE -> VitalCard( @@ -192,23 +194,23 @@ fun VitalsScreen( horizontalArrangement = Arrangement.spacedBy(16.dp), ) { BpGaugeColumn( - title = "Systolic", value = sys, domain = 80.0..190.0, + title = tr("Systolic"), value = sys, domain = 80.0..190.0, zones = cards.getValue(MetricKind.BLOOD_PRESSURE).zones, fallback = ZonePalette.accent(MetricKind.BLOOD_PRESSURE), modifier = Modifier.weight(1f), ) BpGaugeColumn( - title = "Diastolic", value = dia, domain = 50.0..130.0, + title = tr("Diastolic"), value = dia, domain = 50.0..130.0, zones = com.pulseloop.service.VitalsThresholdEngine.diastolicReferenceZones(), fallback = ZonePalette.accent(MetricKind.BLOOD_PRESSURE).copy(alpha = 0.7f), modifier = Modifier.weight(1f), ) } } else { - Text("No blood pressure data yet.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("No blood pressure data yet."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } if (measuring) { - Text("Measuring… updates when complete", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) + Text(tr("Measuring… updates when complete"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) } } DashboardCard.HRV -> VitalCard( @@ -224,7 +226,7 @@ fun VitalsScreen( referenceBands = c.referenceBands, dashedRules = c.dashedRules, ) } else { - Text("No HRV data yet — HRV builds up over a few hours of wear.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("No HRV data yet — HRV builds up over a few hours of wear."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } } DashboardCard.STRESS -> VitalGaugeCardItem( @@ -234,22 +236,22 @@ fun VitalsScreen( // scores below 10 — so the floor would hide exactly the reading it was asked for. hasReading = state.stressSamples.isNotEmpty() && (state.stressIsDerived || (state.latestStress?.toInt() ?: 0) >= 10), - emptyText = "No stress data yet — take a measurement.", + emptyText = tr("No stress data yet — take a measurement."), // Issue #67: say so on the card itself. A derived figure presented as a measurement // would be worse than the empty card it replaces. - footnote = if (state.stressIsDerived) "Estimated from HRV — your ring doesn't measure stress" else null, + footnote = if (state.stressIsDerived) tr("Estimated from HRV — your ring doesn't measure stress") else null, onTap = { navController?.navigate("vitals/stress") }, ) DashboardCard.FATIGUE -> VitalGaugeCardItem( card = cards.getValue(MetricKind.FATIGUE), hasReading = state.fatigueSamples.isNotEmpty() && (state.latestFatigue?.toInt() ?: 0) >= 10, - emptyText = "No fatigue data yet — take a measurement.", + emptyText = tr("No fatigue data yet — take a measurement."), onTap = { navController?.navigate("vitals/fatigue") }, ) DashboardCard.GLUCOSE -> VitalGaugeCardItem( card = cards.getValue(MetricKind.GLUCOSE), hasReading = state.bloodSugar != null, - emptyText = "No blood sugar data yet.", + emptyText = tr("No blood sugar data yet."), measuring = measuring, onTap = { navController?.navigate("vitals/glucose") }, ) @@ -263,11 +265,11 @@ fun VitalsScreen( ZoneLineChart( samples = c.samples, zones = c.zones, yDomain = c.yDomain, accent = ZonePalette.accent(MetricKind.TEMPERATURE), - label = "Temperature", + label = tr("Temperature"), referenceBands = c.referenceBands, dashedRules = c.dashedRules, ) } else { - Text("No temperature data yet — temperature trends appear after overnight wear.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("No temperature data yet — temperature trends appear after overnight wear."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } } else -> {} @@ -285,8 +287,8 @@ fun VitalsScreen( item { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Vitals", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold) - Text("Live measurements and trends", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Vitals"), style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold) + Text(tr("Live measurements and trends"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) state.adjustedNote?.let { AdjustedCaption(it) } } // Measure button: combined (0x23) for 56ff/Jring, or sequential live @@ -357,7 +359,7 @@ fun VitalsScreen( // A ring that streams HRV gets it on its own control in the row below. val hrvOnRemaining = coordinator.canMeasureHrv && !coordinator.streamsSpotVitals val remainingLegsLabel = when { - coordinator.canMeasureBloodPressure && hrvOnRemaining -> "BP & HRV" + coordinator.canMeasureBloodPressure && hrvOnRemaining -> tr("BP & HRV") coordinator.canMeasureBloodPressure -> "BP" hrvOnRemaining -> "HRV" else -> null @@ -377,7 +379,7 @@ fun VitalsScreen( onClick = { runMeasurement( coordinator.heartRateMeasureSeconds, "HR", - caption = "Keep still — measuring heart rate…", + caption = tr("Keep still — measuring heart rate…"), failed = { coordinator.hrState == failedState }, ) { coordinator.measureHeartRateOnly() } }, @@ -391,14 +393,14 @@ fun VitalsScreen( enabled = !measuring, onClick = { runMeasurement( - coordinator.spo2OnlyMeasureSeconds, "SpO₂", - caption = "Keep still — measuring blood oxygen…", + coordinator.spo2OnlyMeasureSeconds, tr("SpO₂"), + caption = tr("Keep still — measuring blood oxygen…"), failed = { coordinator.spo2State == failedState }, ) { coordinator.measureSpO2Only() } }, ) { Text( - if (measuring && measuringLabel == "SpO₂") "SpO₂ ${remaining}s" else "SpO₂", + if (measuring && measuringLabel == "SpO₂") "SpO₂ ${remaining}s" else tr("SpO₂"), color = androidx.compose.ui.graphics.Color.Unspecified, ) } @@ -457,9 +459,9 @@ fun VitalsScreen( runMeasurement( measureSeconds, "all", caption = if (combinedMode) - "Keep still — measuring blood pressure, SpO₂, stress, fatigue & blood sugar…" + tr("Keep still — measuring blood pressure, SpO₂, stress, fatigue & blood sugar…") else - "Keep still — measuring heart rate & SpO₂…", + tr("Keep still — measuring heart rate & SpO₂…"), failed = { !combinedMode && (coordinator.hrState == failedState || coordinator.spo2State == failedState) @@ -470,7 +472,7 @@ fun VitalsScreen( }, ) { Text( - if (measuring) "Measuring… ${remaining}s" else "Measure", + if (measuring) "Measuring… ${remaining}s" else tr("Measure"), color = androidx.compose.ui.graphics.Color.Unspecified, ) } @@ -503,11 +505,11 @@ fun VitalsScreen( Text( when { measureDisconnectedHint -> - "The ring disconnected during measurement." + tr("The ring disconnected during measurement.") measureNotWornHint -> - "The ring isn't detecting your finger. Put it on snugly, then try again." + tr("The ring isn't detecting your finger. Put it on snugly, then try again.") else -> - "Couldn't get a steady reading. Keep the ring snug and your hand still, then try again." + tr("Couldn't get a steady reading. Keep the ring snug and your hand still, then try again.") }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, @@ -595,7 +597,7 @@ private fun VitalGaugeCardItem( Text(emptyText, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } if (measuring) { - Text("Measuring… updates when complete", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) + Text(tr("Measuring… updates when complete"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) } } } @@ -670,7 +672,7 @@ fun VitalDetailScreen( // edge, title centered. Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") + Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } Text( title, @@ -727,7 +729,7 @@ fun VitalDetailScreen( ) Row(verticalAlignment = Alignment.CenterVertically) { IconButton(onClick = { vm.prev() }) { - Icon(Icons.Filled.ChevronLeft, "Previous", tint = PulseColors.textMuted) + Icon(Icons.Filled.ChevronLeft, tr("Previous"), tint = PulseColors.textMuted) } Text( text = dateLabel(state.anchor, state.period), @@ -740,7 +742,7 @@ fun VitalDetailScreen( enabled = vm.canGoForward(), ) { Icon( - Icons.Filled.ChevronRight, "Next", + Icons.Filled.ChevronRight, tr("Next"), tint = if (vm.canGoForward()) PulseColors.textMuted else PulseColors.textMuted.copy(alpha = 0.3f), ) } @@ -752,7 +754,7 @@ fun VitalDetailScreen( contentAlignment = Alignment.Center, ) { Text( - "Not enough data for this period.", + tr("Not enough data for this period."), fontSize = 13.sp, color = PulseColors.textMuted, ) @@ -765,8 +767,8 @@ fun VitalDetailScreen( ?: MaterialTheme.colorScheme.primary, secondary = state.secondary, colorSecondary = ZonePalette.accent(MetricKind.BLOOD_PRESSURE).copy(alpha = 0.5f), - legendPrimary = if (state.isBP) "Systolic" else null, - legendSecondary = if (state.isBP) "Diastolic" else null, + legendPrimary = if (state.isBP) tr("Systolic") else null, + legendSecondary = if (state.isBP) tr("Diastolic") else null, // Points arrive in display units from the VM; convert the zone/axis // reference to match so temp bands (°F) and glucose bands (mmol/L) // line up with the plotted line (iOS #43 §2/§3). @@ -780,7 +782,7 @@ fun VitalDetailScreen( ) if (state.usualRange != null) { Text( - "Shaded: your usual range over the last 30 days", + tr("Shaded: your usual range over the last 30 days"), fontSize = 11.sp, color = PulseColors.textMuted, modifier = Modifier.padding(top = 6.dp), @@ -802,13 +804,13 @@ fun VitalDetailScreen( .padding(horizontal = 10.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically, ) { - DetailStat("Latest", state.latest?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) + DetailStat(tr("Latest"), state.latest?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) DetailStatDivider() - DetailStat("Average", state.avg?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) + DetailStat(tr("Average"), state.avg?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) DetailStatDivider() - DetailStat("Min", state.min?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) + DetailStat(tr("Min"), state.min?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) DetailStatDivider() - DetailStat("Max", state.max?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) + DetailStat(tr("Max"), state.max?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) } } @@ -842,7 +844,7 @@ fun VitalDetailScreen( verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text( - "REFERENCE ZONES", + tr("REFERENCE ZONES"), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, @@ -859,7 +861,7 @@ fun VitalDetailScreen( .background(zone.colorToken.toColor(), CircleShape), ) Text( - zone.label, + tr(zone.label), fontSize = 13.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, @@ -889,7 +891,7 @@ fun VitalDetailScreen( verticalArrangement = Arrangement.spacedBy(6.dp), ) { Text( - "WHAT THIS MEANS", + tr("WHAT THIS MEANS"), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, @@ -980,9 +982,9 @@ private fun ReadingsCard( .fillMaxWidth() .clickable( role = Role.Button, - onClickLabel = if (expanded) "Hide readings" else "Show readings", + onClickLabel = if (expanded) tr("Hide readings") else tr("Show readings"), ) { expanded = !expanded } - .semantics { stateDescription = if (expanded) "Expanded" else "Collapsed" } + .semantics { stateDescription = if (expanded) tr("Expanded") else tr("Collapsed") } .padding(16.dp), verticalAlignment = Alignment.CenterVertically, ) { @@ -1038,7 +1040,7 @@ private fun ReadingsCard( IconButton(onClick = { pendingDelete = reading }) { Icon( Icons.Filled.DeleteOutline, - contentDescription = "Delete this reading", + contentDescription = tr("Delete this reading"), tint = PulseColors.textMuted, modifier = Modifier.size(18.dp), ) @@ -1060,7 +1062,7 @@ private fun ReadingsCard( pendingDelete?.let { reading -> AlertDialog( onDismissRequest = { pendingDelete = null }, - title = { Text("Delete this reading?") }, + title = { Text(tr("Delete this reading?")) }, text = { Text( buildString { @@ -1072,7 +1074,7 @@ private fun ReadingsCard( // Say so plainly rather than letting a user wonder why the reading // didn't come back after a re-sync — that is deliberate. if (reading.fromHistory) { - append(" The reading stays deleted the next time this day syncs.") + append(tr(" The reading stays deleted the next time this day syncs.")) } }, ) @@ -1081,10 +1083,10 @@ private fun ReadingsCard( TextButton(onClick = { onDelete(reading) pendingDelete = null - }) { Text("Delete", color = MaterialTheme.colorScheme.error) } + }) { Text(tr("Delete"), color = MaterialTheme.colorScheme.error) } }, dismissButton = { - TextButton(onClick = { pendingDelete = null }) { Text("Cancel") } + TextButton(onClick = { pendingDelete = null }) { Text(tr("Cancel")) } }, ) } @@ -1199,49 +1201,49 @@ private fun zoneRangeText( */ private fun metricDisclaimer(metric: String, isDerived: Boolean): String? = when { metric == "stress" && isDerived -> - "Estimated from HRV — your ring doesn't measure stress. Scored against your own recent " + + tr("Estimated from HRV — your ring doesn't measure stress. Scored against your own recent " + "HRV readings, so it says how this reading compares with your normal, not how you compare " + - "with anyone else." + "with anyone else.") metric == "glucose" -> - "Estimated wellness metric — not for dosing or diabetes decisions. No smart ring or watch is " + - "FDA-authorized to measure or estimate glucose on its own." + tr("Estimated wellness metric — not for dosing or diabetes decisions. No smart ring or watch is " + + "FDA-authorized to measure or estimate glucose on its own.") metric == "bp" -> - "Ring blood pressure is an estimate. Calibrate against a validated cuff in Settings → Calibration, " + - "and talk to a clinician about persistent high or low readings." + tr("Ring blood pressure is an estimate. Calibrate against a validated cuff in Settings → Calibration, " + + "and talk to a clinician about persistent high or low readings.") else -> null } /** Detail titles use MetricKind.title's sentence case (iOS navigation titles). */ private fun metricDisplayName(metric: String): String = when (metric) { - "hr" -> "Heart rate" - "spo2" -> "Blood oxygen" - "stress" -> "Stress" - "fatigue" -> "Fatigue" + "hr" -> tr("Heart rate") + "spo2" -> tr("Blood oxygen") + "stress" -> tr("Stress") + "fatigue" -> tr("Fatigue") "hrv" -> "HRV" - "temp" -> "Skin temperature" - "bp" -> "Blood pressure" - "glucose" -> "Blood sugar" + "temp" -> tr("Skin temperature") + "bp" -> tr("Blood pressure") + "glucose" -> tr("Blood sugar") else -> metric } /** "WHAT THIS MEANS" copy, verbatim from iOS MetricDetailView `explainerText`. */ private fun metricExplainer(metric: String): String = when (metric) { - "hr" -> "Resting heart rate reflects how hard your heart works at rest. A typical adult range is 60–100 bpm; " + - "fitness, medication, caffeine, and stress all shift it." - "spo2" -> "Blood oxygen (SpO₂) is the percentage of oxygen your blood carries. 95–100% is normal; " + - "altitude and lung conditions can lower it." - "hrv" -> "Heart-rate variability is the variation between beats. It's highly individual, so we track it " + - "against your personal baseline rather than a universal cutoff." - "bp" -> "Blood pressure is systolic over diastolic (mmHg). The category is the worse of the two. " + - "A ring estimate is not a substitute for a cuff." - "stress" -> "A device wellness score from 0–100 based on heart-rate patterns. Lower is calmer. " + - "It's an estimate, not a medical stress measure." - "fatigue" -> "A device wellness score from 0–100 estimating tiredness. Higher means more fatigue. " + - "It's a ring estimate, not a clinical scale." - "glucose" -> "An estimated glucose value. No smart ring is cleared to measure glucose, so treat this " + - "as a wellness estimate only." - "temp" -> "Skin temperature from the ring runs cooler than core body temperature. " + - "Trends over time matter more than any single reading." + "hr" -> tr("Resting heart rate reflects how hard your heart works at rest. A typical adult range is 60–100 bpm; " + + "fitness, medication, caffeine, and stress all shift it.") + "spo2" -> tr("Blood oxygen (SpO₂) is the percentage of oxygen your blood carries. 95–100% is normal; " + + "altitude and lung conditions can lower it.") + "hrv" -> tr("Heart-rate variability is the variation between beats. It's highly individual, so we track it " + + "against your personal baseline rather than a universal cutoff.") + "bp" -> tr("Blood pressure is systolic over diastolic (mmHg). The category is the worse of the two. " + + "A ring estimate is not a substitute for a cuff.") + "stress" -> tr("A device wellness score from 0–100 based on heart-rate patterns. Lower is calmer. " + + "It's an estimate, not a medical stress measure.") + "fatigue" -> tr("A device wellness score from 0–100 estimating tiredness. Higher means more fatigue. " + + "It's a ring estimate, not a clinical scale.") + "glucose" -> tr("An estimated glucose value. No smart ring is cleared to measure glucose, so treat this " + + "as a wellness estimate only.") + "temp" -> tr("Skin temperature from the ring runs cooler than core body temperature. " + + "Trends over time matter more than any single reading.") else -> "" } diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt index 4833cbcf..32d61b28 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll @@ -54,24 +56,24 @@ fun SettingsScreen( // Provider-aware AI Coach summary — mirrors iOS `coachTrailing` (no Apple on-device // mode on Android; hosted providers show the selected model slug). - val coachTrailing = if (!coachEnabled) "Off" else when (providerStore.providerMode) { - CoachProviderMode.OFFLINE_STUB -> "Offline" + val coachTrailing = if (!coachEnabled) tr("Off") else when (providerStore.providerMode) { + CoachProviderMode.OFFLINE_STUB -> tr("Offline") CoachProviderMode.USER_GEMINI_KEY -> providerStore.geminiModel CoachProviderMode.USER_OPENROUTER_KEY -> providerStore.openRouterModel CoachProviderMode.USER_MINIMAX_KEY -> providerStore.minimaxModel // Local: the model name, or just "Local" for a server (llama.cpp) that ignores the field. CoachProviderMode.LOCAL_OPENAI_COMPAT -> - providerStore.localModel.ifBlank { "Local" } - CoachProviderMode.BACKEND_PROXY -> "Backend proxy" + providerStore.localModel.ifBlank { tr("Local") } + CoachProviderMode.BACKEND_PROXY -> tr("Backend proxy") else -> keyStore.model } - val notificationsTrailing = if (keyStore.notificationsEnabled) "On" else "Off" + val notificationsTrailing = if (keyStore.notificationsEnabled) tr("On") else tr("Off") val openCheck by db.accuracyDao().openFlow().collectAsState(initial = null) val accuracyTrailing = openCheck?.let { c -> if (c.state == com.pulseloop.data.entity.AccuracyCheckEntity.STATE_RUNNING) { val (day, total) = AccuracyUiText.dayOf(c) "Day $day of $total" - } else "Report ready" + } else tr("Report ready") } fun navigate(route: String) { @@ -82,7 +84,7 @@ fun SettingsScreen( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(20.dp), ) { - Text("Settings", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold) + Text(tr("Settings"), style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold) val hcSource by remember { com.pulseloop.health.source.HealthConnectSource.activeSource(context) }.collectAsState() if (hcSource != null) { @@ -103,13 +105,13 @@ fun SettingsScreen( // AI COACH — check-ins are a coach sub-feature, only shown once the coach is on. SettingsSection( - title = "AI Coach", + title = tr("AI Coach"), rows = buildList { - add(SettingsRowItem(Icons.Filled.AutoAwesome, PulseColors.accent, "AI Coach", coachTrailing) { + add(SettingsRowItem(Icons.Filled.AutoAwesome, PulseColors.accent, tr("AI Coach"), coachTrailing) { navigate("settings/coach") }) if (coachEnabled) { - add(SettingsRowItem(Icons.Filled.NotificationsActive, PulseColors.warning, "Coach Check-Ins", notificationsTrailing) { + add(SettingsRowItem(Icons.Filled.NotificationsActive, PulseColors.warning, tr("Coach Check-Ins"), notificationsTrailing) { navigate("settings/checkins") }) } @@ -122,16 +124,19 @@ fun SettingsScreen( // MEASUREMENT_INTERVAL, so the generic 56ff jring never shows this row (iOS #74: dropped the // old ring-only "Device" section for this since the row had no other members). SettingsSection( - title = "General", + title = tr("General"), rows = buildList { - add(SettingsRowItem(Icons.Filled.AccountCircle, PulseColors.accent, "User Profile") { + add(SettingsRowItem(Icons.Filled.AccountCircle, PulseColors.accent, tr("User Profile")) { navigate("settings/profile") }) - add(SettingsRowItem(Icons.Filled.MonitorHeart, PulseColors.hrv, "Physiology") { + add(SettingsRowItem(Icons.Filled.MonitorHeart, PulseColors.hrv, tr("Physiology")) { navigate("settings/physiology") }) + add(SettingsRowItem(Icons.Filled.Language, PulseColors.info, tr("Language"), com.pulseloop.ui.i18n.L10n.language.let { if (it == com.pulseloop.ui.i18n.AppLanguage.SYSTEM) tr("System default") else it.label }) { + navigate("settings/language") + }) if (capabilities.contains(WearableCapability.MEASUREMENT_INTERVAL)) { - add(SettingsRowItem(Icons.Filled.Timer, PulseColors.spo2, "Measurement Frequency") { + add(SettingsRowItem(Icons.Filled.Timer, PulseColors.spo2, tr("Measurement Frequency")) { navigate("settings/measurement") }) } @@ -140,15 +145,15 @@ fun SettingsScreen( // METRICS SettingsSection( - title = "Metrics", + title = tr("Metrics"), rows = listOf( - SettingsRowItem(Icons.Filled.TrackChanges, PulseColors.readiness, "Goals") { + SettingsRowItem(Icons.Filled.TrackChanges, PulseColors.readiness, tr("Goals")) { navigate("settings/goals") }, - SettingsRowItem(Icons.Filled.RestaurantMenu, PulseColors.calories, "Nutrition") { + SettingsRowItem(Icons.Filled.RestaurantMenu, PulseColors.calories, tr("Nutrition")) { navigate("settings/nutrition") }, - SettingsRowItem(Icons.Filled.LocalBar, PulseColors.drinks, "Drinks") { + SettingsRowItem(Icons.Filled.LocalBar, PulseColors.drinks, tr("Drinks")) { navigate("drinks") }, ), @@ -157,36 +162,36 @@ fun SettingsScreen( // RESOURCES — Calibration is jring-only (Colmi rings measure neither BP nor blood // sugar); Developer is hidden until unlocked by tapping the version 7× in About. SettingsSection( - title = "Resources", + title = tr("Resources"), rows = buildList { if (capabilities.contains(WearableCapability.BLOOD_PRESSURE) || capabilities.contains(WearableCapability.BLOOD_SUGAR) ) { - add(SettingsRowItem(Icons.Filled.Tune, PulseColors.bloodPressure, "Calibration") { + add(SettingsRowItem(Icons.Filled.Tune, PulseColors.bloodPressure, tr("Calibration")) { navigate("settings/calibration") }) } if (developerUnlocked) { - add(SettingsRowItem(Icons.Filled.BugReport, PulseColors.danger, "Developer") { + add(SettingsRowItem(Icons.Filled.BugReport, PulseColors.danger, tr("Developer")) { navigate("debug") }) } - add(SettingsRowItem(Icons.Filled.Shield, PulseColors.success, "Privacy & Data") { + add(SettingsRowItem(Icons.Filled.Shield, PulseColors.success, tr("Privacy & Data")) { navigate("settings/privacy") }) - add(SettingsRowItem(Icons.Filled.TrendingUp, PulseColors.calories, "Strava") { + add(SettingsRowItem(Icons.Filled.TrendingUp, PulseColors.calories, tr("Strava")) { navigate("settings/strava") }) - add(SettingsRowItem(Icons.Filled.Sync, PulseColors.success, "Health Connect") { + add(SettingsRowItem(Icons.Filled.Sync, PulseColors.success, tr("Health Connect")) { navigate("settings/health-connect") }) - add(SettingsRowItem(Icons.Filled.Watch, PulseColors.info, "Use without a ring") { + add(SettingsRowItem(Icons.Filled.Watch, PulseColors.info, tr("Use without a ring")) { navigate("settings/hc-source") }) - add(SettingsRowItem(Icons.Filled.Verified, PulseColors.info, "Accuracy check", accuracyTrailing) { + add(SettingsRowItem(Icons.Filled.Verified, PulseColors.info, tr("Accuracy check"), accuracyTrailing) { navigate("settings/accuracy-check") }) - add(SettingsRowItem(Icons.Filled.Info, PulseColors.textMuted, "About PulseLoop") { + add(SettingsRowItem(Icons.Filled.Info, PulseColors.textMuted, tr("About PulseLoop")) { navigate("settings/about") }) }, diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index b6dab642..db71e146 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.components.switchRow import com.pulseloop.ui.theme.dither @@ -120,7 +122,7 @@ internal fun SettingsSubScreen( title = { Text(title) }, navigationIcon = { IconButton(onClick = onBack) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") + Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } }, windowInsets = WindowInsets(0, 0, 0, 0), @@ -215,11 +217,11 @@ fun CoachSettingsScreen(onBack: () -> Unit) { // / o4-mini are gone from it (issue #77), and a stored one reads as the default. val models = com.pulseloop.coach.config.OpenAIModel.entries.map { it.slug to it.blurb } - SettingsSubScreen(title = "AI Coach", onBack = onBack) { + SettingsSubScreen(title = tr("AI Coach"), onBack = onBack) { // AI Coach section — ported from CoachSettingsSection.swift Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("AI Coach", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("AI Coach"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) // Readiness differs by provider: the local mode is gated by the server address, // not a key, so the old key-only check told a correctly-configured user their @@ -230,9 +232,9 @@ fun CoachSettingsScreen(onBack: () -> Unit) { else selectedModel Text( if (coachEnabled && ready) "Active — $activeModel" - else if (coachEnabled && isLocal) "Server address needed" - else if (coachEnabled) "API key needed" - else "Disabled", + else if (coachEnabled && isLocal) tr("Server address needed") + else if (coachEnabled) tr("API key needed") + else tr("Disabled"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -252,14 +254,14 @@ fun CoachSettingsScreen(onBack: () -> Unit) { askEnableCheckIns = true } }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text("Enable AI Coach") + Text(tr("Enable AI Coach")) Switch(checked = coachEnabled, onCheckedChange = null) } if (checkInPermissionDenied) { Spacer(Modifier.height(4.dp)) Text( - "Notifications are off for PulseLoop. Turn them on in Android Settings to get check-ins.", + tr("Notifications are off for PulseLoop. Turn them on in Android Settings to get check-ins."), style = MaterialTheme.typography.bodySmall, color = PulseColors.danger, ) @@ -313,9 +315,9 @@ fun CoachSettingsScreen(onBack: () -> Unit) { CoachProviderMode.USER_MINIMAX_KEY to "MiniMax", CoachProviderMode.LOCAL_OPENAI_COMPAT to "Local / self-hosted (no key needed)", ) - val providerLabel = providerOptions.firstOrNull { it.first == providerMode }?.second ?: "OpenAI" + val providerLabel = providerOptions.firstOrNull { it.first == providerMode }?.second ?: tr("OpenAI") - Text("Provider", style = MaterialTheme.typography.labelMedium) + Text(tr("Provider"), style = MaterialTheme.typography.labelMedium) Spacer(Modifier.height(4.dp)) var providerExpanded by remember { mutableStateOf(false) } Box { @@ -362,7 +364,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { IconButton(onClick = onVisibility) { Icon( if (visible) Icons.Filled.VisibilityOff else Icons.Filled.Visibility, - contentDescription = if (visible) "Hide key" else "Show key" + contentDescription = if (visible) tr("Hide key") else tr("Show key") ) } }, @@ -370,15 +372,15 @@ fun CoachSettingsScreen(onBack: () -> Unit) { ) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { Button(onClick = save, enabled = value.isNotBlank(), modifier = Modifier.weight(1f)) { - Text(if (saved) "Update Key" else "Save Key") + Text(if (saved) tr("Update Key") else tr("Save Key")) } if (saved) { - OutlinedButton(onClick = onRemove, modifier = Modifier.weight(1f)) { Text("Remove") } + OutlinedButton(onClick = onRemove, modifier = Modifier.weight(1f)) { Text(tr("Remove")) } } } if (justSaved) { Text( - "Saved ✓", + tr("Saved ✓"), style = MaterialTheme.typography.bodySmall, color = PulseColors.success, modifier = Modifier.padding(top = 4.dp), @@ -411,14 +413,14 @@ fun CoachSettingsScreen(onBack: () -> Unit) { when (providerMode) { CoachProviderMode.USER_GEMINI_KEY -> { CoachModelPicker( - provider = providerMode, providerName = "Gemini", selected = geminiModel, + provider = providerMode, providerName = tr("Gemini"), selected = geminiModel, presets = GeminiModel.entries.map { it.slug to it.blurb }, savedKey = keySaves.let { providerStore.geminiApiKey }, onPick = { geminiModel = it; providerStore.geminiModel = it }, onListing = { liveListing = it }, ) KeyField( - label = "Gemini API Key", value = geminiKey, visible = geminiKeyVisible, + label = tr("Gemini API Key"), value = geminiKey, visible = geminiKeyVisible, saved = providerStore.hasGeminiKey, onValue = { geminiKey = it }, onVisibility = { geminiKeyVisible = !geminiKeyVisible }, onSave = { providerStore.geminiApiKey = geminiKey; keySaves++ }, @@ -427,7 +429,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { } CoachProviderMode.USER_OPENROUTER_KEY -> { CoachModelPicker( - provider = providerMode, providerName = "OpenRouter", selected = orModel, + provider = providerMode, providerName = tr("OpenRouter"), selected = orModel, presets = OpenRouterModel.entries.map { it.slug to it.blurb }, savedKey = keySaves.let { providerStore.openRouterApiKey }, onPick = { orModel = it; providerStore.openRouterModel = it }, @@ -438,13 +440,13 @@ fun CoachSettingsScreen(onBack: () -> Unit) { OutlinedTextField( value = orModel, onValueChange = { orModel = it; providerStore.openRouterModel = it }, - label = { Text("Custom model slug (vendor/model)") }, + label = { Text(tr("Custom model slug (vendor/model)")) }, modifier = Modifier.fillMaxWidth(), singleLine = true, ) Spacer(Modifier.height(8.dp)) KeyField( - label = "OpenRouter API Key", value = orKey, visible = orKeyVisible, + label = tr("OpenRouter API Key"), value = orKey, visible = orKeyVisible, saved = providerStore.hasOpenRouterKey, onValue = { orKey = it }, onVisibility = { orKeyVisible = !orKeyVisible }, onSave = { providerStore.openRouterApiKey = orKey; keySaves++ }, @@ -454,26 +456,26 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Row(Modifier.fillMaxWidth() .switchRow(checked = orPrivacy, onCheckedChange = { orPrivacy = it; providerStore.orPrivacyRouting = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Privacy routing") - Text("Only providers that don't retain data", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Privacy routing")) + Text(tr("Only providers that don't retain data"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } Switch(checked = orPrivacy, onCheckedChange = null) } ModelDropdown( - "Route by", orSort ?: "auto", + tr("Route by"), orSort ?: "auto", listOf("auto" to "Balanced (default)", "price" to "Cheapest first", "throughput" to "Fastest first", "latency" to "Lowest latency first"), ) { providerStore.orProviderSort = it.takeIf { s -> s != "auto" }; orSort = providerStore.orProviderSort } } CoachProviderMode.USER_MINIMAX_KEY -> { CoachModelPicker( - provider = providerMode, providerName = "MiniMax", selected = minimaxModel, + provider = providerMode, providerName = tr("MiniMax"), selected = minimaxModel, presets = MiniMaxModel.entries.map { it.slug to it.blurb }, savedKey = keySaves.let { providerStore.minimaxApiKey }, onPick = { minimaxModel = it; providerStore.minimaxModel = it }, onListing = { liveListing = it }, ) KeyField( - label = "MiniMax API Key", value = minimaxKey, visible = minimaxKeyVisible, + label = tr("MiniMax API Key"), value = minimaxKey, visible = minimaxKeyVisible, saved = providerStore.hasMinimaxKey, onValue = { minimaxKey = it }, onVisibility = { minimaxKeyVisible = !minimaxKeyVisible }, onSave = { providerStore.minimaxApiKey = minimaxKey; keySaves++ }, @@ -493,7 +495,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { localProbeResult = null; localProbeOk = false localProbeNotes = emptyList(); localDiscovered = emptyList() }, - label = { Text("Server address") }, + label = { Text(tr("Server address")) }, placeholder = { Text("http://192.168.1.50:11434") }, modifier = Modifier.fillMaxWidth(), singleLine = true, @@ -502,8 +504,8 @@ fun CoachSettingsScreen(onBack: () -> Unit) { ) Text( urlProblem?.let { LocalEndpoint.message(it) } - ?: "Default ports — Ollama 11434 · LM Studio 1234 · llama.cpp 8080 · vLLM 8000 · SGLang 30000. " + - "The /v1 path is added for you.", + ?: tr("Default ports — Ollama 11434 · LM Studio 1234 · llama.cpp 8080 · vLLM 8000 · SGLang 30000. " + + "The /v1 path is added for you."), style = MaterialTheme.typography.bodySmall, color = if (urlProblem != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, @@ -565,18 +567,18 @@ fun CoachSettingsScreen(onBack: () -> Unit) { localProbeOk = false; localProbeResult = e.reason } catch (e: Exception) { localProbeOk = false - localProbeResult = e.message ?: "Couldn't reach the server." + localProbeResult = e.message ?: tr("Couldn't reach the server.") } localProbeBusy = false } }, enabled = localBaseUrl.isNotBlank() && urlProblem == null && !localProbeBusy, modifier = Modifier.fillMaxWidth(), - ) { Text(if (localProbeBusy) "Detecting…" else "Detect server & configure") } + ) { Text(if (localProbeBusy) tr("Detecting…") else tr("Detect server & configure")) } if (localProbeBusy) { Text( - "Sending three tiny test messages. This can take a minute if the model " + - "still has to load.", + tr("Sending three tiny test messages. This can take a minute if the model " + + "still has to load."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp), @@ -604,7 +606,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Spacer(Modifier.height(8.dp)) if (localDiscovered.isNotEmpty()) { ModelDropdown( - "Model", localModel.ifBlank { "Choose a model" }, + tr("Model"), localModel.ifBlank { tr("Choose a model") }, localDiscovered.map { it to "" }, ) { localModel = it; providerStore.localModel = it } } @@ -613,7 +615,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { OutlinedTextField( value = localModel, onValueChange = { localModel = it; providerStore.localModel = it }, - label = { Text("Model name") }, + label = { Text(tr("Model name")) }, placeholder = { Text("qwen3:8b") }, modifier = Modifier.fillMaxWidth(), singleLine = true, @@ -621,14 +623,14 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Spacer(Modifier.height(8.dp)) KeyField( - label = "API key (optional)", value = localKey, visible = localKeyVisible, + label = tr("API key (optional)"), value = localKey, visible = localKeyVisible, saved = providerStore.hasLocalKey, onValue = { localKey = it }, onVisibility = { localKeyVisible = !localKeyVisible }, onSave = { providerStore.localApiKey = localKey }, onRemove = { localKey = ""; providerStore.localApiKey = "" }, ) Text( - "Only needed if you started the server with --api-key. Leave blank otherwise.", + tr("Only needed if you started the server with --api-key. Leave blank otherwise."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -639,10 +641,10 @@ fun CoachSettingsScreen(onBack: () -> Unit) { localToolCalling = it; providerStore.localToolCalling = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Tool calling") + Text(tr("Tool calling")) Text( - "Lets the coach read your data. Detect sets this for you; turn it off " + - "if your server rejects tools (vLLM needs --enable-auto-tool-choice).", + tr("Lets the coach read your data. Detect sets this for you; turn it off " + + "if your server rejects tools (vLLM needs --enable-auto-tool-choice)."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -652,7 +654,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Spacer(Modifier.height(8.dp)) ModelDropdown( - "Response format", localStructured.label, + tr("Response format"), localStructured.label, LocalStructuredOutput.entries.map { it.label to it.blurb }, ) { picked -> val mode = LocalStructuredOutput.entries.first { it.label == picked } @@ -666,7 +668,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { localMaxTokens = it.filter { c -> c.isDigit() } providerStore.localMaxTokens = localMaxTokens.toIntOrNull() ?: 0 }, - label = { Text("Max tokens") }, + label = { Text(tr("Max tokens")) }, placeholder = { Text("auto") }, modifier = Modifier.weight(1f), singleLine = true, @@ -678,7 +680,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { localTimeout = it.filter { c -> c.isDigit() } localTimeout.toIntOrNull()?.let { v -> providerStore.localTimeoutSeconds = v } }, - label = { Text("Timeout (s)") }, + label = { Text(tr("Timeout (s)")) }, modifier = Modifier .weight(1f) // The store clamps to 10..1800 on write, and a blank field @@ -696,8 +698,8 @@ fun CoachSettingsScreen(onBack: () -> Unit) { ) } Text( - "Leave max tokens blank to let the server decide. Raise the timeout for a large " + - "model on CPU — a slow reply is not retried.", + tr("Leave max tokens blank to let the server decide. Raise the timeout for a large " + + "model on CPU — a slow reply is not retried."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp), @@ -706,14 +708,14 @@ fun CoachSettingsScreen(onBack: () -> Unit) { else -> { // OpenAI (and legacy modes): the model picker + key field. CoachModelPicker( - provider = CoachProviderMode.USER_OPENAI_KEY, providerName = "OpenAI", selected = selectedModel, + provider = CoachProviderMode.USER_OPENAI_KEY, providerName = tr("OpenAI"), selected = selectedModel, presets = models, savedKey = keySaves.let { keyStore.apiKey }, onPick = { selectedModel = it; keyStore.model = it }, onListing = { liveListing = it }, ) KeyField( - label = "OpenAI API Key", value = apiKey, visible = apiKeyVisible, + label = tr("OpenAI API Key"), value = apiKey, visible = apiKeyVisible, saved = keyStore.apiKey.isNotBlank(), onValue = { apiKey = it }, onVisibility = { apiKeyVisible = !apiKeyVisible }, onSave = { keyStore.apiKey = apiKey; keySaves++ }, @@ -723,7 +725,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { } Spacer(Modifier.height(4.dp)) Text( - "Stored securely in Android Keystore. Never leaves your device except to call the model. Provider changes apply from your next message.", + tr("Stored securely in Android Keystore. Never leaves your device except to call the model. Provider changes apply from your next message."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -748,8 +750,8 @@ fun CoachSettingsScreen(onBack: () -> Unit) { val shownEffort = com.pulseloop.coach.config.ReasoningEfforts.resolve(effortProvider, effortModel, reasoningEffort, liveEntry) Spacer(Modifier.height(8.dp)) ModelDropdown( - "Reasoning effort", - com.pulseloop.coach.config.ReasoningEffort.fromRaw(shownEffort)?.label ?: "Default", + tr("Reasoning effort"), + com.pulseloop.coach.config.ReasoningEffort.fromRaw(shownEffort)?.label ?: tr("Default"), listOf("default" to "Model decides (default)") + effortOptions.map { it.rawValue to it.label }, ) { providerStore.reasoningEffort = it.takeIf { s -> s != "default" }; reasoningEffort = providerStore.reasoningEffort } } @@ -758,8 +760,8 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Row(Modifier.fillMaxWidth() .switchRow(checked = imageInput, onCheckedChange = { imageInput = it; providerStore.imageInputEnabled = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Image attachments") - Text("Attach photos to coach messages", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Image attachments")) + Text(tr("Attach photos to coach messages"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } Switch(checked = imageInput, onCheckedChange = null) } @@ -776,8 +778,8 @@ fun CoachSettingsScreen(onBack: () -> Unit) { webSearch = it; keyStore.webSearchEnabled = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Web Search") - Text("Uses additional tokens", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Web Search")) + Text(tr("Uses additional tokens"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } Switch(checked = webSearch, onCheckedChange = null) } @@ -787,8 +789,8 @@ fun CoachSettingsScreen(onBack: () -> Unit) { writeTools = it; keyStore.writeToolsEnabled = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Write Actions") - Text("Set goals, log, edit data", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Write Actions")) + Text(tr("Set goals, log, edit data"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } Switch(checked = writeTools, onCheckedChange = null) } @@ -797,16 +799,16 @@ fun CoachSettingsScreen(onBack: () -> Unit) { liveMeasurements = it; keyStore.liveMeasurementsEnabled = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Live Measurements") - Text("Trigger real-time ring readings", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Live Measurements")) + Text(tr("Trigger real-time ring readings"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } Switch(checked = liveMeasurements, onCheckedChange = null) } Row(Modifier.fillMaxWidth() .switchRow(checked = environmentContext, onCheckedChange = { setEnvironmentContext(it) }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Use location & weather") - Text("Grounds suggestions in your city's current weather", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Use location & weather")) + Text(tr("Grounds suggestions in your city's current weather"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } Switch(checked = environmentContext, onCheckedChange = null) } @@ -819,9 +821,9 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text("Coach Memory", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Coach Memory"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) TextButton(onClick = { showMemory = !showMemory }) { - Text(if (showMemory) "Hide" else "Show (${memories.size})") + Text(if (showMemory) tr("Hide") else "Show (${memories.size})") } } if (showMemory) { @@ -851,16 +853,16 @@ fun CoachSettingsScreen(onBack: () -> Unit) { memoryToDelete?.let { key -> AlertDialog( onDismissRequest = { memoryToDelete = null }, - title = { Text("Delete memory?") }, + title = { Text(tr("Delete memory?")) }, text = { Text("The coach will forget \"$key\". This can't be undone.") }, confirmButton = { TextButton(onClick = { memoryToDelete = null scope.launch { db.coachMemoryDao().deleteByKey(key) } - }) { Text("Delete", color = MaterialTheme.colorScheme.error) } + }) { Text(tr("Delete"), color = MaterialTheme.colorScheme.error) } }, dismissButton = { - TextButton(onClick = { memoryToDelete = null }) { Text("Cancel") } + TextButton(onClick = { memoryToDelete = null }) { Text(tr("Cancel")) } }, ) } @@ -868,13 +870,13 @@ fun CoachSettingsScreen(onBack: () -> Unit) { if (askEnableCheckIns) { AlertDialog( onDismissRequest = { askEnableCheckIns = false }, - title = { Text("Enable Coach Check-Ins?") }, - text = { Text("Get a daily check-in from your coach. You can change this anytime in Coach Check-Ins.") }, + title = { Text(tr("Enable Coach Check-Ins?")) }, + text = { Text(tr("Get a daily check-in from your coach. You can change this anytime in Coach Check-Ins.")) }, confirmButton = { - TextButton(onClick = { askEnableCheckIns = false; enableCheckIns() }) { Text("Enable") } + TextButton(onClick = { askEnableCheckIns = false; enableCheckIns() }) { Text(tr("Enable")) } }, dismissButton = { - TextButton(onClick = { askEnableCheckIns = false }) { Text("Not now") } + TextButton(onClick = { askEnableCheckIns = false }) { Text(tr("Not now")) } }, ) } @@ -951,14 +953,14 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { } } - SettingsSubScreen(title = "Coach Check-Ins", onBack = onBack) { + SettingsSubScreen(title = tr("Coach Check-Ins"), onBack = onBack) { if (!coachEnabled) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("AI Coach is off", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("AI Coach is off"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( - "Enable the AI Coach to change these — daily check-ins are written by the coach from your recent trends.", + tr("Enable the AI Coach to change these — daily check-ins are written by the coach from your recent trends."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -968,18 +970,18 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Daily check-ins", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Daily check-ins"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(12.dp)) Row(Modifier.fillMaxWidth() .switchRow(checked = notificationEnabled, enabled = coachEnabled, onCheckedChange = { setNotifications(it) }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text("Daily Check-in Notifications") + Text(tr("Daily Check-in Notifications")) Switch(checked = notificationEnabled, enabled = coachEnabled, onCheckedChange = null) } if (notifPermissionDenied) { Text( - "Notifications are disabled for PulseLoop in Android Settings.", + tr("Notifications are disabled for PulseLoop in Android Settings."), style = MaterialTheme.typography.bodySmall, color = PulseColors.danger, ) @@ -990,7 +992,7 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { // Morning time picker var morningHour by remember { mutableStateOf(keyStore.morningHour) } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text("Morning") + Text(tr("Morning")) var amExpanded by remember { mutableStateOf(false) } Box { OutlinedButton(enabled = coachEnabled, onClick = { amExpanded = true }) { @@ -1010,7 +1012,7 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { // Evening time picker var eveningHour by remember { mutableStateOf(keyStore.eveningHour) } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text("Evening") + Text(tr("Evening")) var pmExpanded by remember { mutableStateOf(false) } Box { OutlinedButton(enabled = coachEnabled, onClick = { pmExpanded = true }) { @@ -1034,14 +1036,14 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { scope.launch { CoachNotifications.showNow( context, - "PulseLoop Coach", - "This is a test check-in notification.", + tr("PulseLoop Coach"), + tr("This is a test check-in notification."), ) } }, modifier = Modifier.fillMaxWidth(), ) { - Text("Send Test Check-in Now") + Text(tr("Send Test Check-in Now")) } } } @@ -1051,22 +1053,22 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { // NotificationsSettingsView section): a local notification at <20% / <10%, once per day. Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Ring battery alerts", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Ring battery alerts"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( - "Get notified when your ring drops below 20% and 10%, so tracking doesn't stop mid-day.", + tr("Get notified when your ring drops below 20% and 10%, so tracking doesn't stop mid-day."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) Spacer(Modifier.height(12.dp)) Row(Modifier.fillMaxWidth() .switchRow(checked = batteryAlertsEnabled, onCheckedChange = { setBatteryAlerts(it) }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text("Low Battery Notifications") + Text(tr("Low Battery Notifications")) Switch(checked = batteryAlertsEnabled, onCheckedChange = null) } if (batteryPermDenied) { Text( - "Notifications are disabled for PulseLoop in Android Settings.", + tr("Notifications are disabled for PulseLoop in Android Settings."), style = MaterialTheme.typography.bodySmall, color = PulseColors.danger, ) @@ -1097,50 +1099,50 @@ private fun DailyGuidanceSettingsCard() { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { - Text("Daily guidance", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Daily guidance"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text( - "Built on your phone from your ring's data. No AI key needed.", + tr("Built on your phone from your ring's data. No AI key needed."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) GuidanceSwitch( - "Unusual signals alert", - "When two or more of last night's signals are outside your usual range.", + tr("Unusual signals alert"), + tr("When two or more of last night's signals are outside your usual range."), vitals, ) { vitals = it; prefs.vitalsAlerts = it } GuidanceSwitch( - "Weekly report", - "Sunday evening: your week compared with the last one, and one thing to focus on.", + tr("Weekly report"), + tr("Sunday evening: your week compared with the last one, and one thing to focus on."), weekly, ) { weekly = it; prefs.weeklyReport = it } GuidanceSwitch( - "Wind-down reminder", - "A nudge about 30 minutes before your suggested bedtime.", + tr("Wind-down reminder"), + tr("A nudge about 30 minutes before your suggested bedtime."), bedtime, ) { bedtime = it; prefs.bedtimeReminder = it } GuidanceSwitch( - "Meal reminder", - "Around lunch and dinner, only when nothing is logged yet. Needs nutrition tracking on.", + tr("Meal reminder"), + tr("Around lunch and dinner, only when nothing is logged yet. Needs nutrition tracking on."), meal, ) { meal = it; prefs.mealReminder = it } GuidanceSwitch( - "Charge before bed", - "When the ring is at 30% or less a couple of hours before your usual bedtime.", + tr("Charge before bed"), + tr("When the ring is at 30% or less a couple of hours before your usual bedtime."), battery, ) { battery = it; prefs.bedtimeBattery = it } GuidanceSwitch( - "Move reminder", - "Under 100 steps in an hour, 9:00 to 20:00, at most every two hours. Off in Rest Mode.", + tr("Move reminder"), + tr("Under 100 steps in an hour, 9:00 to 20:00, at most every two hours. Off in Rest Mode."), inactive, ) { inactive = it; prefs.inactivityAlerts = it } GuidanceSwitch( - "Step progress", - "Early evening, when you're under 70% of your step goal. Off in Rest Mode.", + tr("Step progress"), + tr("Early evening, when you're under 70% of your step goal. Off in Rest Mode."), progress, ) { progress = it; prefs.activityProgress = it } GuidanceSwitch( - "Medication reminders", - "Once per dose, at its time, for what you add in My Health → Medications & supplements.", + tr("Medication reminders"), + tr("Once per dose, at its time, for what you add in My Health → Medications & supplements."), medsOn, ) { medsOn = it; prefs.medReminders = it } } @@ -1184,10 +1186,10 @@ fun ProfileSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> Unit) ) } - SettingsSubScreen(title = "User Profile", onBack = onBack) { + SettingsSubScreen(title = tr("User Profile"), onBack = onBack) { Text( - "Your age, sex, height and weight let the ring compute accurate calories (and, on " + - "56ff/Jring rings, blood sugar). Blood pressure is measured directly by the sensor.", + tr("Your age, sex, height and weight let the ring compute accurate calories (and, on " + + "56ff/Jring rings, blood sugar). Blood pressure is measured directly by the sensor."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1217,7 +1219,7 @@ fun ProfileSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> Unit) profileDraft = draft.copy(units = keyStore.resolvedUnitSystem) com.pulseloop.widgets.WidgetSnapshotPublisher.publish(context) }) { - Text("Reset units to auto-detect", style = MaterialTheme.typography.labelSmall) + Text(tr("Reset units to auto-detect"), style = MaterialTheme.typography.labelSmall) } } @@ -1234,11 +1236,11 @@ fun ProfileSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> Unit) // Profile (age/sex) shifts widget reference zones — republish. com.pulseloop.widgets.WidgetSnapshotPublisher.publish(context) savedMsg = if (coordinator?.isConnected == true) - "Saved & sent to ring ✓" else "Saved — will sync on next connect" + tr("Saved & sent to ring ✓") else tr("Saved — will sync on next connect") } }, modifier = Modifier.fillMaxWidth(), - ) { Text("Save profile") } + ) { Text(tr("Save profile")) } savedMsg?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) } @@ -1280,32 +1282,32 @@ fun PhysiologySettingsScreen(onBack: () -> Unit) { } } - SettingsSubScreen(title = "Physiology", onBack = onBack) { + SettingsSubScreen(title = tr("Physiology"), onBack = onBack) { Text( - "Optional refinements to how your vitals are interpreted. Leave anything unset and " + - "PulseLoop uses sensible defaults.", + tr("Optional refinements to how your vitals are interpreted. Leave anything unset and " + + "PulseLoop uses sensible defaults."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) PhysiologyCard( - title = "Fitness", - footer = "Treats a low resting heart rate as a sign of fitness rather than a concern, and relaxes the low-HR threshold.", + title = tr("Fitness"), + footer = tr("Treats a low resting heart rate as a sign of fitness rather than a concern, and relaxes the low-HR threshold."), ) { Row(Modifier.switchRow(checked = athleteMode, onCheckedChange = { athleteMode = it; savedMsg = null }), verticalAlignment = Alignment.CenterVertically) { - Text("Athlete mode", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) + Text(tr("Athlete mode"), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) Switch(checked = athleteMode, onCheckedChange = null) } } PhysiologyCard( - title = "Environment", - footer = "Above ~2000 m, normal blood-oxygen readings run lower. We use this to avoid false low-oxygen warnings.", + title = tr("Environment"), + footer = tr("Above ~2000 m, normal blood-oxygen readings run lower. We use this to avoid false low-oxygen warnings."), ) { OutlinedTextField( value = altitudeText, onValueChange = { altitudeText = it.filter(Char::isDigit).take(5); savedMsg = null }, - label = { Text(if (imperial) "Typical altitude (ft)" else "Typical altitude (m)") }, + label = { Text(if (imperial) tr("Typical altitude (ft)") else tr("Typical altitude (m)")) }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), singleLine = true, modifier = Modifier.fillMaxWidth(), @@ -1313,17 +1315,17 @@ fun PhysiologySettingsScreen(onBack: () -> Unit) { } PhysiologyCard( - title = "Health context", - footer = "Optional. Both can change what's expected for your heart rate or oxygen, so we adjust labels instead of alarming.", + title = tr("Health context"), + footer = tr("Optional. Both can change what's expected for your heart rate or oxygen, so we adjust labels instead of alarming."), ) { - TriStateRow("Beta-blockers", betaBlockers) { betaBlockers = it; savedMsg = null } + TriStateRow(tr("Beta-blockers"), betaBlockers) { betaBlockers = it; savedMsg = null } Spacer(Modifier.height(12.dp)) - TriStateRow("Known lung condition", lungCondition) { lungCondition = it; savedMsg = null } + TriStateRow(tr("Known lung condition"), lungCondition) { lungCondition = it; savedMsg = null } } - PhysiologyCard(title = "Units", footer = null) { + PhysiologyCard(title = tr("Units"), footer = null) { Row(verticalAlignment = Alignment.CenterVertically) { - Text("Glucose unit", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) + Text(tr("Glucose unit"), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) SingleChoiceSegmentedButtonRow { GlucoseUnit.entries.forEachIndexed { i, u -> SegmentedButton( @@ -1347,10 +1349,10 @@ fun PhysiologySettingsScreen(onBack: () -> Unit) { if (entered != null && entered > 0) (if (imperial) entered * 0.3048 else entered) else null // Physiology shifts the vitals reference zones the widgets render — republish. com.pulseloop.widgets.WidgetSnapshotPublisher.publish(context) - savedMsg = "Saved ✓" + savedMsg = tr("Saved ✓") }, modifier = Modifier.fillMaxWidth(), - ) { Text("Save") } + ) { Text(tr("Save")) } savedMsg?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) } @@ -1421,12 +1423,12 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U glucoseRef = keyStore.glucoseRefMgdl.takeIf { it > 0 }?.let { "%.0f".format(it) } ?: "" } - SettingsSubScreen(title = "Calibration", onBack = onBack) { + SettingsSubScreen(title = tr("Calibration"), onBack = onBack) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Blood pressure calibration", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Blood pressure calibration"), style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold) Text( - "Optional. Enter a recent cuff reading so the ring offsets its values to match.", + tr("Optional. Enter a recent cuff reading so the ring offsets its values to match."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1434,13 +1436,13 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { OutlinedTextField( value = bpSys, onValueChange = { bpSys = it.filter(Char::isDigit).take(3) }, - label = { Text("Systolic") }, + label = { Text(tr("Systolic")) }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), singleLine = true, modifier = Modifier.weight(1f), ) OutlinedTextField( value = bpDia, onValueChange = { bpDia = it.filter(Char::isDigit).take(3) }, - label = { Text("Diastolic") }, + label = { Text(tr("Diastolic")) }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), singleLine = true, modifier = Modifier.weight(1f), ) @@ -1455,11 +1457,11 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U keyStore.bpAdjustDiastolic = diaI coordinator?.applyUserSettings(db.userProfileDao().get(), sysI, diaI) savedMsg = if (coordinator?.isConnected == true) - "Saved & sent to ring ✓" else "Saved — will sync on next connect" + tr("Saved & sent to ring ✓") else tr("Saved — will sync on next connect") } }, modifier = Modifier.fillMaxWidth(), - ) { Text("Save calibration") } + ) { Text(tr("Save calibration")) } savedMsg?.let { Spacer(Modifier.height(6.dp)) Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) @@ -1469,10 +1471,10 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Blood sugar calibration", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Blood sugar calibration"), style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold) Text( - "Optional. The ring estimates glucose from your profile, not a real sensor. " + - "Enter a recent lab/meter reading (mg/dL) to offset the displayed value to match.", + tr("Optional. The ring estimates glucose from your profile, not a real sensor. " + + "Enter a recent lab/meter reading (mg/dL) to offset the displayed value to match."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1480,7 +1482,7 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { OutlinedTextField( value = glucoseRef, onValueChange = { glucoseRef = it.filter(Char::isDigit).take(3) }, - label = { Text("Reading (mg/dL)") }, + label = { Text(tr("Reading (mg/dL)")) }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), singleLine = true, modifier = Modifier.weight(1.4f), ) @@ -1489,12 +1491,12 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U scope.launch { val ref = glucoseRef.toDoubleOrNull() if (ref == null || ref <= 0) { - glucoseMsg = "Enter a valid mg/dL reading" + glucoseMsg = tr("Enter a valid mg/dL reading") return@launch } val latestRaw = db.measurementDao().latest(MeasurementKind.BLOOD_SUGAR.name) if (latestRaw == null) { - glucoseMsg = "Take a blood sugar measurement first, then calibrate" + glucoseMsg = tr("Take a blood sugar measurement first, then calibrate") return@launch } // Stored readings are raw (offset is applied only at display), @@ -1506,7 +1508,7 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U } }, modifier = Modifier.weight(1f), - ) { Text("Calibrate") } + ) { Text(tr("Calibrate")) } } Row(verticalAlignment = Alignment.CenterVertically) { Text( @@ -1521,8 +1523,8 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U keyStore.glucoseRefMgdl = 0.0 glucoseOffset = 0.0 glucoseRef = "" - glucoseMsg = "Calibration cleared" - }) { Text("Reset") } + glucoseMsg = tr("Calibration cleared") + }) { Text(tr("Reset")) } } } glucoseMsg?.let { @@ -1551,9 +1553,9 @@ fun GoalsSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> Unit) { goalDraft = com.pulseloop.ui.onboarding.GoalDraft.from(db.userGoalDao().get(), goalUnits) } - SettingsSubScreen(title = "Goals", onBack = onBack) { + SettingsSubScreen(title = tr("Goals"), onBack = onBack) { Text( - "Daily and weekly targets behind the activity rings.", + tr("Daily and weekly targets behind the activity rings."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1581,11 +1583,11 @@ fun GoalsSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> Unit) { // Ring goals drive the widget's activity rings — republish. com.pulseloop.widgets.WidgetSnapshotPublisher.publish(context) goalSavedMsg = if (coordinator?.isConnected == true) - "Saved & sent to ring ✓" else "Saved" + tr("Saved & sent to ring ✓") else tr("Saved") } }, modifier = Modifier.fillMaxWidth(), - ) { Text("Save goals") } + ) { Text(tr("Save goals")) } goalSavedMsg?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) } @@ -1655,13 +1657,13 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U } } - SettingsSubScreen(title = "Measurement Frequency", onBack = onBack) { + SettingsSubScreen(title = tr("Measurement Frequency"), onBack = onBack) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Measurement", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Measurement"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( - "How often the ring measures in the background. Shorter heart-rate intervals give finer history at the cost of battery.", + tr("How often the ring measures in the background. Shorter heart-rate intervals give finer history at the cost of battery."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1669,12 +1671,12 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U if (device == null) { Text( - "Pair a ring to configure its all-day measurements.", + tr("Pair a ring to configure its all-day measurements."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } else { - VitalToggle("All-day heart rate", cfgHrEnabled) { cfgHrEnabled = it } + VitalToggle(tr("All-day heart rate"), cfgHrEnabled) { cfgHrEnabled = it } if (cfgHrEnabled) { Text( "Every $cfgHrInterval min", @@ -1691,14 +1693,14 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U } HorizontalDivider(Modifier.padding(vertical = 8.dp)) if (WearableCapability.SPO2 in capabilities) { - VitalToggle("Blood oxygen (SpO₂)", cfgSpo2) { cfgSpo2 = it } + VitalToggle(tr("Blood oxygen (SpO₂)"), cfgSpo2) { cfgSpo2 = it } // The monitor command takes the same shape for every vital // (`01 {enable, interval}`), so blood oxygen always had an interval — // it just wasn't surfaced and silently followed heart rate. On a ring // running both monitors hourly that is most of the battery (issue #66). if (cfgSpo2 && supportsSpo2Interval) { Text( - if (cfgSpo2Interval <= 0) "Same as heart rate" else "Every $cfgSpo2Interval min", + if (cfgSpo2Interval <= 0) tr("Same as heart rate") else "Every $cfgSpo2Interval min", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1718,13 +1720,13 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U } } if (supportsStressSetting) { - VitalToggle("Stress", cfgStress) { cfgStress = it } + VitalToggle(tr("Stress"), cfgStress) { cfgStress = it } } if (WearableCapability.HRV in capabilities) { VitalToggle("HRV", cfgHrv) { cfgHrv = it } } if (WearableCapability.TEMPERATURE in capabilities) { - VitalToggle("Temperature", cfgTemp) { cfgTemp = it } + VitalToggle(tr("Temperature"), cfgTemp) { cfgTemp = it } } Spacer(Modifier.height(12.dp)) @@ -1748,11 +1750,11 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U ) coordinator?.applyMeasurementSettings() cfgSavedMsg = if (coordinator?.isConnected == true) - "Saved & sent to ring ✓" else "Saved — will sync on next connect" + tr("Saved & sent to ring ✓") else tr("Saved — will sync on next connect") } }, modifier = Modifier.fillMaxWidth(), - ) { Text("Save measurement settings") } + ) { Text(tr("Save measurement settings")) } cfgSavedMsg?.let { Spacer(Modifier.height(6.dp)) Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) @@ -1809,15 +1811,15 @@ private fun QuietHoursCard() { horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { - Text("Sleep quiet hours", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Sleep quiet hours"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Switch(checked = enabled, onCheckedChange = null) } Text( - "When on, sleep the ring records outside the window is trimmed off on import — a " + + tr("When on, sleep the ring records outside the window is trimmed off on import — a " + "still wrist reads as sleep, so an evening on the sofa can log a phantom session " + "and run the night high. Set the start to when you actually go to bed. Naps " + "outside the window are skipped too. Already-imported nights are never touched, " + - "and what the gate skips while it is narrower stays skipped.", + "and what the gate skips while it is narrower stays skipped."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1845,12 +1847,12 @@ private fun QuietHoursCard() { ) { Column(Modifier.weight(1f).padding(end = 8.dp)) { Text( - "Track Bedtime / DND mode", + tr("Track Bedtime / DND mode"), style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium, ) Text( - "Automatically align quiet hours with Android's Bedtime or Do Not Disturb mode.", + tr("Automatically align quiet hours with Android's Bedtime or Do Not Disturb mode."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1860,8 +1862,8 @@ private fun QuietHoursCard() { Spacer(Modifier.height(8.dp)) Text( - if (gateByZenMode) "Fallback schedule (used when no Bedtime/DND mode was active):" - else "Quiet hours schedule:", + if (gateByZenMode) tr("Fallback schedule (used when no Bedtime/DND mode was active):") + else tr("Quiet hours schedule:"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1881,14 +1883,14 @@ private fun QuietHoursCard() { if (showPermissionDialog) { AlertDialog( onDismissRequest = { showPermissionDialog = false }, - title = { Text("Permission required") }, + title = { Text(tr("Permission required")) }, text = { Text( - "To log when Bedtime or Do Not Disturb turns on and off while PulseLoop is " + + tr("To log when Bedtime or Do Not Disturb turns on and off while PulseLoop is " + "in the background, Android requires Notification access. PulseLoop only " + "listens for Mode changes and does not read your notifications.\n\n" + "If the switch is greyed out, open PulseLoop's App info, tap ⋮ → " + - "Allow restricted settings, then come back here.", + "Allow restricted settings, then come back here."), ) }, confirmButton = { @@ -1907,13 +1909,13 @@ private fun QuietHoursCard() { context.startActivity(intent) prefs.gateByZenMode = true } catch (_: Exception) {} - }) { Text("Open Settings") } + }) { Text(tr("Open Settings")) } }, dismissButton = { TextButton(onClick = { showPermissionDialog = false if (!prefs.gateByZenMode) ZenModeListener.setEnabled(context, false) - }) { Text("Cancel") } + }) { Text(tr("Cancel")) } }, ) } @@ -1927,7 +1929,7 @@ private fun QuietHoursCard() { ) AlertDialog( onDismissRequest = { picking = null }, - title = { Text(if (which == "start") "Quiet from" else "Quiet until") }, + title = { Text(if (which == "start") tr("Quiet from") else tr("Quiet until")) }, text = { TimePicker(state = pickerState) }, confirmButton = { TextButton(onClick = { @@ -1935,10 +1937,10 @@ private fun QuietHoursCard() { if (which == "start") { start = minutes; prefs.startMinutes = minutes } else { end = minutes; prefs.endMinutes = minutes } picking = null - }) { Text("Done") } + }) { Text(tr("Done")) } }, dismissButton = { - TextButton(onClick = { picking = null }) { Text("Cancel") } + TextButton(onClick = { picking = null }) { Text(tr("Cancel")) } }, ) } @@ -1985,9 +1987,9 @@ fun WearableSettingsScreen( val battery = bleState.batteryPercent ?: device?.batteryPercent val lastSyncedLabel = (coordinator?.lastSyncAt ?: device?.lastSyncAt) ?.let { DeviceHeroStatus.relativeShort(it, System.currentTimeMillis()) } - ?: "Not yet" + ?: tr("Not yet") - SettingsSubScreen(title = "Wearable", onBack = onBack) { + SettingsSubScreen(title = tr("Wearable"), onBack = onBack) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { @@ -1998,7 +2000,7 @@ fun WearableSettingsScreen( Spacer(Modifier.width(8.dp)) Text( if (isConnected) "Connected — $wearableDisplayName · ${battery ?: 0}%" - else device?.let { "Last seen: $wearableDisplayName" } ?: "No ring paired", + else device?.let { "Last seen: $wearableDisplayName" } ?: tr("No ring paired"), style = MaterialTheme.typography.bodyMedium, ) } @@ -2009,7 +2011,7 @@ fun WearableSettingsScreen( val fwDisplay = if (rawFw.contains("V")) "V" + rawFw.substringAfterLast("V") else rawFw Text("Firmware: $fwDisplay", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) } else if (device != null) { - Text("Firmware: reading… (connect ring to read)", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) + Text(tr("Firmware: reading… (connect ring to read)"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) } if (device != null) { Text("Last synced: $lastSyncedLabel", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) @@ -2021,7 +2023,7 @@ fun WearableSettingsScreen( Button(onClick = onAddRing, modifier = Modifier.fillMaxWidth()) { Icon(Icons.Filled.Add, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Add a ring") + Text(tr("Add a ring")) } } @@ -2033,7 +2035,7 @@ fun WearableSettingsScreen( ) { Icon(Icons.Filled.Sync, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Sync now") + Text(tr("Sync now")) } if (supportsFindDevice) { Spacer(Modifier.height(8.dp)) @@ -2043,7 +2045,7 @@ fun WearableSettingsScreen( ) { Icon(Icons.Filled.NotificationsActive, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Find ring") + Text(tr("Find ring")) } } Spacer(Modifier.height(8.dp)) @@ -2053,7 +2055,7 @@ fun WearableSettingsScreen( ) { Icon(Icons.Filled.Close, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Disconnect") + Text(tr("Disconnect")) } } else if (bleClient?.hasLastKnownRing == true && bleState.connectionState != RingConnectionState.RECONNECTING @@ -2065,7 +2067,7 @@ fun WearableSettingsScreen( ) { Icon(Icons.Filled.Refresh, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Reconnect last ring") + Text(tr("Reconnect last ring")) } } } @@ -2086,11 +2088,11 @@ fun WearableSettingsScreen( if (device != null) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Ring management", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Ring management"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( - "Forget unbinds the ring and removes it from the app so it can be paired " + - "elsewhere. The app stays connected automatically the rest of the time.", + tr("Forget unbinds the ring and removes it from the app so it can be paired " + + "elsewhere. The app stays connected automatically the rest of the time."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -2102,7 +2104,7 @@ fun WearableSettingsScreen( ) { Icon(Icons.Filled.DeleteForever, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Forget Ring") + Text(tr("Forget Ring")) } // Factory reset — destructive, ring-side wipe. Only for connected rings that @@ -2110,8 +2112,8 @@ fun WearableSettingsScreen( if (isConnected && supportsFactoryReset) { Spacer(Modifier.height(8.dp)) Text( - "Factory reset erases all data stored on the ring itself and resets " + - "it to factory state. Your synced data in the app is kept.", + tr("Factory reset erases all data stored on the ring itself and resets " + + "it to factory state. Your synced data in the app is kept."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -2124,7 +2126,7 @@ fun WearableSettingsScreen( ) { Icon(Icons.Filled.Refresh, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text(if (resetting) (resetStatus.ifEmpty { "Resetting…" }) else "Factory Reset Ring") + Text(if (resetting) (resetStatus.ifEmpty { tr("Resetting…") }) else tr("Factory Reset Ring")) } } } @@ -2135,11 +2137,11 @@ fun WearableSettingsScreen( if (showForgetRing) { AlertDialog( onDismissRequest = { showForgetRing = false }, - title = { Text("Forget ring?") }, + title = { Text(tr("Forget ring?")) }, text = { Text( - "This unbinds the ring and removes it from the app. Your synced data is " + - "kept, but you'll need to pair the ring again to keep syncing." + tr("This unbinds the ring and removes it from the app. Your synced data is " + + "kept, but you'll need to pair the ring again to keep syncing.") ) }, confirmButton = { @@ -2162,10 +2164,10 @@ fun WearableSettingsScreen( db.deviceDao().clear() } } - }) { Text("Forget", color = MaterialTheme.colorScheme.error) } + }) { Text(tr("Forget"), color = MaterialTheme.colorScheme.error) } }, dismissButton = { - TextButton(onClick = { showForgetRing = false }) { Text("Cancel") } + TextButton(onClick = { showForgetRing = false }) { Text(tr("Cancel")) } }, ) } @@ -2173,19 +2175,19 @@ fun WearableSettingsScreen( if (showFactoryReset) { AlertDialog( onDismissRequest = { showFactoryReset = false }, - title = { Text("Factory reset ring?") }, + title = { Text(tr("Factory reset ring?")) }, text = { Text( - "This erases all data stored on the ring and resets it to factory " + + tr("This erases all data stored on the ring and resets it to factory " + "state. We'll sync its latest data into the app first, but this " + - "can't be undone. The ring will need to be re-paired afterward." + "can't be undone. The ring will need to be re-paired afterward.") ) }, confirmButton = { TextButton(onClick = { showFactoryReset = false resetting = true - resetStatus = "Syncing latest data…" + resetStatus = tr("Syncing latest data…") RingSyncWorker.cancel(context) // onCleared runs on the coordinator's long-lived scope: the reset // takes up to ~30s, and the device row must be cleared even if the @@ -2196,10 +2198,10 @@ fun WearableSettingsScreen( db.deviceDao().clear() resetting = false } - }) { Text("Reset ring", color = MaterialTheme.colorScheme.error) } + }) { Text(tr("Reset ring"), color = MaterialTheme.colorScheme.error) } }, dismissButton = { - TextButton(onClick = { showFactoryReset = false }) { Text("Cancel") } + TextButton(onClick = { showFactoryReset = false }) { Text(tr("Cancel")) } }, ) } @@ -2234,14 +2236,14 @@ private fun BackgroundSyncCard() { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Reliable background sync", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Reliable background sync"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( if (exempt) { - "On. PulseLoop syncs your ring about every 30 minutes, even while the phone is idle." + tr("On. PulseLoop syncs your ring about every 30 minutes, even while the phone is idle.") } else { - "Android may delay background syncs by hours while your phone is idle. Your ring " + - "keeps recording either way; allowing this keeps the app up to date." + tr("Android may delay background syncs by hours while your phone is idle. Your ring " + + "keeps recording either way; allowing this keeps the app up to date.") }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, @@ -2267,7 +2269,7 @@ private fun BackgroundSyncCard() { }, modifier = Modifier.fillMaxWidth(), ) { - Text(if (exempt) "Manage in Android settings" else "Allow background sync") + Text(if (exempt) tr("Manage in Android settings") else tr("Allow background sync")) } } } @@ -2275,17 +2277,17 @@ private fun BackgroundSyncCard() { /** 24h/7d windows for the battery drainage chart (iOS #61b — only these two ranges). */ private enum class BatteryHistoryRange(val label: String, val spanMs: Long) { - DAY("24h", 24 * 3600_000L), - WEEK("7d", 7 * 24 * 3600_000L), + DAY(tr("24h"), 24 * 3600_000L), + WEEK(tr("7d"), 7 * 24 * 3600_000L), } /** Fixed 0–100 zone coloring for the battery line — mirrors iOS `colorForValue` * (≤20 danger, ≤50 warning, else success). Zone boundaries use an exclusive upper bound * (`ZoneLineChart` matches `lower <= value < upper`), so 21/51 sit just above each cut. */ private val batteryZones = listOf( - MetricZone("critical", "Critical", null, 21.0, ZoneSeverity.CRITICAL, VitalColorToken.Red, "Battery critically low"), - MetricZone("low", "Low", 21.0, 51.0, ZoneSeverity.WATCH, VitalColorToken.Amber, "Battery low"), - MetricZone("good", "Good", 51.0, null, ZoneSeverity.OPTIMAL, VitalColorToken.Mint, "Battery healthy"), + MetricZone("critical", tr("Critical"), null, 21.0, ZoneSeverity.CRITICAL, VitalColorToken.Red, tr("Battery critically low")), + MetricZone("low", tr("Low"), 21.0, 51.0, ZoneSeverity.WATCH, VitalColorToken.Amber, tr("Battery low")), + MetricZone("good", tr("Good"), 51.0, null, ZoneSeverity.OPTIMAL, VitalColorToken.Mint, tr("Battery healthy")), ) /** @@ -2310,7 +2312,7 @@ private fun BatteryHistorySection(db: PulseLoopDatabase) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text("Battery history", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Battery history"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) SingleChoiceSegmentedButtonRow { BatteryHistoryRange.entries.forEachIndexed { i, r -> SegmentedButton( @@ -2324,7 +2326,7 @@ private fun BatteryHistorySection(db: PulseLoopDatabase) { Spacer(Modifier.height(8.dp)) if (samples.size < 2) { Text( - "Not enough data yet — battery history builds up as the ring reports its level.", + tr("Not enough data yet — battery history builds up as the ring reports its level."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -2357,19 +2359,19 @@ private sealed class ResetAction { data object UnpairAndReset : ResetAction() val title: String get() = when (this) { - is UnpairRing -> "Unpair ring?" - is ResetAppData -> "Reset app data?" - is UnpairAndReset -> "Unpair ring & reset app data?" + is UnpairRing -> tr("Unpair ring?") + is ResetAppData -> tr("Reset app data?") + is UnpairAndReset -> tr("Unpair ring & reset app data?") } val message: String get() = when (this) { - is UnpairRing -> "Unpair your ring? The ring will forget this phone; your data stays." - is ResetAppData -> "This permanently erases all your data — metrics, sleep, activity, coach history, settings, and saved API keys — and can't be undone." - is UnpairAndReset -> "This unpairs your ring, then permanently erases all your data — metrics, sleep, activity, coach history, settings, and saved API keys — and can't be undone." + is UnpairRing -> tr("Unpair your ring? The ring will forget this phone; your data stays.") + is ResetAppData -> tr("This permanently erases all your data — metrics, sleep, activity, coach history, settings, and saved API keys — and can't be undone.") + is UnpairAndReset -> tr("This unpairs your ring, then permanently erases all your data — metrics, sleep, activity, coach history, settings, and saved API keys — and can't be undone.") } val confirmLabel: String get() = when (this) { - is UnpairRing -> "Unpair ring" - is ResetAppData -> "Reset app data" - is UnpairAndReset -> "Unpair & reset" + is UnpairRing -> tr("Unpair ring") + is ResetAppData -> tr("Reset app data") + is UnpairAndReset -> tr("Unpair & reset") } } @@ -2455,14 +2457,14 @@ fun PrivacyDataSettingsScreen( } } - SettingsSubScreen(title = "Privacy & Data", onBack = onBack) { + SettingsSubScreen(title = tr("Privacy & Data"), onBack = onBack) { // Data Backup — export/import full app data as JSON. Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Data Backup", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Data Backup"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( - "Export all your data to a single JSON file for backup, device migration, or external analysis. Import restores everything — replacing all current data.", + tr("Export all your data to a single JSON file for backup, device migration, or external analysis. Import restores everything — replacing all current data."), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -2481,10 +2483,10 @@ fun PrivacyDataSettingsScreen( putExtra(Intent.EXTRA_STREAM, uri) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } - context.startActivity(Intent.createChooser(shareIntent, "Export PulseLoop Data")) + context.startActivity(Intent.createChooser(shareIntent, tr("Export PulseLoop Data"))) } } catch (_: Exception) { - statusMessage = "Export failed" + statusMessage = tr("Export failed") } exportInProgress = false } @@ -2496,7 +2498,7 @@ fun PrivacyDataSettingsScreen( CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) Spacer(Modifier.width(8.dp)) } - Text(if (exportInProgress) "Exporting…" else "Export All Data") + Text(if (exportInProgress) tr("Exporting…") else tr("Export All Data")) } OutlinedButton( onClick = { @@ -2509,7 +2511,7 @@ fun PrivacyDataSettingsScreen( CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) Spacer(Modifier.width(8.dp)) } - Text(if (importInProgress) "Importing…" else "Import Data") + Text(if (importInProgress) tr("Importing…") else tr("Import Data")) } } } @@ -2520,10 +2522,10 @@ fun PrivacyDataSettingsScreen( // App data — destructive reset/restore actions. Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("App Data", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("App Data"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( - "Destructive actions: unpair the ring, factory-reset app data, or both.", + tr("Destructive actions: unpair the ring, factory-reset app data, or both."), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -2535,7 +2537,7 @@ fun PrivacyDataSettingsScreen( ) { Icon(Icons.Filled.BluetoothDisabled, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Unpair Ring") + Text(tr("Unpair Ring")) } Spacer(Modifier.height(8.dp)) OutlinedButton( @@ -2545,7 +2547,7 @@ fun PrivacyDataSettingsScreen( ) { Icon(Icons.Filled.DeleteForever, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Reset App Data") + Text(tr("Reset App Data")) } Spacer(Modifier.height(8.dp)) OutlinedButton( @@ -2555,7 +2557,7 @@ fun PrivacyDataSettingsScreen( ) { Icon(Icons.Filled.Warning, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text("Unpair & Reset") + Text(tr("Unpair & Reset")) } } } @@ -2563,20 +2565,20 @@ fun PrivacyDataSettingsScreen( // Demo data — Android-only (iOS seeds via the Simulator's SeedData). Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Demo Data", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Demo Data"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( - "Explore the app without a ring. Seeds activity, HR, SpO2, sleep, and a coach conversation.", + tr("Explore the app without a ring. Seeds activity, HR, SpO2, sleep, and a coach conversation."), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) Spacer(Modifier.height(12.dp)) Button(onClick = { showSeedDialog = true }, modifier = Modifier.fillMaxWidth()) { - Text("Reseed Demo Data") + Text(tr("Reseed Demo Data")) } Spacer(Modifier.height(8.dp)) OutlinedButton(onClick = { showClearDialog = true }, modifier = Modifier.fillMaxWidth()) { - Text("Clear Demo Data", color = PulseColors.danger) + Text(tr("Clear Demo Data"), color = PulseColors.danger) } } } @@ -2585,22 +2587,22 @@ fun PrivacyDataSettingsScreen( Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { var maskSensitive by remember { mutableStateOf(true) } - Text("Diagnostics", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Diagnostics"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( - "Export app, device, and wearable logs as JSON for bug reports.", + tr("Export app, device, and wearable logs as JSON for bug reports."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) Spacer(Modifier.height(12.dp)) Row(Modifier.switchRow(checked = maskSensitive, onCheckedChange = { maskSensitive = it }), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Anonymize export", style = MaterialTheme.typography.bodyMedium) + Text(tr("Anonymize export"), style = MaterialTheme.typography.bodyMedium) Text( if (maskSensitive) - "Removes health values, ring serial & MAC addresses. Keeps models, opcodes & errors." + tr("Removes health values, ring serial & MAC addresses. Keeps models, opcodes & errors.") else - "OFF — includes full unmasked BLE frames and health values (for protocol debugging only).", + tr("OFF — includes full unmasked BLE frames and health values (for protocol debugging only)."), style = MaterialTheme.typography.bodySmall, color = if (maskSensitive) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.error, @@ -2624,7 +2626,7 @@ fun PrivacyDataSettingsScreen( ) { Icon(Icons.Filled.Share, null) Spacer(Modifier.width(8.dp)) - Text(if (maskSensitive) "Export Diagnostics" else "Export Full (Unmasked)") + Text(if (maskSensitive) tr("Export Diagnostics") else tr("Export Full (Unmasked)")) } } } @@ -2636,7 +2638,7 @@ fun PrivacyDataSettingsScreen( val msg = statusMessage!! AlertDialog( onDismissRequest = { statusMessage = null }, - title = { Text("Error") }, + title = { Text(tr("Error")) }, text = { Text(msg) }, confirmButton = { TextButton(onClick = { statusMessage = null }) { Text("OK") } @@ -2646,8 +2648,8 @@ fun PrivacyDataSettingsScreen( showImportSuccess -> AlertDialog( onDismissRequest = { showImportSuccess = false }, - title = { Text("Import Complete") }, - text = { Text("Your data has been restored from the backup.") }, + title = { Text(tr("Import Complete")) }, + text = { Text(tr("Your data has been restored from the backup.")) }, confirmButton = { TextButton(onClick = { showImportSuccess = false }) { Text("OK") } }, @@ -2655,9 +2657,9 @@ fun PrivacyDataSettingsScreen( showImportConfirm -> AlertDialog( onDismissRequest = { showImportConfirm = false; pendingImportUri = null }, - title = { Text("Replace all data?") }, + title = { Text(tr("Replace all data?")) }, text = { - Text("This permanently deletes everything currently in the app and replaces it with the contents of this file. This can't be undone.") + Text(tr("This permanently deletes everything currently in the app and replaces it with the contents of this file. This can't be undone.")) }, confirmButton = { TextButton(onClick = { @@ -2671,16 +2673,16 @@ fun PrivacyDataSettingsScreen( com.pulseloop.data.DataArchiveService.importFile(context, uri, db) showImportSuccess = true } catch (_: Exception) { - statusMessage = "Import failed — the file may be corrupt or from a newer version." + statusMessage = tr("Import failed — the file may be corrupt or from a newer version.") } importInProgress = false } }) { - Text("Delete old data & import", color = MaterialTheme.colorScheme.error) + Text(tr("Delete old data & import"), color = MaterialTheme.colorScheme.error) } }, dismissButton = { - TextButton(onClick = { showImportConfirm = false; pendingImportUri = null }) { Text("Cancel") } + TextButton(onClick = { showImportConfirm = false; pendingImportUri = null }) { Text(tr("Cancel")) } }, ) @@ -2703,15 +2705,15 @@ fun PrivacyDataSettingsScreen( } }, dismissButton = { - TextButton(onClick = { pendingReset = null }) { Text("Cancel") } + TextButton(onClick = { pendingReset = null }) { Text(tr("Cancel")) } }, ) } showSeedDialog -> AlertDialog( onDismissRequest = { showSeedDialog = false }, - title = { Text("Reseed Demo Data?") }, - text = { Text("This will replace all existing demo data. Your synced ring data — including sleep history — will not be affected.") }, + title = { Text(tr("Reseed Demo Data?")) }, + text = { Text(tr("This will replace all existing demo data. Your synced ring data — including sleep history — will not be affected.")) }, confirmButton = { TextButton(onClick = { showSeedDialog = false @@ -2719,20 +2721,20 @@ fun PrivacyDataSettingsScreen( DemoDataSeeder.seed(PulseLoopDatabase.getInstance(context)) com.pulseloop.widgets.WidgetSnapshotPublisher.publish(context) } - }) { Text("Reseed") } + }) { Text(tr("Reseed")) } }, dismissButton = { - TextButton(onClick = { showSeedDialog = false }) { Text("Cancel") } + TextButton(onClick = { showSeedDialog = false }) { Text(tr("Cancel")) } }, ) showClearDialog -> AlertDialog( onDismissRequest = { showClearDialog = false }, - title = { Text("Clear Demo Data?") }, + title = { Text(tr("Clear Demo Data?")) }, text = { Text( - "Removes all demo measurements, activity, sleep, and the demo device. " + - "Synced ring data is not affected.", + tr("Removes all demo measurements, activity, sleep, and the demo device. " + + "Synced ring data is not affected."), ) }, confirmButton = { @@ -2742,10 +2744,10 @@ fun PrivacyDataSettingsScreen( DemoDataSeeder.clear(PulseLoopDatabase.getInstance(context)) com.pulseloop.widgets.WidgetSnapshotPublisher.publish(context) } - }) { Text("Clear", color = PulseColors.danger) } + }) { Text(tr("Clear"), color = PulseColors.danger) } }, dismissButton = { - TextButton(onClick = { showClearDialog = false }) { Text("Cancel") } + TextButton(onClick = { showClearDialog = false }) { Text(tr("Cancel")) } }, ) } @@ -2793,7 +2795,7 @@ fun AboutSettingsScreen(onOpenDebug: () -> Unit, onBack: () -> Unit) { lastVersionTap = now if (developerUnlocked) { - showToast("Developer options are already enabled.") + showToast(tr("Developer options are already enabled.")) return } @@ -2807,7 +2809,7 @@ fun AboutSettingsScreen(onOpenDebug: () -> Unit, onBack: () -> Unit) { developerUnlocked = true keyStore.developerUnlocked = true haptics.performHapticFeedback(HapticFeedbackType.LongPress) - showToast("You are now a developer!") + showToast(tr("You are now a developer!")) onOpenDebug() } else if (remaining <= 3) { showToast("You're $remaining step${if (remaining == 1) "" else "s"} away from Developer options.") @@ -2815,7 +2817,7 @@ fun AboutSettingsScreen(onOpenDebug: () -> Unit, onBack: () -> Unit) { } SettingsSubScreen( - title = "About", + title = tr("About"), onBack = onBack, bottomOverlay = { toast?.let { message -> @@ -2850,7 +2852,7 @@ fun AboutSettingsScreen(onOpenDebug: () -> Unit, onBack: () -> Unit) { .dither(PulseColors.accent, tapProgress * 0.22f) .padding(16.dp), ) { - Text("Version", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Version"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( "PulseLoop v${com.pulseloop.BuildConfig.VERSION_NAME} (${com.pulseloop.BuildConfig.VERSION_CODE})", @@ -2861,12 +2863,12 @@ fun AboutSettingsScreen(onOpenDebug: () -> Unit, onBack: () -> Unit) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("PulseLoop", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("PulseLoop"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( - "An LLM-native health app that turns a cheap Bluetooth smart ring into a real, " + + tr("An LLM-native health app that turns a cheap Bluetooth smart ring into a real, " + "conversational health tracker. It talks to the ring directly over Bluetooth — no " + - "vendor cloud, no account — and layers an AI coach on top of your own data.", + "vendor cloud, no account — and layers an AI coach on top of your own data."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -2887,7 +2889,7 @@ fun AboutSettingsScreen(onOpenDebug: () -> Unit, onBack: () -> Unit) { ) { Row(Modifier.padding(16.dp).fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Source on GitHub", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold) + Text(tr("Source on GitHub"), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold) Text( REPO_URL.removePrefix("https://"), style = MaterialTheme.typography.bodySmall, @@ -2900,11 +2902,11 @@ fun AboutSettingsScreen(onOpenDebug: () -> Unit, onBack: () -> Unit) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("License", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold) + Text(tr("License"), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( - "Open-source health tracker. Ported from iOS.\nCC BY 4.0 · Free to share and " + - "adapt, including commercially, with appropriate credit.", + tr("Open-source health tracker. Ported from iOS.\nCC BY 4.0 · Free to share and " + + "adapt, including commercially, with appropriate credit."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -2929,7 +2931,7 @@ fun NutritionSettingsScreen(onBack: () -> Unit, onNavigateToNutrition: () -> Uni var goalReload by remember { mutableIntStateOf(0) } LaunchedEffect(goalReload) { goal = db.userGoalDao().get(); goalLoaded = true } - SettingsSubScreen(title = "Nutrition", onBack = onBack) { + SettingsSubScreen(title = tr("Nutrition"), onBack = onBack) { CoachManagedCard(com.pulseloop.service.GoalSync.NUTRITION_FIELDS) { goalReload++ } Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { @@ -2941,8 +2943,8 @@ fun NutritionSettingsScreen(onBack: () -> Unit, onNavigateToNutrition: () -> Uni } }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Enable Nutrition Tracking", fontWeight = FontWeight.Medium) - Text("Log meals and track calories & macros", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Enable Nutrition Tracking"), fontWeight = FontWeight.Medium) + Text(tr("Log meals and track calories & macros"), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) } Switch(checked = goal?.nutritionEnabled == true, enabled = goalLoaded, onCheckedChange = null) } @@ -2952,17 +2954,17 @@ fun NutritionSettingsScreen(onBack: () -> Unit, onNavigateToNutrition: () -> Uni if (goal?.nutritionEnabled == true) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { - Text("Daily Goals", fontWeight = FontWeight.SemiBold) - NutrientStepper("Calories (kcal)", goal?.intakeCalories ?: 2000.0, 50.0, 100.0, 10000.0) { v -> + Text(tr("Daily Goals"), fontWeight = FontWeight.SemiBold) + NutrientStepper(tr("Calories (kcal)"), goal?.intakeCalories ?: 2000.0, 50.0, 100.0, 10000.0) { v -> scope.launch { goal = goal?.copy(intakeCalories = v)?.also { db.userGoalDao().upsert(it); com.pulseloop.service.GoalSync.noteEdits(context, it) } } } - NutrientStepper("Protein (g)", goal?.intakeProteinG ?: 150.0, 5.0, 0.0, 500.0) { v -> + NutrientStepper(tr("Protein (g)"), goal?.intakeProteinG ?: 150.0, 5.0, 0.0, 500.0) { v -> scope.launch { goal = goal?.copy(intakeProteinG = v)?.also { db.userGoalDao().upsert(it); com.pulseloop.service.GoalSync.noteEdits(context, it) } } } - NutrientStepper("Carbs (g)", goal?.intakeCarbsG ?: 250.0, 5.0, 0.0, 800.0) { v -> + NutrientStepper(tr("Carbs (g)"), goal?.intakeCarbsG ?: 250.0, 5.0, 0.0, 800.0) { v -> scope.launch { goal = goal?.copy(intakeCarbsG = v)?.also { db.userGoalDao().upsert(it); com.pulseloop.service.GoalSync.noteEdits(context, it) } } } - NutrientStepper("Fat (g)", goal?.intakeFatG ?: 65.0, 5.0, 0.0, 300.0) { v -> + NutrientStepper(tr("Fat (g)"), goal?.intakeFatG ?: 65.0, 5.0, 0.0, 300.0) { v -> scope.launch { goal = goal?.copy(intakeFatG = v)?.also { db.userGoalDao().upsert(it); com.pulseloop.service.GoalSync.noteEdits(context, it) } } } OutlinedButton(onClick = { @@ -2973,20 +2975,20 @@ fun NutritionSettingsScreen(onBack: () -> Unit, onNavigateToNutrition: () -> Uni .also { db.userGoalDao().upsert(it) } } }, modifier = Modifier.fillMaxWidth()) { - Text("Balance Macros (30/40/30)") + Text(tr("Balance Macros (30/40/30)")) } } } Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Quick Access", fontWeight = FontWeight.SemiBold) + Text(tr("Quick Access"), fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Button( onClick = onNavigateToNutrition, modifier = Modifier.fillMaxWidth(), ) { - Text("Open Nutrition Log") + Text(tr("Open Nutrition Log")) } } } @@ -3041,14 +3043,14 @@ fun StravaSettingsScreen(onBack: () -> Unit) { } } - SettingsSubScreen(title = "Strava", onBack = onBack) { + SettingsSubScreen(title = tr("Strava"), onBack = onBack) { if (!isConfigured) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Strava Not Configured", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Strava Not Configured"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( - "Add stravaClientId and stravaClientSecret to local.properties to enable Strava integration.", + tr("Add stravaClientId and stravaClientSecret to local.properties to enable Strava integration."), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -3059,7 +3061,7 @@ fun StravaSettingsScreen(onBack: () -> Unit) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Strava Integration", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Strava Integration"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( if (isConnected) "Connected as $athleteName. Workouts sync automatically when finished." @@ -3080,8 +3082,8 @@ fun StravaSettingsScreen(onBack: () -> Unit) { // uploadAuto records why it stopped, if it stopped. statusMessage = tokenStore.lastError()?.also { tokenStore.clearLastError() } ?: when (count) { - 0 -> "Nothing new to upload" - 1 -> "Uploaded 1 workout" + 0 -> tr("Nothing new to upload") + 1 -> tr("Uploaded 1 workout") else -> "Uploaded $count workouts" } } catch (e: Exception) { @@ -3093,14 +3095,14 @@ fun StravaSettingsScreen(onBack: () -> Unit) { modifier = Modifier.weight(1f), enabled = !isUploading, ) { - Text(if (isUploading) "Syncing…" else "Sync Now") + Text(if (isUploading) tr("Syncing…") else tr("Sync Now")) } OutlinedButton( onClick = { confirmDisconnect = true }, modifier = Modifier.weight(1f), colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error), ) { - Text("Disconnect") + Text(tr("Disconnect")) } } } else { @@ -3114,14 +3116,14 @@ fun StravaSettingsScreen(onBack: () -> Unit) { val intent = Intent(Intent.ACTION_VIEW, android.net.Uri.parse(authUrl)) try { context.startActivity(intent) - statusMessage = "Authorize in your browser — you'll return to PulseLoop automatically." + statusMessage = tr("Authorize in your browser — you'll return to PulseLoop automatically.") } catch (_: Exception) { - statusMessage = "Could not open browser" + statusMessage = tr("Could not open browser") } }, modifier = Modifier.fillMaxWidth(), ) { - Text("Connect Strava") + Text(tr("Connect Strava")) } } } @@ -3130,7 +3132,7 @@ fun StravaSettingsScreen(onBack: () -> Unit) { if (isConnected) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Auto Upload", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Auto Upload"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( "Finished workouts are automatically uploaded to Strava. GPS routes, heart rate data, and sport type are included.", @@ -3159,8 +3161,8 @@ fun StravaSettingsScreen(onBack: () -> Unit) { if (confirmDisconnect) { AlertDialog( onDismissRequest = { confirmDisconnect = false }, - title = { Text("Disconnect Strava?") }, - text = { Text("PulseLoop will stop uploading workouts. Workouts already on Strava stay there.") }, + title = { Text(tr("Disconnect Strava?")) }, + text = { Text(tr("PulseLoop will stop uploading workouts. Workouts already on Strava stay there.")) }, confirmButton = { TextButton(onClick = { confirmDisconnect = false @@ -3174,12 +3176,12 @@ fun StravaSettingsScreen(onBack: () -> Unit) { tokenStore.clear() isConnected = false athleteName = null - statusMessage = "Disconnected from Strava" + statusMessage = tr("Disconnected from Strava") } - }) { Text("Disconnect", color = MaterialTheme.colorScheme.error) } + }) { Text(tr("Disconnect"), color = MaterialTheme.colorScheme.error) } }, dismissButton = { - TextButton(onClick = { confirmDisconnect = false }) { Text("Cancel") } + TextButton(onClick = { confirmDisconnect = false }) { Text(tr("Cancel")) } }, ) } @@ -3253,7 +3255,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { ) } statusMessage = if (got.isEmpty()) { - "No Health Connect permissions granted — nothing to export." + tr("No Health Connect permissions granted — nothing to export.") } else { "Connected. ${got.size} of ${HealthConnectPermissions.all.size} permission types granted." } @@ -3307,13 +3309,13 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { } } - SettingsSubScreen(title = "Health Connect", onBack = onBack) { + SettingsSubScreen(title = tr("Health Connect"), onBack = onBack) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Health Connect", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Health Connect"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( - "Export ring data to Health Connect so other apps and dashboards can show it. Write-only: PulseLoop never reads data back.", + tr("Export ring data to Health Connect so other apps and dashboards can show it. Write-only: PulseLoop never reads data back."), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -3322,25 +3324,25 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { when (availability) { HealthConnectAvailability.UNAVAILABLE -> { Text( - "Health Connect isn't available on this device. Install the Health Connect app to use this feature.", + tr("Health Connect isn't available on this device. Install the Health Connect app to use this feature."), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, ) Spacer(Modifier.height(8.dp)) Button(onClick = { openHealthConnectPlayStore(context) }, modifier = Modifier.fillMaxWidth()) { - Text("Install Health Connect") + Text(tr("Install Health Connect")) } } HealthConnectAvailability.PROVIDER_UPDATE_REQUIRED -> { Text( - "The Health Connect app on this device needs an update before it can be used.", + tr("The Health Connect app on this device needs an update before it can be used."), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, ) Spacer(Modifier.height(8.dp)) Button(onClick = { openHealthConnectPlayStore(context) }, modifier = Modifier.fillMaxWidth()) { - Text("Update Health Connect") + Text(tr("Update Health Connect")) } } @@ -3354,9 +3356,9 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { } }), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Export PulseLoop data", style = MaterialTheme.typography.bodyLarge) + Text(tr("Export PulseLoop data"), style = MaterialTheme.typography.bodyLarge) Text( - if (prefs.isConnected) "Connected" else "Not connected", + if (prefs.isConnected) tr("Connected") else tr("Not connected"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -3372,10 +3374,10 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { TextButton( onClick = { openHealthConnectApp(context) }, modifier = Modifier.align(Alignment.Start), - ) { Text("Open Health Connect") } + ) { Text(tr("Open Health Connect")) } if (!prefs.isConnected) { Text( - "Manage or re-grant permissions, and review or delete PulseLoop's data, in the Health Connect app.", + tr("Manage or re-grant permissions, and review or delete PulseLoop's data, in the Health Connect app."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -3388,10 +3390,10 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { if (availability == HealthConnectAvailability.AVAILABLE && prefs.isConnected) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Data Types", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Data Types"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( - "Exported only when switched on. A row stays dim until its permission is granted.", + tr("Exported only when switched on. A row stays dim until its permission is granted."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -3443,7 +3445,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { Text(label, style = MaterialTheme.typography.bodyMedium) if (!rowGranted) { Text( - "Awaiting permission", + tr("Awaiting permission"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -3452,8 +3454,8 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { if (heldUnits.isNotEmpty()) { Text( if (row == HealthConnectPermissions.DataTypeRow.STEPS_AND_ACTIVITY) { - "Paused by the accuracy check: " + heldUnits.joinToString(", ") { it.metric.label.lowercase() } - } else "Paused by the accuracy check", + tr("Paused by the accuracy check: ") + heldUnits.joinToString(", ") { it.metric.label.lowercase() } + } else tr("Paused by the accuracy check"), style = MaterialTheme.typography.bodySmall, color = PulseColors.warning, ) @@ -3465,7 +3467,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { // Plan §7 open item: the rings' HRV metric is vendor-undocumented, and // Health Connect has no SDNN type — we export it as RMSSD. Text( - "HRV is exported as RMSSD — Health Connect has no SDNN type, and the rings' metric is vendor-undocumented.", + tr("HRV is exported as RMSSD — Health Connect has no SDNN type, and the rings' metric is vendor-undocumented."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -3499,7 +3501,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { "Last sync ${DeviceHeroStatus.relativeShort(syncedAt, System.currentTimeMillis())} — " + (prefs.lastSyncSummary ?: "unknown") } else { - "No export has run yet. With the master switch on and a backfill choice made, PulseLoop exports automatically." + tr("No export has run yet. With the master switch on and a backfill choice made, PulseLoop exports automatically.") }, modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.bodyMedium, @@ -3511,17 +3513,17 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { // stamp so the export state matches an empty Health store. Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text("Remove exported data", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Remove exported data"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( - "Delete every record PulseLoop wrote to Health Connect and reset the export to start fresh. Your ring data in PulseLoop is untouched.", + tr("Delete every record PulseLoop wrote to Health Connect and reset the export to start fresh. Your ring data in PulseLoop is untouched."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) if (!prefs.isConnected) { Spacer(Modifier.height(4.dp)) Text( - "Deleting needs write permission, and PulseLoop has none right now — re-grant above, or delete the data in the Health Connect app.", + tr("Deleting needs write permission, and PulseLoop has none right now — re-grant above, or delete the data in the Health Connect app."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, ) @@ -3533,7 +3535,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { enabled = !removing, colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error), modifier = Modifier.fillMaxWidth(), - ) { Text(if (removing) "Removing…" else "Remove PulseLoop data") } + ) { Text(if (removing) tr("Removing…") else tr("Remove PulseLoop data")) } } } } @@ -3553,7 +3555,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { verticalAlignment = Alignment.CenterVertically, ) { Text(msg, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) - TextButton(onClick = { store.update { it.copy(removalStatus = null) } }) { Text("Dismiss") } + TextButton(onClick = { store.update { it.copy(removalStatus = null) } }) { Text(tr("Dismiss")) } } } } @@ -3580,21 +3582,21 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { // false (it no longer holds enabled + connected + NOT_ASKED), which also keeps the // on-screen state honest — re-enabling re-offers the dialog. onDismissRequest = { store.update { it.copy(enabled = false) } }, - title = { Text("How much history should we export?") }, + title = { Text(tr("How much history should we export?")) }, // No "change this later" promise: there is no UI to change backfillChoice short of // "Remove PulseLoop data", which resets it to NOT_ASKED and re-offers this dialog. - text = { Text("Exporting all history can take a while on the first run.") }, + text = { Text(tr("Exporting all history can take a while on the first run.")) }, confirmButton = { TextButton(onClick = { store.update { it.copy(backfillChoice = HealthConnectPrefs.BackfillChoice.EXPORT_ALL) } HealthConnectExportWorker.enqueue(context) // answer the gate → run the pass - }) { Text("Sync all history") } + }) { Text(tr("Sync all history")) } }, dismissButton = { TextButton(onClick = { store.update { it.copy(backfillChoice = HealthConnectPrefs.BackfillChoice.EXPORT_NEW_ONLY) } HealthConnectExportWorker.enqueue(context) // stamps watermarks, exports nothing - }) { Text("Only new data from now on") } + }) { Text(tr("Only new data from now on")) } }, ) } @@ -3605,18 +3607,18 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { if (showRevokeResetDialog) { AlertDialog( onDismissRequest = { showRevokeResetDialog = false; store.update { it.copy(revocationOfferDismissed = true) } }, - title = { Text("Health Connect permissions revoked") }, - text = { Text("PulseLoop no longer has any Health Connect permissions. Reset the export so a later re-grant re-exports your history?") }, + title = { Text(tr("Health Connect permissions revoked")) }, + text = { Text(tr("PulseLoop no longer has any Health Connect permissions. Reset the export so a later re-grant re-exports your history?")) }, confirmButton = { TextButton(onClick = { store.clearWatermarks() store.update { it.copy(lastSyncAt = null, lastSyncSummary = null, revocationOfferDismissed = true) } showRevokeResetDialog = false - statusMessage = "Export reset — re-grant permissions to sync again." - }) { Text("Reset export") } + statusMessage = tr("Export reset — re-grant permissions to sync again.") + }) { Text(tr("Reset export")) } }, dismissButton = { - TextButton(onClick = { showRevokeResetDialog = false; store.update { it.copy(revocationOfferDismissed = true) } }) { Text("Not now") } + TextButton(onClick = { showRevokeResetDialog = false; store.update { it.copy(revocationOfferDismissed = true) } }) { Text(tr("Not now")) } }, ) } @@ -3626,8 +3628,8 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { if (showRemoveDialog) { AlertDialog( onDismissRequest = { showRemoveDialog = false }, - title = { Text("Remove PulseLoop data?") }, - text = { Text("This deletes every record PulseLoop wrote to Health Connect and resets the export. It cannot be undone, and your ring data in PulseLoop is not affected.") }, + title = { Text(tr("Remove PulseLoop data?")) }, + text = { Text(tr("This deletes every record PulseLoop wrote to Health Connect and resets the export. It cannot be undone, and your ring data in PulseLoop is not affected.")) }, confirmButton = { TextButton(onClick = { showRemoveDialog = false @@ -3636,10 +3638,10 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { // deleted, the rest alive, and the watermarks never cleared — unrepairable // from a write-only client. The worker reports back via prefs.removalStatus. HealthConnectRemovalWorker.enqueue(context) - }) { Text("Remove") } + }) { Text(tr("Remove")) } }, dismissButton = { - TextButton(onClick = { showRemoveDialog = false }) { Text("Cancel") } + TextButton(onClick = { showRemoveDialog = false }) { Text(tr("Cancel")) } }, ) } @@ -3691,7 +3693,7 @@ private fun BatteryRuntimeEstimate(samples: List) { } if (estimate == null) { Text( - "Not enough of a trend to estimate runtime yet — it appears after a few hours of discharge.", + tr("Not enough of a trend to estimate runtime yet — it appears after a few hours of discharge."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -3740,14 +3742,14 @@ private fun CoachManagedCard(fields: Set, Column(Modifier.weight(1f)) { Text("Coach goal: ${g.description}", fontWeight = FontWeight.Medium) Text( - if (managed.isEmpty()) "Your goal doesn't set any of these." - else "Set by your goal: " + managed.joinToString(", ") { it.label } + ". Change one here and it stops following.", + if (managed.isEmpty()) tr("Your goal doesn't set any of these.") + else tr("Set by your goal: ") + managed.joinToString(", ") { it.label } + ". Change one here and it stops following.", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } Switch(checked = following.size == fields.size, onCheckedChange = null) } - Text("Let my goal manage these", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(tr("Let my goal manage these"), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) } } } @@ -3778,9 +3780,9 @@ private fun AutoBackupCard() { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Automatic backups", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Automatic backups"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text( - "Saves the same file as Export to a folder you choose, and keeps the latest 5.", + tr("Saves the same file as Export to a folder you choose, and keeps the latest 5."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -3795,7 +3797,7 @@ private fun AutoBackupCard() { "Folder: ${folderName ?: "not chosen"}", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f), ) - TextButton(onClick = { picker.launch(null) }) { Text(if (folderName == null) "Choose" else "Change") } + TextButton(onClick = { picker.launch(null) }) { Text(if (folderName == null) tr("Choose") else tr("Change")) } } Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { listOf(1 to "Daily", 7 to "Weekly").forEach { (d, label) -> @@ -3819,7 +3821,7 @@ private fun AutoBackupCard() { } }, modifier = Modifier.fillMaxWidth(), - ) { Text(if (running) "Backing up…" else "Back up now") } + ) { Text(if (running) tr("Backing up…") else tr("Back up now")) } } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt index 700d5b4d..58e2123e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ui.theme.dither import androidx.compose.foundation.Canvas import androidx.compose.foundation.background @@ -128,15 +130,15 @@ private fun androidx.compose.foundation.lazy.LazyListScope.dayItems( val noData = SleepInsights.noDataState(SleepRangeKey.DAY) item { SleepHeroCard(label = noData.label, value = noData.value, support = noData.support, score = null, scoreLabel = null, noData = true) } item { - VisualizationCard(eyebrow = "Stages", title = "Sleep architecture", legend = false) { + VisualizationCard(eyebrow = tr("Stages"), title = tr("Sleep architecture"), legend = false) { Column( Modifier.fillMaxWidth().height(180.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { - Text("No sleep recorded", fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) + Text(tr("No sleep recorded"), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) Text( - "Wear your ring overnight to see your hypnogram here.", + tr("Wear your ring overnight to see your hypnogram here."), fontSize = 12.sp, color = PulseColors.textMuted, ) } @@ -154,7 +156,7 @@ private fun androidx.compose.foundation.lazy.LazyListScope.dayItems( val summary = state.daySummary val fallback = state.coach CoachMessageCard( - headline = summary?.title ?: fallback?.headline ?: "Sleep insights", + headline = summary?.title ?: fallback?.headline ?: tr("Sleep insights"), body = summary?.body ?: fallback?.body ?: "", chips = summary?.let { parseChipsJson(it.chipsJSON) } ?: fallback?.chips ?: emptyList(), onTap = { navController?.navigate("coach") }, @@ -172,7 +174,7 @@ private fun androidx.compose.foundation.lazy.LazyListScope.sessionPageItems( ) { item { SessionHero(session, blocks, goalMinutes) } item { - VisualizationCard(eyebrow = "Stages", title = "Sleep architecture", legend = true) { + VisualizationCard(eyebrow = tr("Stages"), title = tr("Sleep architecture"), legend = true) { SleepHypnogram(blocks = remember(blocks) { com.pulseloop.service.hypnogramBlocks(blocks) }, spanMin = session.spanMinutes, startTs = session.startAt) } } @@ -203,14 +205,14 @@ private fun SessionHero(session: SleepSessionEntity, blocks: List 14) maxOf(1, bars.size / 6) else 1 val summary = remember(bars, goalMin) { val tracked = bars.filter { it.present }.mapNotNull { it.durationMin } - if (tracked.isEmpty()) "Nightly sleep: no nights tracked in this range" + if (tracked.isEmpty()) tr("Nightly sleep: no nights tracked in this range") else "Nightly sleep: latest ${SleepFormat.duration(tracked.last())}, " + "range ${SleepFormat.duration(tracked.min())}–${SleepFormat.duration(tracked.max())}, " + "${tracked.size} of ${bars.size} nights tracked" + @@ -877,7 +879,7 @@ private fun SleepDayNavHeader(state: SleepViewModel.SleepState, viewModel: Sleep verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, ) { - NavChevron(Icons.Filled.ChevronLeft, "Previous day", canOlder) { viewModel?.stepDay(older = true) } + NavChevron(Icons.Filled.ChevronLeft, tr("Previous day"), canOlder) { viewModel?.stepDay(older = true) } Column( Modifier .weight(1f) @@ -897,7 +899,7 @@ private fun SleepDayNavHeader(state: SleepViewModel.SleepState, viewModel: Sleep letterSpacing = 0.5.sp, color = PulseColors.textSecondary, ) } - NavChevron(Icons.Filled.ChevronRight, "Next day", canNewer) { viewModel?.stepDay(older = false) } + NavChevron(Icons.Filled.ChevronRight, tr("Next day"), canNewer) { viewModel?.stepDay(older = false) } } if (showPicker) { @@ -959,9 +961,9 @@ private fun SleepDayPickerDialog( confirmButton = { TextButton(onClick = { state.selectedDateMillis?.let { onPick(utcMillisToLocalDayKey(it)) } ?: onDismiss() - }) { Text("Done") } + }) { Text(tr("Done")) } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(tr("Cancel")) } }, ) { DatePicker(state = state, title = null) } @@ -985,8 +987,8 @@ private fun dayLabel(dayMillis: Long): String { val daysAgo = ((today - dayMillis) / 86_400_000L).toInt() val date = java.time.Instant.ofEpochMilli(dayMillis).atZone(java.time.ZoneId.systemDefault()) return when { - daysAgo <= 0 -> "Today" - daysAgo == 1 -> "Yesterday" + daysAgo <= 0 -> tr("Today") + daysAgo == 1 -> tr("Yesterday") daysAgo < 7 -> date.format(java.time.format.DateTimeFormatter.ofPattern("EEEE")) date.year == java.time.Year.now().value -> date.format(java.time.format.DateTimeFormatter.ofPattern("EEE, MMM d")) else -> date.format(java.time.format.DateTimeFormatter.ofPattern("MMM d, yyyy")) @@ -1007,10 +1009,10 @@ private fun daySubLabel(dayMillis: Long): String { private fun clockTime(ts: Long): String = SleepFormat.clockTime(ts) private fun qualityText(label: SleepQualityLabel): String = when (label) { - SleepQualityLabel.EXCELLENT -> "Excellent" - SleepQualityLabel.GOOD -> "Good" - SleepQualityLabel.FAIR -> "Fair" - SleepQualityLabel.NEEDS_WORK -> "Needs work" + SleepQualityLabel.EXCELLENT -> tr("Excellent") + SleepQualityLabel.GOOD -> tr("Good") + SleepQualityLabel.FAIR -> tr("Fair") + SleepQualityLabel.NEEDS_WORK -> tr("Needs work") } internal fun parseChipsJson(json: String?): List { @@ -1052,9 +1054,9 @@ private fun SleepRecordsCard( var pendingRun by remember { mutableStateOf(null) } var editingRun by remember { mutableStateOf(null) } VisualizationCard( - eyebrow = "Records", + eyebrow = tr("Records"), // One run only happens on a carousel page, which may be a nap rather than a night. - title = if (runs.size == 1) "The ring recorded this as one record" + title = if (runs.size == 1) tr("The ring recorded this as one record") else "The ring recorded this night in ${runs.size} parts", legend = false, ) { @@ -1083,7 +1085,7 @@ private fun SleepRecordsCard( IconButton(onClick = { editingRun = run }) { Icon( Icons.Filled.Edit, - contentDescription = "Edit this record's times", + contentDescription = tr("Edit this record's times"), tint = PulseColors.textMuted, modifier = Modifier.size(18.dp), ) @@ -1094,7 +1096,7 @@ private fun SleepRecordsCard( IconButton(onClick = { pendingRun = run }) { Icon( Icons.Filled.DeleteOutline, - contentDescription = "Delete this record", + contentDescription = tr("Delete this record"), tint = PulseColors.textMuted, modifier = Modifier.size(18.dp), ) @@ -1127,7 +1129,7 @@ private fun SleepRecordsCard( val updated = viewModel?.editSleepRecord(session.id, run.recordStartAt, newStart, newEnd) ?: false if (!updated) { android.widget.Toast.makeText( - context, "Couldn't update this record", android.widget.Toast.LENGTH_SHORT, + context, tr("Couldn't update this record"), android.widget.Toast.LENGTH_SHORT, ).show() } } @@ -1138,7 +1140,7 @@ private fun SleepRecordsCard( pendingRun?.let { run -> AlertDialog( onDismissRequest = { pendingRun = null }, - title = { Text("Delete this record?") }, + title = { Text(tr("Delete this record?")) }, text = { Text( "${SleepFormat.clockTime(run.startAt)} – ${SleepFormat.clockTime(run.endAt)} " + @@ -1152,14 +1154,14 @@ private fun SleepRecordsCard( val removed = viewModel?.deleteSleepRecord(session.id, run.recordStartAt) ?: false if (!removed) { android.widget.Toast.makeText( - context, "Couldn't delete this record", android.widget.Toast.LENGTH_SHORT, + context, tr("Couldn't delete this record"), android.widget.Toast.LENGTH_SHORT, ).show() } } - }) { Text("Delete", color = PulseColors.danger) } + }) { Text(tr("Delete"), color = PulseColors.danger) } }, dismissButton = { - TextButton(onClick = { pendingRun = null }) { Text("Keep") } + TextButton(onClick = { pendingRun = null }) { Text(tr("Keep")) } }, ) } @@ -1182,11 +1184,11 @@ private fun SleepRecordEditDialog( AlertDialog( onDismissRequest = onDismiss, - title = { Text("Edit sleep record") }, + title = { Text(tr("Edit sleep record")) }, text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { Text( - "Adjust start or end time to trim this record. Stages outside the new range will be removed.", + tr("Adjust start or end time to trim this record. Stages outside the new range will be removed."), style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = PulseColors.textMuted, ) @@ -1217,7 +1219,7 @@ private fun SleepRecordEditDialog( } if (currentStart >= currentEnd) { Text( - "Start time must be before end time.", + tr("Start time must be before end time."), color = PulseColors.danger, fontSize = 12.sp, ) @@ -1229,11 +1231,11 @@ private fun SleepRecordEditDialog( onClick = { onSave(currentStart, currentEnd) }, enabled = currentStart < currentEnd && (currentStart != run.startAt || currentEnd != run.endAt), ) { - Text("Save") + Text(tr("Save")) } }, dismissButton = { - TextButton(onClick = onDismiss) { Text("Cancel") } + TextButton(onClick = onDismiss) { Text(tr("Cancel")) } }, ) @@ -1250,7 +1252,7 @@ private fun SleepRecordEditDialog( AlertDialog( onDismissRequest = { pickingTime = null }, - title = { Text(if (which == "start") "Adjust start time" else "Adjust end time") }, + title = { Text(if (which == "start") tr("Adjust start time") else tr("Adjust end time")) }, // The dial doesn't fit a landscape dialog; the keyboard entry form does. text = { if (landscape) TimeInput(state = timeState) else TimePicker(state = timeState) }, confirmButton = { @@ -1264,10 +1266,10 @@ private fun SleepRecordEditDialog( currentEnd = resolved } pickingTime = null - }) { Text("Done") } + }) { Text(tr("Done")) } }, dismissButton = { - TextButton(onClick = { pickingTime = null }) { Text("Cancel") } + TextButton(onClick = { pickingTime = null }) { Text(tr("Cancel")) } }, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt index 138654f6..1f11d6dc 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable @@ -96,7 +98,7 @@ fun TodayGlance( ) { Icon(Icons.Filled.Warning, null, Modifier.size(16.dp), tint = PulseColors.warning) Text( - "Unusual last night: " + alert.joinToString(", ") { it.title.lowercase() }, + tr("Unusual last night: ") + alert.joinToString(", ") { it.title.lowercase() }, fontSize = 13.sp, color = PulseColors.textPrimary, maxLines = 2, overflow = TextOverflow.Ellipsis, ) @@ -123,10 +125,10 @@ fun TodayGlance( @Composable fun QuickLogRow(onMeal: () -> Unit, onTag: () -> Unit, onMeasure: () -> Unit, onWorkout: () -> Unit) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - QuickChip("Meal", Icons.Filled.Restaurant, PulseColors.calories, Modifier.weight(1f), onMeal) - QuickChip("Tag day", Icons.Filled.LocalOffer, PulseColors.accent, Modifier.weight(1f), onTag) - QuickChip("Measure", Icons.Filled.FavoriteBorder, PulseColors.heartRate, Modifier.weight(1f), onMeasure) - QuickChip("Workout", Icons.Filled.DirectionsRun, PulseColors.steps, Modifier.weight(1f), onWorkout) + QuickChip(tr("Meal"), Icons.Filled.Restaurant, PulseColors.calories, Modifier.weight(1f), onMeal) + QuickChip(tr("Tag day"), Icons.Filled.LocalOffer, PulseColors.accent, Modifier.weight(1f), onTag) + QuickChip(tr("Measure"), Icons.Filled.FavoriteBorder, PulseColors.heartRate, Modifier.weight(1f), onMeasure) + QuickChip(tr("Workout"), Icons.Filled.DirectionsRun, PulseColors.steps, Modifier.weight(1f), onWorkout) } } @@ -168,7 +170,7 @@ fun LastNightCard( .padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Text("LAST NIGHT", fontSize = 11.sp, letterSpacing = 1.8.sp, color = PulseColors.sleep) + Text(tr("LAST NIGHT"), fontSize = 11.sp, letterSpacing = 1.8.sp, color = PulseColors.sleep) Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(12.dp)) { Text(durationText, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) score?.let { @@ -198,10 +200,10 @@ fun LastNightCard( fun MealSheet(onDismiss: () -> Unit, onPick: (start: String) -> Unit) { ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(), containerColor = PulseColors.secondaryBackground) { Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text("Log a meal", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - SheetOption("Photo", "Snap your plate; the AI estimates it", Icons.Filled.CameraAlt) { onPick("photo") } - SheetOption("Barcode", "Scan a packaged food", Icons.Filled.QrCodeScanner) { onPick("barcode") } - SheetOption("Add by hand", "Type the name and calories", Icons.Filled.Add) { onPick("add") } + Text(tr("Log a meal"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + SheetOption(tr("Photo"), tr("Snap your plate; the AI estimates it"), Icons.Filled.CameraAlt) { onPick("photo") } + SheetOption(tr("Barcode"), tr("Scan a packaged food"), Icons.Filled.QrCodeScanner) { onPick("barcode") } + SheetOption(tr("Add by hand"), tr("Type the name and calories"), Icons.Filled.Add) { onPick("add") } } } } @@ -212,9 +214,9 @@ fun MealSheet(onDismiss: () -> Unit, onPick: (start: String) -> Unit) { fun TagDaySheet(db: PulseLoopDatabase, onDismiss: () -> Unit, onSeeEffects: () -> Unit) { ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), containerColor = PulseColors.secondaryBackground) { Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 32.dp)) { - JournalTagsCard(db, java.time.LocalDate.now(), "Tag your day", allowYesterday = true) { + JournalTagsCard(db, java.time.LocalDate.now(), tr("Tag your day"), allowYesterday = true) { Text( - "See what affects you", + tr("See what affects you"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, modifier = Modifier .heightIn(min = 48.dp) @@ -272,7 +274,7 @@ fun CoachBriefSheet( .padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Text("TODAY'S BRIEF", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.accent) + Text(tr("TODAY'S BRIEF"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.accent) Text(title, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(body, fontSize = 15.sp, lineHeight = 22.sp, color = PulseColors.textSecondary) if (chips.isNotEmpty()) { @@ -298,7 +300,7 @@ fun CoachBriefSheet( androidx.compose.material3.Button( onClick = onAsk, modifier = Modifier.fillMaxWidth(), - ) { Text("Ask the coach about it") } + ) { Text(tr("Ask the coach about it")) } } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt index 9bd83775..44433405 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.ui.draw.clip @@ -294,12 +296,12 @@ fun TodayScreen( } TodayMoments.Moment.TAG_DAY -> item { JournalTagsCard( - db, java.time.LocalDate.now(), "Tag your day", + db, java.time.LocalDate.now(), tr("Tag your day"), tags = com.pulseloop.service.JournalInsights.Tag.entries.take(6), allowYesterday = true, ) { Text( - "See what affects you", + tr("See what affects you"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.readiness, modifier = Modifier .heightIn(min = 48.dp) @@ -360,7 +362,7 @@ fun TodayScreen( val summary = state.coachSummary val fromCoach = coachEnabled && summary != null CoachBriefSheet( - title = if (fromCoach) summary!!.title else (readiness?.let { "Today" } ?: hero.title), + title = if (fromCoach) summary!!.title else (readiness?.let { tr("Today") } ?: hero.title), body = if (fromCoach) summary!!.body else listOfNotNull(readiness?.let { com.pulseloop.service.ReadinessCopy.headline(it) }, hero.summary).joinToString("\n\n"), chips = if (fromCoach) parseChips(summary!!.chipsJSON) else hero.chips.map { it.label }, @@ -513,7 +515,7 @@ private fun BloodPressureTile( val dia = vitals.bpDiastolic?.toDouble() Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { if (sys == null || dia == null) { - Text("No reading", fontSize = 12.sp, color = PulseColors.textMuted) + Text(tr("No reading"), fontSize = 12.sp, color = PulseColors.textMuted) } else { val sysZones = VitalsThresholdEngine.zones(MetricKind.BLOOD_PRESSURE, vitals.profile) val diaZones = VitalsThresholdEngine.diastolicReferenceZones() @@ -563,14 +565,14 @@ private data class Hero(val title: String, val summary: String, val chips: List< /** Ported from TodayInsights.deriveHero (TodayView.swift), minus the iOS calibration branch. */ private fun deriveHero(state: TodayViewModel.TodayState, sleep: SleepViewModel.SleepState): Hero { val steps = state.steps ?: return Hero( - title = "Waiting for first sync", + title = tr("Waiting for first sync"), summary = if (com.pulseloop.health.source.HealthConnectSource.enabledNow) - "Importing from Health Connect. Your steps, sleep and heart rate appear once your device's app has synced." - else "Sync your ring to start collecting movement, heart rate, blood oxygen, and recovery context.", + tr("Importing from Health Connect. Your steps, sleep and heart rate appear once your device's app has synced.") + else tr("Sync your ring to start collecting movement, heart rate, blood oxygen, and recovery context."), chips = listOf( - ToneChip("Baseline pending", ChipTone.WARN), - ToneChip(if (state.heartRate == null) "HR pending" else "HR collected", ChipTone.NEUTRAL), - ToneChip("Sleep pending", ChipTone.WARN), + ToneChip(tr("Baseline pending"), ChipTone.WARN), + ToneChip(if (state.heartRate == null) tr("HR pending") else tr("HR collected"), ChipTone.NEUTRAL), + ToneChip(tr("Sleep pending"), ChipTone.WARN), ), ) @@ -581,9 +583,9 @@ private fun deriveHero(state: TodayViewModel.TodayState, sleep: SleepViewModel.S val stepsDelta = if (base == 0.0) 0 else (((steps - base) / base) * 100).toInt() val title = when { - stepsDelta >= 20 -> "Building momentum" - stepsDelta <= -20 -> "Take it easy" - else -> "Steady build" + stepsDelta >= 20 -> tr("Building momentum") + stepsDelta <= -20 -> tr("Take it easy") + else -> tr("Steady build") } val hrStr = state.heartRate?.let { "$it bpm" } ?: "—" @@ -610,8 +612,8 @@ private fun deriveHero(state: TodayViewModel.TodayState, sleep: SleepViewModel.S if (series.size > 1) "Steps ${if (stepsDelta >= 0) "+" else ""}$stepsDelta%" else "Steps collected", stepsTone, ), - ToneChip(if (state.heartRate == null) "HR pending" else "HR collected", hrTone), - ToneChip(if (night != null) "Sleep synced" else "Sleep pending", if (night != null) ChipTone.NEUTRAL else ChipTone.WARN), + ToneChip(if (state.heartRate == null) tr("HR pending") else tr("HR collected"), hrTone), + ToneChip(if (night != null) tr("Sleep synced") else tr("Sleep pending"), if (night != null) ChipTone.NEUTRAL else ChipTone.WARN), ), ) } @@ -641,7 +643,7 @@ internal data class FoodTotals( /** Half-width Nutrition tile: calories eaten against the goal, macros, and a one-tap log. */ @Composable private fun NutritionTile(food: FoodTotals?, modifier: Modifier, onLog: () -> Unit, onTap: () -> Unit) { - TodayTile(label = "Nutrition", color = PulseColors.calories, modifier = modifier, onTap = onTap) { + TodayTile(label = tr("Nutrition"), color = PulseColors.calories, modifier = modifier, onTap = onTap) { val kcal = food?.kcal ?: 0.0 Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(4.dp)) { Text(Formats.count(kcal.toInt()), fontSize = 22.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, maxLines = 1) @@ -662,7 +664,7 @@ private fun NutritionTile(food: FoodTotals?, modifier: Modifier, onLog: () -> Un fontSize = 11.sp, color = PulseColors.textSecondary, maxLines = 1, ) } else { - Text("Nothing logged yet", fontSize = 11.sp, color = PulseColors.textMuted, maxLines = 1) + Text(tr("Nothing logged yet"), fontSize = 11.sp, color = PulseColors.textMuted, maxLines = 1) } Text( "+ Log meal", diff --git a/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt b/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt index 4418b481..0ebd579b 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState @@ -45,8 +47,8 @@ fun WhatChangedScreen(onBack: () -> Unit) { Column(Modifier.fillMaxSize().background(PulseColors.background)) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { - IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } - Text("What changed", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } + Text(tr("What changed"), modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) } Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), @@ -58,10 +60,10 @@ fun WhatChangedScreen(onBack: () -> Unit) { Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { - Text("LAST 3 DAYS", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("LAST 3 DAYS"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) if (recent.isEmpty()) { - Text("Nothing stood out", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("Your nights look like your usual. That's an answer too.", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(tr("Nothing stood out"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Your nights look like your usual. That's an answer too."), fontSize = 13.sp, color = PulseColors.textSecondary) } else { recent.distinctBy { it.kind }.forEach { FindingRow(it) } } @@ -80,7 +82,7 @@ fun WhatChangedScreen(onBack: () -> Unit) { } } Text( - "Each night is compared with your own previous four weeks once there are two weeks to compare with. " + + tr("Each night is compared with your own previous four weeks once there are two weeks to compare with. ") + "Findings carry the formula version that made them (now v${Algorithms.VERSION}). Patterns, not diagnoses.", fontSize = 11.sp, color = PulseColors.textMuted, ) diff --git a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt index 01f61992..513f14fb 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.tr + import android.content.res.Configuration import com.pulseloop.ui.theme.dither import androidx.compose.foundation.background @@ -123,7 +125,7 @@ fun WorkoutSummaryScreen( ) { item { Row(Modifier.fillMaxWidth()) { - CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, "Back", tint = PulseColors.textSecondary, onTap = onBack) + CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, tr("Back"), tint = PulseColors.textSecondary, onTap = onBack) Spacer(Modifier.weight(1f)) if (s.useGps && points.any { it.accepted }) { CircleIconButton(Icons.Filled.Share, "Export route as GPX", tint = PulseColors.textSecondary, onTap = { @@ -143,9 +145,9 @@ fun WorkoutSummaryScreen( }) Spacer(Modifier.width(10.dp)) } - CircleIconButton(Icons.Filled.Edit, "Edit workout", tint = PulseColors.accent, onTap = { editing = true }) + CircleIconButton(Icons.Filled.Edit, tr("Edit workout"), tint = PulseColors.accent, onTap = { editing = true }) Spacer(Modifier.width(10.dp)) - CircleIconButton(Icons.Filled.Delete, "Delete workout", tint = PulseColors.danger, onTap = { confirmDelete = true }) + CircleIconButton(Icons.Filled.Delete, tr("Delete workout"), tint = PulseColors.danger, onTap = { confirmDelete = true }) } } item { @@ -175,7 +177,7 @@ fun WorkoutSummaryScreen( if (confirmDelete) { AlertDialog( onDismissRequest = { confirmDelete = false }, - title = { Text("Delete workout?") }, + title = { Text(tr("Delete workout?")) }, text = { Text("This removes the session and its recorded route. This can't be undone.") }, confirmButton = { TextButton(onClick = { @@ -188,9 +190,9 @@ fun WorkoutSummaryScreen( com.pulseloop.health.HealthConnectWorkoutDeletion.removeSessionRecords(context, s.id) onBack() } - }) { Text("Delete", color = PulseColors.danger) } + }) { Text(tr("Delete"), color = PulseColors.danger) } }, - dismissButton = { TextButton(onClick = { confirmDelete = false }) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = { confirmDelete = false }) { Text(tr("Cancel")) } }, ) } @@ -206,7 +208,7 @@ fun WorkoutSummaryScreen( reload() editing = false } else { - editError = "Couldn't save these changes. Check the times and try again." + editError = tr("Couldn't save these changes. Check the times and try again.") } } }, @@ -236,11 +238,11 @@ private fun EditWorkoutSheet( val pauseMs = (session.totalPauseSeconds * 1000).toLong() val validationMessage = when { - endedAt > System.currentTimeMillis() -> "End time can't be in the future." + endedAt > System.currentTimeMillis() -> tr("End time can't be in the future.") endedAt - startedAt <= pauseMs -> if (session.totalPauseSeconds > 0) "The window must be longer than the ${maxOf(1, (session.totalPauseSeconds / 60).toInt())} min of pauses in this workout." - else "End must be after the start." + else tr("End must be after the start.") else -> null } @@ -249,9 +251,9 @@ private fun EditWorkoutSheet( Modifier.fillMaxWidth().padding(horizontal = 20.dp).padding(bottom = 24.dp), verticalArrangement = Arrangement.spacedBy(14.dp), ) { - Text("Edit workout", fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Edit workout"), fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - EditFieldRow("Activity") { + EditFieldRow(tr("Activity")) { Box { OutlinedButton(onClick = { typeExpanded = true }) { Icon(ActivityMeta.icon(type), null, tint = PulseColors.accent, modifier = Modifier.size(16.dp)) @@ -270,17 +272,17 @@ private fun EditWorkoutSheet( } } - EditFieldRow("Starts") { + EditFieldRow(tr("Starts")) { DateTimeButton(startedAt) { startedAt = it } } - EditFieldRow("Ends") { + EditFieldRow(tr("Ends")) { DateTimeButton(endedAt) { endedAt = it } } val message = validationMessage ?: saveError Text( message - ?: "Distance, calories, and heart-rate stats are recalculated for the new window.", + ?: tr("Distance, calories, and heart-rate stats are recalculated for the new window."), fontSize = 12.sp, color = if (message != null) PulseColors.warning else PulseColors.textMuted, textAlign = androidx.compose.ui.text.style.TextAlign.Center, @@ -296,11 +298,11 @@ private fun EditWorkoutSheet( ) { Icon(Icons.Filled.Check, null) Spacer(Modifier.width(8.dp)) - Text("Save changes", fontWeight = FontWeight.SemiBold) + Text(tr("Save changes"), fontWeight = FontWeight.SemiBold) } TextButton(onClick = onDismiss, modifier = Modifier.fillMaxWidth().height(52.dp)) { - Text("Cancel", color = PulseColors.textPrimary, fontWeight = FontWeight.SemiBold) + Text(tr("Cancel"), color = PulseColors.textPrimary, fontWeight = FontWeight.SemiBold) } } } @@ -360,9 +362,9 @@ internal fun DateTimeButton(valueMillis: Long, onChange: (Long) -> Unit) { } showDate = false showTime = true - }) { Text("Next") } + }) { Text(tr("Next")) } }, - dismissButton = { TextButton(onClick = { showDate = false }) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = { showDate = false }) { Text(tr("Cancel")) } }, ) { DatePicker(state = state, title = null) } } @@ -377,7 +379,7 @@ internal fun DateTimeButton(valueMillis: Long, onChange: (Long) -> Unit) { ) AlertDialog( onDismissRequest = { showTime = false }, - title = { Text("Time") }, + title = { Text(tr("Time")) }, // The dial doesn't fit a landscape dialog; the keyboard entry form does. text = { if (landscape) TimeInput(state = timeState) else TimePicker(state = timeState) }, confirmButton = { @@ -390,9 +392,9 @@ internal fun DateTimeButton(valueMillis: Long, onChange: (Long) -> Unit) { }.timeInMillis onChange(result) showTime = false - }) { Text("Done") } + }) { Text(tr("Done")) } }, - dismissButton = { TextButton(onClick = { showTime = false }) { Text("Cancel") } }, + dismissButton = { TextButton(onClick = { showTime = false }) { Text(tr("Cancel")) } }, ) } } @@ -442,8 +444,8 @@ private fun dateRange(s: ActivitySessionEntity): String { it.get(Calendar.YEAR) == startCal.get(Calendar.YEAR) && it.get(Calendar.DAY_OF_YEAR) == startCal.get(Calendar.DAY_OF_YEAR) } val day = when { - sameDay -> "Today" - yesterday -> "Yesterday" + sameDay -> tr("Today") + yesterday -> tr("Yesterday") else -> SimpleDateFormat("MMM d", Locale.getDefault()).format(Date(s.startedAt)) } val ended = s.endedAt ?: return day @@ -622,13 +624,13 @@ private fun MissingWorkout(onBack: () -> Unit) { ) { Icon(Icons.AutoMirrored.Filled.DirectionsRun, null, tint = PulseColors.textMuted, modifier = Modifier.size(48.dp)) Spacer(Modifier.height(12.dp)) - Text("Workout not found", fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + Text(tr("Workout not found"), fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) Spacer(Modifier.height(6.dp)) Text( - "This workout is no longer in local storage. It may have been deleted or replaced.", + tr("This workout is no longer in local storage. It may have been deleted or replaced."), fontSize = 14.sp, color = PulseColors.textMuted, textAlign = TextAlign.Center, ) Spacer(Modifier.height(16.dp)) - TextButton(onClick = onBack) { Text("Back", color = PulseColors.accent) } + TextButton(onClick = onBack) { Text(tr("Back"), color = PulseColors.accent) } } } diff --git a/app/src/main/java/com/pulseloop/ui/theme/FairyMode.kt b/app/src/main/java/com/pulseloop/ui/theme/FairyMode.kt index 4ff8eb46..b366f219 100644 --- a/app/src/main/java/com/pulseloop/ui/theme/FairyMode.kt +++ b/app/src/main/java/com/pulseloop/ui/theme/FairyMode.kt @@ -46,18 +46,18 @@ object FairyMode { fun onProfileName(name: String?) { val match = matches(name) if (match && !on && !celebrating) celebrating = true - if (!match && on) setOn(false) + if (!match && on) persist(false) } /** Called by the overlay at the moment of transformation, under the sparkles. */ - fun transform() = setOn(true) + fun transform() = persist(true) fun celebrationDone() { celebrating = false - if (!on) setOn(true) + if (!on) persist(true) } - private fun setOn(value: Boolean) { + private fun persist(value: Boolean) { on = value prefs?.edit()?.putBoolean("on", value)?.apply() } diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt index 6232addf..6640bd1c 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.viewmodels +import com.pulseloop.ui.i18n.tr + import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.pulseloop.data.ActivityBucketDeletion @@ -960,7 +962,7 @@ class CoachViewModel( ) private val greeting = ChatMessage("assistant", - "Hi! I'm your PulseLoop coach. I can answer questions about your sleep, heart rate, activity, and recovery. What would you like to know?") + tr("Hi! I'm your PulseLoop coach. I can answer questions about your sleep, heart rate, activity, and recovery. What would you like to know?")) private val _state = MutableStateFlow(CoachState(messages = listOf(greeting))) val state: StateFlow = _state.asStateFlow() @@ -1134,7 +1136,11 @@ class CoachViewModel( // ──────────────────────── Vital Detail ──────────────────────── -enum class Period(val label: String) { DAY("Today"), WEEK("Week"), MONTH("Month") } +enum class Period(private val en: String) { + DAY(tr("Today")), WEEK(tr("Week")), MONTH(tr("Month")); + /** Translated when read, not when the enum loads, so a language change shows at once. */ + val label: String get() = tr(en) +} /** * VitalDetailViewModel — drives a single-metric detail screen with Today/Week/Month diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt index 3d1bd1e1..ac14ce32 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.viewmodels +import com.pulseloop.ui.i18n.tr + import com.pulseloop.service.BaselineStats import com.pulseloop.service.MeasurementContext import com.pulseloop.service.MetricContext @@ -214,7 +216,7 @@ object VitalsCardFactory { metric = MetricKind.HEART_RATE, title = MetricKind.HEART_RATE.title, valueText = valueText, latestValue = latest, unitText = if (latest != null) "bpm range" else null, - statusText = interp?.displayLabel ?: "No reading", + statusText = interp?.displayLabel ?: tr("No reading"), statusToken = interp?.statusColorToken ?: VitalColorToken.Neutral, subtitleText = "$resting · $peak", samples = samples, zones = VitalsThresholdEngine.zones(MetricKind.HEART_RATE, profile), @@ -240,7 +242,7 @@ object VitalsCardFactory { metric = MetricKind.SPO2, title = MetricKind.SPO2.title, valueText = averageLabel(samples, latest), latestValue = latest, unitText = if (latest != null) "% avg" else null, - statusText = interp?.displayLabel ?: "No reading", + statusText = interp?.displayLabel ?: tr("No reading"), statusToken = interp?.statusColorToken ?: VitalColorToken.Neutral, subtitleText = subtitle, samples = samples, zones = VitalsThresholdEngine.zones(MetricKind.SPO2, profile), @@ -273,13 +275,13 @@ object VitalsCardFactory { val subtitle = if (baseline != null && baseline.isEstablished) { "Baseline ${baseline.mean.toInt()} ms" } else { - "Building baseline" + tr("Building baseline") } return VitalCardState( metric = MetricKind.HRV, title = MetricKind.HRV.title, valueText = latest?.let { "${it.toInt()}" } ?: "--", latestValue = latest, unitText = if (latest != null) "ms" else null, - statusText = interp?.displayLabel ?: "Building baseline", + statusText = interp?.displayLabel ?: tr("Building baseline"), statusToken = interp?.statusColorToken ?: VitalColorToken.Neutral, subtitleText = subtitle, samples = samples, @@ -304,11 +306,11 @@ object VitalsCardFactory { val latest = samples.lastOrNull()?.value val quality = quality(metric, samples.lastOrNull()?.timestampMs, inputs) val interp = latest?.let { VitalsThresholdEngine.interpret(it, metric, profile) } - val subtitle = if (metric == MetricKind.STRESS) "Lower is calmer" else "Ring model estimate" + val subtitle = if (metric == MetricKind.STRESS) tr("Lower is calmer") else tr("Ring model estimate") return VitalCardState( metric = metric, title = metric.title, valueText = latest?.let { "${it.toInt()}" } ?: "--", latestValue = latest, unitText = null, - statusText = interp?.displayLabel ?: "No data", + statusText = interp?.displayLabel ?: tr("No data"), statusToken = interp?.statusColorToken ?: VitalColorToken.Neutral, subtitleText = subtitle, samples = samples, zones = VitalsThresholdEngine.zones(metric, profile), @@ -350,7 +352,7 @@ object VitalsCardFactory { valueText = latest?.let { "%.1f".format(tempValue(it, units)) } ?: "--", latestValue = latest?.let { tempValue(it, units) }, unitText = if (latest != null) tempUnit(units) else null, - statusText = interp?.displayLabel ?: "No data", + statusText = interp?.displayLabel ?: tr("No data"), statusToken = interp?.statusColorToken ?: VitalColorToken.Neutral, subtitleText = null, samples = dispSamples, zones = zones, @@ -380,7 +382,7 @@ object VitalsCardFactory { // No latestValue: the "sys/dia" label has no single number; BP gauges read the two // series directly. valueText = valueText, unitText = if (sys != null) "mmHg" else null, - statusText = interp?.displayLabel ?: "No reading", + statusText = interp?.displayLabel ?: tr("No reading"), statusToken = interp?.statusColorToken ?: VitalColorToken.Neutral, // Systolic/diastolic values are shown under each of the two gauges on the card, so the // subtitle would just repeat them. @@ -390,7 +392,7 @@ object VitalsCardFactory { yDomain = 80.0..190.0, referenceBands = emptyList(), dashedRules = emptyList(), trend = TrendSummary.compute(inputs.systolic, MetricKind.BLOOD_PRESSURE, unitLabel = "mmHg"), sourceQuality = quality, isEstimated = true, - confidenceLabel = if (inputs.hasBPReference) "Estimated" else "Estimated · calibrate with a cuff", + confidenceLabel = if (inputs.hasBPReference) tr("Estimated") else tr("Estimated · calibrate with a cuff"), lastUpdatedText = lastUpdated(inputs.systolic.lastOrNull()?.timestampMs, inputs.nowMs), isEmpty = sys == null || dia == null, ) @@ -426,9 +428,9 @@ object VitalsCardFactory { metric = MetricKind.GLUCOSE, title = MetricKind.GLUCOSE.title, valueText = valueText ?: "--", latestValue = latest?.let(::gv), unitText = if (latest != null) gUnit.label else null, - statusText = interp?.displayLabel ?: "No estimate", + statusText = interp?.displayLabel ?: tr("No estimate"), statusToken = interp?.statusColorToken ?: VitalColorToken.Neutral, - subtitleText = "Estimated wellness metric", + subtitleText = tr("Estimated wellness metric"), samples = dispSamples, zones = zones, yDomain = domain, referenceBands = listOf(ReferenceBand(gv(70.0), gv(140.0), VitalColorToken.Mint)), diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml new file mode 100644 index 00000000..725fae1e --- /dev/null +++ b/app/src/main/res/values-pt/strings.xml @@ -0,0 +1,13 @@ + + + + Atividade do dia + Passos, distância e calorias com seus anéis de progresso. + Bloco de métrica + Um bloco de Hoje à sua escolha: atividade, sono, frequência cardíaca e mais. + Dois blocos de métrica + Dois blocos de Hoje lado a lado, cada um configurável. + Foto da refeição + Registrar refeição + Um toque abre a câmera para registrar uma refeição com análise por IA. + diff --git a/app/src/test/java/com/pulseloop/ui/i18n/PortugueseCatalogTest.kt b/app/src/test/java/com/pulseloop/ui/i18n/PortugueseCatalogTest.kt new file mode 100644 index 00000000..9595c0d4 --- /dev/null +++ b/app/src/test/java/com/pulseloop/ui/i18n/PortugueseCatalogTest.kt @@ -0,0 +1,49 @@ +package com.pulseloop.ui.i18n + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +/** + * The pt-BR catalog (assets/i18n/pt-BR.json): every entry is a usable drop-in for its English key. + * A key is the exact English text, so these are the properties that keep a translated screen intact + * when a string is concatenated with numbers or formatted at runtime. + */ +class PortugueseCatalogTest { + + private val catalog: Map = run { + val f = listOf("src/main/assets/i18n/pt-BR.json", "app/src/main/assets/i18n/pt-BR.json").map(::File).first { it.exists() } + Json.parseToJsonElement(f.readText()).jsonObject.mapValues { it.value.jsonPrimitive.content } + } + + @Test + fun `the catalog is substantial and has no empty entries`() { + assertTrue(catalog.size > 900) + assertTrue(catalog.values.none { it.isBlank() }) + } + + @Test + fun `leading and trailing spaces survive translation`() { + catalog.forEach { (en, pt) -> + assertEquals("leading space: $en", en.startsWith(" "), pt.startsWith(" ")) + assertEquals("trailing space: $en", en.endsWith(" "), pt.endsWith(" ")) + } + } + + @Test + fun `format specifiers survive translation`() { + val spec = Regex("%[0-9$,.]*[sdf]") + catalog.forEach { (en, pt) -> + assertEquals("specifiers: $en", spec.findAll(en).map { it.value }.sorted().toList(), spec.findAll(pt).map { it.value }.sorted().toList()) + } + } + + @Test + fun `an untranslated string falls back to English`() { + assertEquals("Not in any catalog 123", tr("Not in any catalog 123")) + } +} From 86f8daac7e3653e86f4cd71b4d79553168a1f913 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 10:26:36 +0000 Subject: [PATCH 3/3] Portuguese catalog: 1,023 UI strings in pt-BR The meal-analysis prompt and its schema stay English: they go to the model, not the screen. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/assets/i18n/pt-BR.json | 1025 +++++++++++++++++ .../pulseloop/ui/screens/MealAnalysisSheet.kt | 10 +- 2 files changed, 1030 insertions(+), 5 deletions(-) create mode 100644 app/src/main/assets/i18n/pt-BR.json diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json new file mode 100644 index 00000000..9584b9f8 --- /dev/null +++ b/app/src/main/assets/i18n/pt-BR.json @@ -0,0 +1,1025 @@ +{ + "\n\nThe day's total drops by that much. This can't be undone, and the record stays deleted the next time this day syncs.": "\n\nO total do dia diminui nesse valor. Isso não pode ser desfeito, e o registro continua excluído na próxima vez que este dia sincronizar.", + " Delete": " Excluir", + " The reading stays deleted the next time this day syncs.": " A leitura continua excluída na próxima vez que este dia sincronizar.", + " · Health Connect": " · Health Connect", + " · from food log": " · do diário alimentar", + " · paused": " · pausado", + " · tap for this week's plan": " · toque para ver o plano da semana", + "\"Nearby devices\"": "\"Dispositivos próximos\"", + "24h": "24h", + "3 minutes of slow breathing. An urge usually passes within 20 minutes.": "3 minutos de respiração lenta. A vontade geralmente passa em até 20 minutos.", + "3-question check": "Verificação de 3 perguntas", + "600 ml": "600 ml", + "7d": "7d", + "8 hours before bed": "8 horas antes de dormir", + "A bridge app: it copies another app's data (for example Huawei Health) into Health Connect.": "Um app ponte: ele copia dados de outro app (por exemplo, Huawei Health) para o Health Connect.", + "A bridge app: name the watch behind it.": "Um app ponte: informe o relógio por trás dele.", + "A check is already open.": "Já há uma verificação em andamento.", + "A device wellness score from 0–100 based on heart-rate patterns. Lower is calmer. It's an estimate, not a medical stress measure.": "Uma pontuação de bem-estar de 0 a 100 baseada nos padrões de frequência cardíaca. Quanto menor, mais calmo. É uma estimativa, não uma medição médica de estresse.", + "A device wellness score from 0–100 estimating tiredness. Higher means more fatigue. It's a ring estimate, not a clinical scale.": "Uma pontuação de bem-estar de 0 a 100 que estima o cansaço. Quanto maior, mais fadiga. É uma estimativa do anel, não uma escala clínica.", + "A few more days of data and your routines show up here.": "Mais alguns dias de dados e suas rotinas aparecem aqui.", + "A nudge about 30 minutes before your suggested bedtime.": "Um lembrete cerca de 30 minutos antes do horário sugerido para dormir.", + "A record for you and your doctor. PulseLoop doesn't check interactions or doses; ask your pharmacist.": "Um registro para você e seu médico. O PulseLoop não verifica interações nem doses; consulte seu farmacêutico.", + "A ring is paired. Forget it in Settings → Wearable first: the two would count the same steps and nights.": "Há um anel pareado. Esqueça-o primeiro em Configurações → Wearable: os dois contariam os mesmos passos e noites.", + "A solid active day so far.": "Um dia ativo e consistente até agora.", + "A typical week now": "Uma semana típica agora", + "A weekly limit and dry days you choose": "Um limite semanal e dias sem álcool que você escolhe", + "ADD DETAIL (OPTIONAL)": "ADICIONAR DETALHES (OPCIONAL)", + "AI Coach": "Coach de IA", + "AI Coach is off": "Coach de IA desativado", + "AI analysis needs the coach enabled with a configured provider (Settings → AI Coach). You can still search the database or enter the meal manually.": "A análise por IA precisa do coach ativado com um provedor configurado (Configurações → Coach de IA). Você ainda pode buscar no banco de dados ou inserir a refeição manualmente.", + "AI estimate": "Estimativa da IA", + "AI health coach": "Coach de saúde com IA", + "AI meal log": "Registro de refeição com IA", + "API key (optional)": "Chave de API (opcional)", + "API key needed": "Chave de API necessária", + "About": "Sobre", + "About PulseLoop": "Sobre o PulseLoop", + "Above ~2000 m, normal blood-oxygen readings run lower. We use this to avoid false low-oxygen warnings.": "Acima de ~2000 m, as leituras normais de oxigênio no sangue ficam mais baixas. Usamos isso para evitar alertas falsos de oxigênio baixo.", + "Accuracy check": "Verificação de precisão", + "Accuracy check sources": "Fontes da verificação de precisão", + "Accuracy report": "Relatório de precisão", + "Accuracy report ready · choose what to do with the paused export": "Relatório de precisão pronto · escolha o que fazer com a exportação pausada", + "Active": "Ativo", + "Active minutes": "Minutos ativos", + "Activity": "Atividade", + "Activity and live vitals, right away": "Atividade e sinais vitais ao vivo, na hora", + "Activity is estimated by PulseLoop from your ring's steps and the workouts you log. It is not a medical measurement.": "A atividade é estimada pelo PulseLoop a partir dos passos do seu anel e dos treinos que você registra. Não é uma medição médica.", + "Activity recording": "Gravação de atividade", + "Activity type": "Tipo de atividade", + "Add": "Adicionar", + "Add a ring": "Adicionar um anel", + "Add a workout you forgot to record": "Adicione um treino que você esqueceu de gravar", + "Add by hand": "Adicionar manualmente", + "Add medication or supplement": "Adicionar medicamento ou suplemento", + "Add stravaClientId and stravaClientSecret to local.properties to enable Strava integration.": "Adicione stravaClientId e stravaClientSecret ao local.properties para ativar a integração com o Strava.", + "Add what you take on a schedule. PulseLoop asks once per dose and keeps a week's record, and the coach can see it.": "Adicione o que você toma com horário. O PulseLoop pergunta uma vez por dose e guarda o registro de uma semana, e o coach pode vê-lo.", + "Add workout": "Adicionar treino", + "Add your age in Settings → User Profile for cardio capacity.": "Adicione sua idade em Configurações → Perfil do usuário para a capacidade cardiorrespiratória.", + "Add your ring": "Adicione seu anel", + "Adjust end time": "Ajustar horário de término", + "Adjust start or end time to trim this record. Stages outside the new range will be removed.": "Ajuste o horário de início ou de término para recortar este registro. As fases fora do novo intervalo serão removidas.", + "Adjust start time": "Ajustar horário de início", + "After 1–2 drinks": "Depois de 1–2 doses", + "After 3 or more": "Depois de 3 ou mais", + "After a session": "Depois de uma sessão", + "Age": "Idade", + "Alcoólicos Anônimos": "Alcoólicos Anônimos", + "All-day heart rate": "Frequência cardíaca o dia todo", + "Allow Bluetooth access": "Permitir acesso ao Bluetooth", + "Allow access": "Permitir acesso", + "Allow background access so imports also run while PulseLoop is closed.": "Permita o acesso em segundo plano para que as importações também rodem com o PulseLoop fechado.", + "Allow background sync": "Permitir sincronização em segundo plano", + "Allow camera access in Settings to scan barcodes, or enter the food manually instead.": "Permita o acesso à câmera em Configurações para ler códigos de barras, ou insira o alimento manualmente.", + "Allow more": "Permitir mais", + "An LLM-native health app that turns a cheap Bluetooth smart ring into a real, conversational health tracker. It talks to the ring directly over Bluetooth — no vendor cloud, no account — and layers an AI coach on top of your own data.": "Um app de saúde nativo de LLM que transforma um anel inteligente Bluetooth barato em um monitor de saúde de verdade, com conversa. Ele se comunica com o anel diretamente via Bluetooth — sem nuvem do fabricante, sem conta — e adiciona um coach de IA sobre os seus próprios dados.", + "An estimated glucose value. No smart ring is cleared to measure glucose, so treat this as a wellness estimate only.": "Um valor estimado de glicose. Nenhum anel inteligente é aprovado para medir glicose, então trate isto apenas como uma estimativa de bem-estar.", + "Analyze": "Analisar", + "Android may delay background syncs by hours while your phone is idle. Your ring keeps recording either way; allowing this keeps the app up to date.": "O Android pode atrasar as sincronizações em segundo plano por horas enquanto o celular está ocioso. Seu anel continua gravando de qualquer forma; permitir isso mantém o app atualizado.", + "Anonymize export": "Anonimizar exportação", + "Anything else": "Outra coisa", + "Anywhere: your doctor. If you drink most days, don't stop all at once; a doctor can help you cut down safely.": "Em qualquer lugar: seu médico. Se você bebe na maioria dos dias, não pare de uma vez; um médico pode ajudar você a reduzir com segurança.", + "App Data": "Dados do app", + "App Info": "Informações do app", + "Applied to what PulseLoop shows, never to stored readings or Health Connect.": "Aplicado ao que o PulseLoop mostra, nunca às leituras armazenadas nem ao Health Connect.", + "Apply": "Aplicar", + "Around lunch and dinner, only when nothing is logged yet. Needs nutrition tracking on.": "Perto do almoço e do jantar, só quando ainda não há nada registrado. Requer o acompanhamento de nutrição ativado.", + "Ask the coach about it": "Pergunte ao coach", + "Ask the coach...": "Pergunte ao coach...", + "Athlete mode": "Modo atleta", + "Attach photo": "Anexar foto", + "Attach photos to coach messages": "Anexar fotos às mensagens do coach", + "Attached photo": "Foto anexada", + "Authorize in your browser — you'll return to PulseLoop automatically.": "Autorize no navegador — você voltará ao PulseLoop automaticamente.", + "Auto Upload": "Envio automático", + "Automatic backups": "Backups automáticos", + "Automatically align quiet hours with Android's Bedtime or Do Not Disturb mode.": "Alinhar automaticamente o horário de silêncio com o modo Hora de dormir ou Não perturbe do Android.", + "Average": "Média", + "Avg ": "Méd. ", + "Awaiting permission": "Aguardando permissão", + "Awake": "Acordado", + "BP & HRV": "PA e HRV", + "Back": "Voltar", + "Back up now": "Fazer backup agora", + "Backend proxy": "Proxy de backend", + "Backing up…": "Fazendo backup…", + "Balance Macros (30/40/30)": "Equilibrar macros (30/40/30)", + "Barcode": "Código de barras", + "Barcode scanning needs a working device camera. Enter the food manually instead.": "A leitura de código de barras precisa de uma câmera funcionando. Insira o alimento manualmente.", + "Baseline pending": "Linha de base pendente", + "Battery critically low": "Bateria criticamente baixa", + "Battery healthy": "Bateria saudável", + "Battery history": "Histórico da bateria", + "Battery low": "Bateria baixa", + "Bedtime": "Hora de dormir", + "Beer": "Cerveja", + "Below avg": "Abaixo da média", + "Beta-blockers": "Betabloqueadores", + "Blood Pressure": "Pressão arterial", + "Blood oxygen": "Oxigênio no sangue", + "Blood oxygen (SpO₂)": "Oxigênio no sangue (SpO₂)", + "Blood oxygen (SpO₂) is the percentage of oxygen your blood carries. 95–100% is normal; altitude and lung conditions can lower it.": "O oxigênio no sangue (SpO₂) é a porcentagem de oxigênio que seu sangue transporta. De 95 a 100% é normal; altitude e problemas pulmonares podem reduzi-lo.", + "Blood pressure": "Pressão arterial", + "Blood pressure calibration": "Calibração da pressão arterial", + "Blood pressure is systolic over diastolic (mmHg). The category is the worse of the two. A ring estimate is not a substitute for a cuff.": "A pressão arterial é a sistólica sobre a diastólica (mmHg). A categoria é a pior das duas. Uma estimativa do anel não substitui um medidor de braçadeira.", + "Blood sugar": "Glicemia", + "Blood sugar calibration": "Calibração da glicemia", + "Bluetooth access needed": "Acesso ao Bluetooth necessário", + "Bluetooth is off": "Bluetooth desativado", + "Body clock": "Relógio biológico", + "Body metrics": "Medidas corporais", + "Breathe": "Respirar", + "Breathe in": "Inspire", + "Breathe out": "Expire", + "Breathing sessions this week": "Sessões de respiração nesta semana", + "Building baseline": "Criando linha de base", + "Building momentum": "Ganhando ritmo", + "Built on your phone from your ring's data. No AI key needed.": "Gerado no seu celular a partir dos dados do anel. Não precisa de chave de IA.", + "CAPS AD": "CAPS AD", + "CVV · 188": "CVV · 188", + "Caipirinha": "Caipirinha", + "Calibrate": "Calibrar", + "Calibration": "Calibração", + "Calibration cleared": "Calibração apagada", + "Calories": "Calorias", + "Calories (kcal)": "Calorias (kcal)", + "Camera": "Câmera", + "Camera access needed": "Acesso à câmera necessário", + "Cancel": "Cancelar", + "Carbs": "Carboidratos", + "Carbs (g)": "Carboidratos (g)", + "Cardio": "Cardio", + "Cardio load today": "Carga cardio hoje", + "Casual or brisk walking": "Caminhada leve ou rápida", + "Change": "Alterar", + "Charge before bed": "Carregue antes de dormir", + "Chart": "Gráfico", + "Check finished: resume Health Connect export": "Verificação concluída: retomar exportação para o Health Connect", + "Choose": "Escolher", + "Choose a model": "Escolha um modelo", + "Choose an activity, when it started, and how long it lasted.": "Escolha uma atividade, quando ela começou e quanto tempo durou.", + "Chopp": "Chopp", + "Clear": "Limpar", + "Clear Demo Data": "Apagar dados de demonstração", + "Clear Demo Data?": "Apagar dados de demonstração?", + "Clear plan": "Limpar plano", + "Coach": "Coach", + "Coach Check-Ins": "Check-ins do coach", + "Coach Memory": "Memória do coach", + "Coach is thinking…": "O coach está pensando…", + "Cocktail": "Coquetel", + "Collapsed": "Recolhido", + "Compare my ring with this": "Comparar meu anel com isto", + "Compare with my phone": "Comparar com meu celular", + "Compare your ring with another device": "Compare seu anel com outro dispositivo", + "Compared with your own recent nights. This can follow illness, stress, alcohol or a hard day. It isn't a diagnosis; consider an easier day.": "Comparado com suas noites recentes. Isso pode acompanhar doença, estresse, álcool ou um dia puxado. Não é um diagnóstico; considere um dia mais leve.", + "Compared with your typical week": "Comparado com sua semana típica", + "Concerning": "Preocupante", + "Connect": "Conectar", + "Connect + Query": "Conectar + consultar", + "Connect Strava": "Conectar Strava", + "Connect ring": "Conectar anel", + "Connected": "Conectado", + "Connecting…": "Conectando…", + "Connection failed": "Falha na conexão", + "Connection, command and reply events, stored as they happen. Times are local.": "Eventos de conexão, comando e resposta, armazenados à medida que acontecem. Horários locais.", + "Continue": "Continuar", + "Continue without ring": "Continuar sem anel", + "Contributors": "Colaboradores", + "Copy summary": "Copiar resumo", + "Cost estimates aren't available for on-device or custom models.": "Estimativas de custo não estão disponíveis para modelos locais ou personalizados.", + "Could not export diagnostics.": "Não foi possível exportar os diagnósticos.", + "Could not open browser": "Não foi possível abrir o navegador", + "Couldn't delete this record": "Não foi possível excluir este registro", + "Couldn't get a steady reading. Keep the ring snug and your hand still, then try again.": "Não foi possível obter uma leitura estável. Mantenha o anel justo e a mão parada, e tente de novo.", + "Couldn't load your health history.": "Não foi possível carregar seu histórico de saúde.", + "Couldn't look up that barcode. Check your connection or enter the meal manually.": "Não foi possível consultar esse código de barras. Verifique sua conexão ou insira a refeição manualmente.", + "Couldn't process that photo. Try again or describe the meal.": "Não foi possível processar essa foto. Tente de novo ou descreva a refeição.", + "Couldn't reach the server.": "Não foi possível acessar o servidor.", + "Couldn't read Health Connect. Try again in a moment.": "Não foi possível ler o Health Connect. Tente de novo em instantes.", + "Couldn't read: ": "Não foi possível ler: ", + "Couldn't save these changes. Check the times and try again.": "Não foi possível salvar as alterações. Verifique os horários e tente de novo.", + "Couldn't update this record": "Não foi possível atualizar este registro", + "Court sessions": "Sessões em quadra", + "Critical": "Crítico", + "Custom model slug (vendor/model)": "Slug de modelo personalizado (fornecedor/modelo)", + "Customize": "Personalizar", + "Cycle": "Ciclo", + "Cycling": "Ciclismo", + "DATA SOURCE": "FONTE DE DADOS", + "DETECTED · REVIEW": "DETECTADO · REVISAR", + "Daily Check-in Notifications": "Notificações de check-in diário", + "Daily Goals": "Metas diárias", + "Daily and weekly targets behind the activity rings.": "Metas diárias e semanais por trás dos anéis de atividade.", + "Daily check-ins": "Check-ins diários", + "Daily goals": "Metas diárias", + "Daily guidance": "Orientação diária", + "Daily targets": "Metas diárias", + "Dance": "Dança", + "Data Backup": "Backup de dados", + "Data Types": "Tipos de dados", + "Data behind this score": "Dados por trás desta pontuação", + "Data stays on device": "Os dados ficam no dispositivo", + "Database": "Banco de dados", + "Day": "Dia", + "Days 3–7": "Dias 3–7", + "Debug": "Depuração", + "Decrease duration by 5 minutes": "Diminuir a duração em 5 minutos", + "Deep": "Profundo", + "Default": "Padrão", + "Default ports — Ollama 11434 · LM Studio 1234 · llama.cpp 8080 · vLLM 8000 · SGLang 30000. The /v1 path is added for you.": "Portas padrão — Ollama 11434 · LM Studio 1234 · llama.cpp 8080 · vLLM 8000 · SGLang 30000. O caminho /v1 é adicionado para você.", + "Delete": "Excluir", + "Delete drink?": "Excluir bebida?", + "Delete every record PulseLoop wrote to Health Connect and reset the export to start fresh. Your ring data in PulseLoop is untouched.": "Exclua todos os registros que o PulseLoop gravou no Health Connect e redefina a exportação para começar do zero. Os dados do anel no PulseLoop não são afetados.", + "Delete meal?": "Excluir refeição?", + "Delete memory?": "Excluir memória?", + "Delete old data & import": "Excluir dados antigos e importar", + "Delete this activity record": "Excluir este registro de atividade", + "Delete this activity record?": "Excluir este registro de atividade?", + "Delete this reading": "Excluir esta leitura", + "Delete this reading?": "Excluir esta leitura?", + "Delete this record": "Excluir este registro", + "Delete this record?": "Excluir este registro?", + "Delete workout": "Excluir treino", + "Delete workout?": "Excluir treino?", + "Deleting needs write permission, and PulseLoop has none right now — re-grant above, or delete the data in the Health Connect app.": "A exclusão precisa de permissão de gravação, e o PulseLoop não tem nenhuma agora — conceda de novo acima ou exclua os dados no app Health Connect.", + "Demo Data": "Dados de demonstração", + "Describe": "Descrever", + "Describe your meal": "Descreva sua refeição", + "Destructive actions: unpair the ring, factory-reset app data, or both.": "Ações destrutivas: desparear o anel, redefinir os dados do app ou ambos.", + "Details": "Detalhes", + "Detect server & configure": "Detectar servidor e configurar", + "Detecting…": "Detectando…", + "Developer": "Desenvolvedor", + "Developer options are already enabled.": "As opções de desenvolvedor já estão ativadas.", + "Device: ": "Dispositivo: ", + "Device: not recorded": "Dispositivo: não registrado", + "Diagnostics": "Diagnósticos", + "Diastolic": "Diastólica", + "Disabled": "Desativado", + "Disconnect": "Desconectar", + "Disconnect Strava?": "Desconectar o Strava?", + "Disconnected": "Desconectado", + "Disconnected from Strava": "Desconectado do Strava", + "Dismiss": "Dispensar", + "Distance": "Distância", + "Distance, calories, and heart-rate stats are recalculated for the new window.": "Distância, calorias e estatísticas de frequência cardíaca são recalculadas para o novo período.", + "Done": "Concluído", + "Dose (optional)": "Dose (opcional)", + "Drink less, sleep better": "Beba menos, durma melhor", + "Drinks": "Bebidas", + "Drinks settings": "Configurações de bebidas", + "Drinks tonight": "Bebidas hoje à noite", + "Dry": "Sem álcool", + "Dry days a week": "Dias sem álcool por semana", + "Duration": "Duração", + "Each night is compared with your own previous four weeks once there are two weeks to compare with. ": "Cada noite é comparada com suas próprias quatro semanas anteriores assim que houver duas semanas para comparar. ", + "Early evening, when you're under 70% of your step goal. Off in Rest Mode.": "No início da noite, quando você estiver abaixo de 70% da sua meta de passos. Desativado no Modo Descanso.", + "Edit": "Editar", + "Edit goals": "Editar metas", + "Edit sleep record": "Editar registro de sono", + "Edit this record's times": "Editar os horários deste registro", + "Edit workout": "Editar treino", + "Elevated": "Elevado", + "Enable": "Ativar", + "Enable AI Coach": "Ativar Coach de IA", + "Enable Coach Check-Ins?": "Ativar check-ins do Coach?", + "Enable Nutrition Tracking": "Ativar registro de nutrição", + "Enable the AI Coach to change these — daily check-ins are written by the coach from your recent trends.": "Ative o Coach de IA para alterar isso — os check-ins diários são escritos pelo coach com base nas suas tendências recentes.", + "End must be after the start.": "O fim deve ser depois do início.", + "End now": "Encerrar agora", + "End session": "Encerrar sessão", + "End the check now?": "Encerrar a verificação agora?", + "End time can't be in the future.": "O horário de término não pode estar no futuro.", + "Ended early.": "Encerrado antes do previsto.", + "Ended early: a different ring was paired.": "Encerrado antes do previsto: outro anel foi pareado.", + "Ends": "Termina", + "Enter a valid mg/dL reading": "Insira uma leitura válida em mg/dL", + "Environment": "Ambiente", + "Error": "Erro", + "Estimated": "Estimado", + "Estimated from HRV — your ring doesn't measure stress": "Estimado a partir da HRV — seu anel não mede estresse", + "Estimated from HRV — your ring doesn't measure stress. Scored against your own recent HRV readings, so it says how this reading compares with your normal, not how you compare with anyone else.": "Estimado a partir da HRV — seu anel não mede estresse. Calculado com base nas suas próprias leituras recentes de HRV, então mostra como esta leitura se compara ao seu normal, não como você se compara a outras pessoas.", + "Estimated from resting heart rate and age": "Estimado a partir da frequência cardíaca em repouso e da idade", + "Estimated wellness metric": "Métrica de bem-estar estimada", + "Estimated wellness metric — not for dosing or diabetes decisions. No smart ring or watch is FDA-authorized to measure or estimate glucose on its own.": "Métrica de bem-estar estimada — não use para dosagem ou decisões sobre diabetes. Nenhum anel inteligente ou relógio é autorizado pela FDA a medir ou estimar glicose por conta própria.", + "Estimated · calibrate with a cuff": "Estimado · calibre com um medidor de pressão", + "Estimates from your ring compared with your own recent normal, not medical measurements.": "Estimativas do seu anel comparadas com o seu próprio normal recente, não medições médicas.", + "Estimating nutrition…": "Estimando nutrição…", + "Evening": "Noite", + "Everything compared agrees within its band.": "Tudo o que foi comparado está dentro da faixa.", + "Excellent": "Excelente", + "Expanded": "Expandido", + "Explain my heart rate trend": "Explique minha tendência de frequência cardíaca", + "Explore the app without a ring. Seeds activity, HR, SpO2, sleep, and a coach conversation.": "Explore o app sem um anel. Gera dados de atividade, HR, SpO2, sono e uma conversa com o coach.", + "Explore without ring": "Explorar sem anel", + "Export All Data": "Exportar todos os dados", + "Export Diagnostics": "Exportar diagnósticos", + "Export Full (Unmasked)": "Exportar completo (sem máscara)", + "Export PulseLoop Data": "Exportar dados do PulseLoop", + "Export PulseLoop data": "Exportar dados do PulseLoop", + "Export all your data to a single JSON file for backup, device migration, or external analysis. Import restores everything — replacing all current data.": "Exporte todos os seus dados para um único arquivo JSON para backup, migração de dispositivo ou análise externa. A importação restaura tudo — substituindo todos os dados atuais.", + "Export app, device, and wearable logs as JSON for bug reports.": "Exporte logs do app, do dispositivo e do wearable em JSON para relatórios de bugs.", + "Export app, device, and wearable logs as JSON.": "Exporte logs do app, do dispositivo e do wearable em JSON.", + "Export failed": "Falha na exportação", + "Export reset — re-grant permissions to sync again.": "Exportação redefinida — conceda as permissões novamente para voltar a sincronizar.", + "Export ring data to Health Connect so other apps and dashboards can show it. Write-only: PulseLoop never reads data back.": "Exporte os dados do anel para o Health Connect para que outros apps e painéis possam exibi-los. Somente gravação: o PulseLoop nunca lê dados de volta.", + "Export them too": "Exportar também", + "Export them too if you're taking the other device off and want the ring's full history in Health Connect.": "Exporte também se você vai deixar de usar o outro dispositivo e quer o histórico completo do anel no Health Connect.", + "Exported only when switched on. A row stays dim until its permission is granted.": "Exportado somente quando ativado. Uma linha fica esmaecida até que sua permissão seja concedida.", + "Exporting all history can take a while on the first run.": "Exportar todo o histórico pode demorar um pouco na primeira vez.", + "Exporting…": "Exportando…", + "Factory Reset Ring": "Restaurar anel de fábrica", + "Factory reset erases all data stored on the ring itself and resets it to factory state. Your synced data in the app is kept.": "A restauração de fábrica apaga todos os dados armazenados no próprio anel e o retorna ao estado de fábrica. Seus dados sincronizados no app são mantidos.", + "Factory reset ring?": "Restaurar anel de fábrica?", + "Fair": "Razoável", + "Fallback schedule (used when no Bedtime/DND mode was active):": "Horário alternativo (usado quando nenhum modo Hora de dormir/Não perturbe estava ativo):", + "Fat": "Gordura", + "Fat (g)": "Gordura (g)", + "Fat Burn": "Queima de gordura", + "Fatigue": "Fadiga", + "Feeling unwell? Pause activity nudges for 3 days.": "Não está se sentindo bem? Pause os lembretes de atividade por 3 dias.", + "Female": "Feminino", + "Filter models": "Filtrar modelos", + "Filter, e.g. claude": "Filtrar, ex.: claude", + "Find ring": "Encontrar anel", + "Finish": "Concluir", + "Firmware: reading… (connect ring to read)": "Firmware: lendo… (conecte o anel para ler)", + "First sync": "Primeira sincronização", + "Fitness": "Condicionamento", + "Flow, stretch, or breathwork": "Flow, alongamento ou respiração", + "For drinks, money and calories saved": "Para bebidas, dinheiro e calorias economizados", + "Forget": "Esquecer", + "Forget Ring": "Esquecer anel", + "Forget ring?": "Esquecer anel?", + "Forget unbinds the ring and removes it from the app so it can be paired elsewhere. The app stays connected automatically the rest of the time.": "Esquecer desvincula o anel e o remove do app para que possa ser pareado em outro lugar. No restante do tempo, o app permanece conectado automaticamente.", + "Formula version": "Versão da fórmula", + "Free emotional support, any time, by phone or chat.": "Apoio emocional gratuito, a qualquer hora, por telefone ou chat.", + "Free public care for alcohol use. Ask at your local health unit.": "Atendimento público e gratuito para uso de álcool. Pergunte na sua unidade de saúde.", + "From the next-meal suggestion": "Da sugestão de próxima refeição", + "Gemini": "Gemini", + "Gemini API Key": "Chave de API do Gemini", + "General": "Geral", + "Get a daily check-in from your coach. You can change this anytime in Coach Check-Ins.": "Receba um check-in diário do seu coach. Você pode alterar isso a qualquer momento em Check-ins do Coach.", + "Get notified when your ring drops below 20% and 10%, so tracking doesn't stop mid-day.": "Seja avisado quando a bateria do anel ficar abaixo de 20% e 10%, para o monitoramento não parar no meio do dia.", + "Get started": "Começar", + "Glucose": "Glicose", + "Glucose unit": "Unidade de glicose", + "Goal progress: ": "Progresso da meta: ", + "Goals": "Metas", + "Goals, scores and Health Connect keep the ring's own count.": "Metas, pontuações e Health Connect mantêm a contagem do próprio anel.", + "Good": "Bom", + "Good afternoon": "Boa tarde", + "Good evening": "Boa noite", + "Good morning": "Bom dia", + "Good night": "Boa noite", + "Great balance of movement and recovery. Keep it up.": "Ótimo equilíbrio entre movimento e recuperação. Continue assim.", + "Grounds suggestions in your city's current weather": "Baseia as sugestões no clima atual da sua cidade", + "Gym": "Academia", + "HR collected": "HR coletada", + "HR pending": "HR pendente", + "HR, SpO₂, HRV & stress": "HR, SpO₂, HRV e estresse", + "HRV is exported as RMSSD — Health Connect has no SDNN type, and the rings' metric is vendor-undocumented.": "A HRV é exportada como RMSSD — o Health Connect não tem um tipo SDNN, e a métrica dos anéis não é documentada pelo fabricante.", + "HRV readings": "Leituras de HRV", + "Habits & routines · 30-day averages": "Hábitos e rotinas · médias de 30 dias", + "Health Connect": "Health Connect", + "Health Connect isn't available on this device. Install the Health Connect app to use this feature.": "O Health Connect não está disponível neste dispositivo. Instale o app Health Connect para usar este recurso.", + "Health Connect isn't available on this phone.": "O Health Connect não está disponível neste celular.", + "Health Connect permissions revoked": "Permissões do Health Connect revogadas", + "Health areas · last 60–90 days": "Áreas de saúde · últimos 60–90 dias", + "Health context": "Contexto de saúde", + "Heart": "Coração", + "Heart Rate": "Frequência cardíaca", + "Heart rate": "Frequência cardíaca", + "Heart rate since last night": "Frequência cardíaca desde ontem à noite", + "Heart-rate readings": "Leituras de frequência cardíaca", + "Heart-rate variability is the variation between beats. It's highly individual, so we track it against your personal baseline rather than a universal cutoff.": "A variabilidade da frequência cardíaca é a variação entre os batimentos. Ela é muito individual, então a acompanhamos em relação à sua linha de base pessoal, e não a um limite universal.", + "Height": "Altura", + "Hi! I'm your PulseLoop coach. I can answer questions about your sleep, heart rate, activity, and recovery. What would you like to know?": "Olá! Sou seu coach do PulseLoop. Posso responder perguntas sobre seu sono, frequência cardíaca, atividade e recuperação. O que você gostaria de saber?", + "Hide": "Ocultar", + "Hide activity records": "Ocultar registros de atividade", + "Hide connection details": "Ocultar detalhes da conexão", + "Hide key": "Ocultar chave", + "Hide packets": "Ocultar pacotes", + "Hide readings": "Ocultar leituras", + "High": "Alto", + "Hiking": "Trilha", + "How am I doing on my goal? What should I focus on this week?": "Como estou indo na minha meta? No que devo focar esta semana?", + "How am I doing today?": "Como estou hoje?", + "How can I sleep better?": "Como posso dormir melhor?", + "How long": "Quanto tempo", + "How many": "Quantas", + "How much history should we export?": "Quanto do histórico devemos exportar?", + "How often the ring measures in the background. Shorter heart-rate intervals give finer history at the cost of battery.": "Com que frequência o anel mede em segundo plano. Intervalos menores de frequência cardíaca dão um histórico mais detalhado, mas gastam mais bateria.", + "I wear an Oura or another device": "Uso um Oura ou outro dispositivo", + "I'd like to set a goal. Ask me what I want and help me make it realistic for my data.": "Quero definir uma meta. Pergunte o que eu quero e me ajude a torná-la realista para os meus dados.", + "Identity": "Identidade", + "Idle between syncs": "Ocioso entre sincronizações", + "If your watch syncs through an app like Health Sync, check that it's set to write to Health Connect.": "Se o seu relógio sincroniza por um app como o Health Sync, verifique se ele está configurado para gravar no Health Connect.", + "Image attachments": "Anexos de imagem", + "Imperial": "Imperial", + "Import Complete": "Importação concluída", + "Import Data": "Importar dados", + "Import failed — the file may be corrupt or from a newer version.": "Falha na importação — o arquivo pode estar corrompido ou ser de uma versão mais recente.", + "Import now": "Importar agora", + "Importing from Health Connect. Your steps, sleep and heart rate appear once your device's app has synced.": "Importando do Health Connect. Seus passos, sono e frequência cardíaca aparecem assim que o app do seu dispositivo sincronizar.", + "Importing…": "Importando…", + "In drinks, roughly": "Em doses, aproximadamente", + "In the Oura app: Settings → Health Connect, and turn on sharing. Then come back and look again.": "No app Oura: Configurações → Health Connect, e ative o compartilhamento. Depois volte e verifique novamente.", + "Increase duration by 5 minutes": "Aumentar a duração em 5 minutos", + "Input tokens": "Tokens de entrada", + "Install Health Connect": "Instalar Health Connect", + "It changes what PulseLoop shows and what it works out from it (zones, resting baseline, calorie estimate). Your ring's stored readings and what goes to Health Connect stay as measured.": "Isso muda o que o PulseLoop mostra e o que ele calcula a partir disso (zonas, linha de base em repouso, estimativa de calorias). As leituras armazenadas no anel e o que vai para o Health Connect permanecem como medidos.", + "Journal": "Diário", + "Keep": "Manter", + "Keep going": "Continue", + "Keep recording": "Continuar gravando", + "Keep still — measuring blood oxygen…": "Fique parado — medindo o oxigênio no sangue…", + "Keep still — measuring blood pressure, SpO₂, stress, fatigue & blood sugar…": "Fique parado — medindo pressão arterial, SpO₂, estresse, fadiga e glicose…", + "Keep still — measuring heart rate & SpO₂…": "Fique parado — medindo frequência cardíaca e SpO₂…", + "Keep still — measuring heart rate…": "Fique parado — medindo frequência cardíaca…", + "Known lung condition": "Doença pulmonar conhecida", + "LAST 3 DAYS": "ÚLTIMOS 3 DIAS", + "LAST CAFFEINE": "ÚLTIMA CAFEÍNA", + "LAST NIGHT": "ONTEM À NOITE", + "Language": "Idioma", + "Last 8 weeks": "Últimas 8 semanas", + "Last Sleep": "Último sono", + "Last night": "Ontem à noite", + "Latest": "Mais recente", + "Learned from nights you woke recovered": "Aprendido com noites em que você acordou recuperado", + "Learning": "Aprendendo", + "Learns your baseline": "Aprende sua linha de base", + "Leave max tokens blank to let the server decide. Raise the timeout for a large model on CPU — a slow reply is not retried.": "Deixe o máximo de tokens em branco para o servidor decidir. Aumente o tempo limite para um modelo grande em CPU — uma resposta lenta não é repetida.", + "Less": "Menos", + "Let my goal manage these": "Deixar minha meta gerenciar isso", + "Lets the coach read your data. Detect sets this for you; turn it off if your server rejects tools (vLLM needs --enable-auto-tool-choice).": "Permite que o coach leia seus dados. Detectar define isso para você; desative se o seu servidor rejeitar ferramentas (o vLLM precisa de --enable-auto-tool-choice).", + "Library": "Biblioteca", + "License": "Licença", + "Light": "Leve", + "Live Measurements": "Medições ao vivo", + "Live measurements and trends": "Medições ao vivo e tendências", + "Live workout tracking": "Acompanhamento de treino ao vivo", + "Loading…": "Carregando…", + "Local": "Local", + "Location": "Localização", + "Log Activity": "Registrar atividade", + "Log Meal": "Registrar refeição", + "Log Past Activity": "Registrar atividade anterior", + "Log a drink": "Registrar uma bebida", + "Log a drink in one tap": "Registre uma bebida com um toque", + "Log a few evenings with drinks and PulseLoop will compare those nights with your dry ones.": "Registre algumas noites com bebidas e o PulseLoop vai comparar essas noites com as noites sem álcool.", + "Log a meal": "Registrar uma refeição", + "Log a past period": "Registrar uma menstruação anterior", + "Log drinks": "Registrar bebidas", + "Log meal": "Registrar refeição", + "Log meals and track calories & macros": "Registre refeições e acompanhe calorias e macros", + "Log meals to see food next to the calories you burn, and to link late meals and drinks to your sleep.": "Registre refeições para ver a alimentação ao lado das calorias que você queima e relacionar refeições e bebidas tardias ao seu sono.", + "Log this": "Registrar isto", + "Log your period to see its phase beside your sleep and recovery": "Registre sua menstruação para ver a fase do ciclo ao lado do seu sono e recuperação", + "Log your period to start": "Registre sua menstruação para começar", + "Look again": "Verificar novamente", + "Looking for apps writing to Health Connect…": "Procurando apps que gravam no Health Connect…", + "Low": "Baixo", + "Low Battery Notifications": "Notificações de bateria fraca", + "Lower is calmer": "Quanto menor, mais calmo", + "Male": "Masculino", + "Manage in Android settings": "Gerenciar nas configurações do Android", + "Manage or re-grant permissions, and review or delete PulseLoop's data, in the Health Connect app.": "Gerencie ou conceda novamente as permissões e revise ou exclua os dados do PulseLoop no app Health Connect.", + "Mask sensitive data": "Mascarar dados sensíveis", + "Max": "Máx.", + "Max tokens": "Máximo de tokens", + "Meal": "Refeição", + "Meal details": "Detalhes da refeição", + "Meal name": "Nome da refeição", + "Meal reminder": "Lembrete de refeição", + "Measure": "Medir", + "Measured by your ring": "Medido pelo seu anel", + "Measurement": "Medição", + "Measurement Frequency": "Frequência de medição", + "Measurement units": "Unidades de medida", + "Measuring… updates when complete": "Medindo… atualiza ao concluir", + "Medication": "Medicamento", + "Medication reminders": "Lembretes de medicamentos", + "Medications & supplements": "Medicamentos e suplementos", + "Meetings across the country: aa.org.br": "Reuniões em todo o país: aa.org.br", + "Message the coach": "Enviar mensagem ao coach", + "Metric": "Métrico", + "Metrics": "Métricas", + "Min": "Mín.", + "MiniMax": "MiniMax", + "MiniMax API Key": "Chave de API do MiniMax", + "Model": "Modelo", + "Model name": "Nome do modelo", + "Models": "Modelos", + "Moderate": "Moderado", + "Month": "Mês", + "Monthly average": "Média mensal", + "More": "Mais", + "Morning": "Manhã", + "Move reminder": "Lembrete para se mexer", + "My Health": "Minha saúde", + "My Health & Trends": "Minha saúde e tendências", + "Name": "Nome", + "Needs 5 nights in the last 2 weeks": "Precisa de 5 noites nas últimas 2 semanas", + "Needs work": "Precisa melhorar", + "New chat": "Nova conversa", + "Next": "Próximo", + "Next day": "Próximo dia", + "Next: end date": "Próximo: data de término", + "Night covered by the ring": "Noite registrada pelo anel", + "Nightly sleep": "Sono por noite", + "Nightly sleep: no nights tracked in this range": "Sono por noite: nenhuma noite registrada neste período", + "Nights in your baseline": "Noites na sua linha de base", + "No HR samples yet — sync your ring to start your trend.": "Ainda não há amostras de HR — sincronize seu anel para começar sua tendência.", + "No HRV data yet — HRV builds up over a few hours of wear.": "Ainda não há dados de HRV — a HRV se forma após algumas horas de uso.", + "No Health Connect permissions granted — nothing to export.": "Nenhuma permissão do Health Connect concedida — nada para exportar.", + "No PulseLoop ring? If your Oura, Galaxy Ring, Fitbit or watch app writes to Health Connect, PulseLoop can read it from there: sleep, heart rate, HRV, blood oxygen, steps, calories, workouts and periods. Every screen, the coach and your insights then work from that data.": "Não tem um anel PulseLoop? Se o app do seu Oura, Galaxy Ring, Fitbit ou relógio grava no Health Connect, o PulseLoop pode ler esses dados de lá: sono, frequência cardíaca, HRV, oxigênio no sangue, passos, calorias, treinos e menstruação. Todas as telas, o coach e seus insights passam a usar esses dados.", + "No SpO₂ samples yet — take a reading to start your trend.": "Ainda não há amostras de SpO₂ — faça uma medição para começar sua tendência.", + "No access granted. You can allow it in Health Connect's settings.": "Acesso não concedido. Você pode permitir nas configurações do Health Connect.", + "No accuracy check for this ring yet. Corrections from another ring don't carry over.": "Ainda não há verificação de precisão para este anel. Correções de outro anel não são aproveitadas.", + "No blood pressure data yet.": "Ainda não há dados de pressão arterial.", + "No blood sugar data yet.": "Ainda não há dados de glicemia.", + "No body measurements found in Health Connect yet.": "Nenhuma medida corporal encontrada no Health Connect ainda.", + "No clear difference": "Sem diferença clara", + "No data": "Sem dados", + "No daytime stress readings today yet.": "Ainda não há leituras de estresse diurno hoje.", + "No estimate": "Sem estimativa", + "No events yet. Sync the ring or trigger a measurement to see data.": "Nenhum evento ainda. Sincronize o anel ou inicie uma medição para ver os dados.", + "No export has run yet. With the master switch on and a backfill choice made, PulseLoop exports automatically.": "Nenhuma exportação foi feita ainda. Com a chave principal ativada e uma opção de histórico escolhida, o PulseLoop exporta automaticamente.", + "No fatigue data yet — take a measurement.": "Ainda não há dados de fadiga — faça uma medição.", + "No nights tracked in this range yet.": "Nenhuma noite registrada neste período ainda.", + "No reading": "Sem leitura", + "No ring connected": "Nenhum anel conectado", + "No ring paired": "Nenhum anel pareado", + "No rings found yet": "Nenhum anel encontrado ainda", + "No rows to display.": "Nenhuma linha para exibir.", + "No score": "Sem pontuação", + "No sleep recorded": "Nenhum sono registrado", + "No sleep stages, only time asleep": "Sem fases do sono, só o tempo dormindo", + "No sleep yet": "Ainda sem sono", + "No stress data yet — take a measurement.": "Ainda não há dados de estresse — faça uma medição.", + "No subscription": "Sem assinatura", + "No temperature data yet — temperature trends appear after overnight wear.": "Ainda não há dados de temperatura — as tendências de temperatura aparecem após usar o anel durante a noite.", + "No workouts recorded today": "Nenhum treino registrado hoje", + "No workouts yet — recorded workouts will appear here.": "Nenhum treino ainda — os treinos registrados aparecerão aqui.", + "None. A finished check offers one wherever the ring is consistently off.": "Nenhuma. Uma verificação concluída oferece uma sempre que o anel estiver consistentemente desviado.", + "Normal": "Normal", + "Not a diagnosis. Rest, fluids and an easier day help; see a doctor if you feel unwell.": "Não é um diagnóstico. Descanso, hidratação e um dia mais leve ajudam; procure um médico se não estiver se sentindo bem.", + "Not allowed to read: ": "Sem permissão para ler: ", + "Not connected": "Não conectado", + "Not enough data for this period.": "Dados insuficientes para este período.", + "Not enough data yet — battery history builds up as the ring reports its level.": "Dados insuficientes por enquanto — o histórico de bateria se forma à medida que o anel informa o nível.", + "Not enough data yet: ": "Dados insuficientes por enquanto: ", + "Not enough nights yet": "Noites insuficientes por enquanto", + "Not enough of a trend to estimate runtime yet — it appears after a few hours of discharge.": "Ainda não há tendência suficiente para estimar a autonomia — ela aparece após algumas horas de descarga.", + "Not imported yet": "Ainda não importado", + "Not measured": "Não medido", + "Not now": "Agora não", + "Not set": "Não definido", + "Not this": "Não é isso", + "Not yet": "Ainda não", + "Nothing logged yet": "Nada registrado ainda", + "Nothing new to upload": "Nada novo para enviar", + "Nothing stood out": "Nada se destacou", + "Nothing to compare yet. Check back after the first full day and night.": "Nada para comparar ainda. Volte depois do primeiro dia e noite completos.", + "Notifications are disabled for PulseLoop in Android Settings.": "As notificações estão desativadas para o PulseLoop nas Configurações do Android.", + "Notifications are off for PulseLoop. Turn them on in Android Settings to get check-ins.": "As notificações estão desativadas para o PulseLoop. Ative-as nas Configurações do Android para receber check-ins.", + "Nutrition": "Nutrição", + "OFF — includes full unmasked BLE frames (for protocol debugging only).": "DESATIVADO — inclui frames BLE completos sem mascaramento (apenas para depuração de protocolo).", + "OFF — includes full unmasked BLE frames and health values (for protocol debugging only).": "DESATIVADO — inclui frames BLE completos sem mascaramento e valores de saúde (apenas para depuração de protocolo).", + "OR DESCRIBE IT": "OU DESCREVA", + "Off": "Desativado", + "Offline": "Offline", + "On": "Ativado", + "On. PulseLoop syncs your ring about every 30 minutes, even while the phone is idle.": "Ativado. O PulseLoop sincroniza seu anel a cada 30 minutos, mesmo com o celular ocioso.", + "Once per dose, at its time, for what you add in My Health → Medications & supplements.": "Uma vez por dose, no horário dela, para o que você adicionar em Minha saúde → Medicamentos e suplementos.", + "Only needed if you started the server with --api-key. Leave blank otherwise.": "Só é necessário se você iniciou o servidor com --api-key. Caso contrário, deixe em branco.", + "Only new data from now on": "Apenas dados novos daqui em diante", + "Only providers that don't retain data": "Apenas provedores que não retêm dados", + "Open": "Abrir", + "Open Drinks: this week, your plan and what drinking does to your nights": "Abrir Bebidas: esta semana, seu plano e o que beber faz com suas noites", + "Open Health Connect": "Abrir Health Connect", + "Open Nutrition Log": "Abrir registro de nutrição", + "Open Settings": "Abrir Configurações", + "Open ring settings": "Abrir configurações do anel", + "Open settings": "Abrir configurações", + "Open today's activity": "Abrir atividade de hoje", + "Open-source health tracker. Ported from iOS.\nCC BY 4.0 · Free to share and adapt, including commercially, with appropriate credit.": "Rastreador de saúde de código aberto. Portado do iOS.\nCC BY 4.0 · Livre para compartilhar e adaptar, inclusive comercialmente, com o devido crédito.", + "OpenAI": "OpenAI", + "OpenAI API Key": "Chave de API da OpenAI", + "OpenRouter": "OpenRouter", + "OpenRouter API Key": "Chave de API do OpenRouter", + "Optional": "Opcional", + "Optional refinements to how your vitals are interpreted. Leave anything unset and PulseLoop uses sensible defaults.": "Configurações opcionais na forma como seus sinais vitais são interpretados. Deixe qualquer item em branco e o PulseLoop usa padrões adequados.", + "Optional. Both can change what's expected for your heart rate or oxygen, so we adjust labels instead of alarming.": "Opcional. Ambos podem mudar o esperado para sua frequência cardíaca ou oxigenação, então ajustamos os rótulos em vez de alarmar.", + "Optional. Enter a recent cuff reading so the ring offsets its values to match.": "Opcional. Informe uma medição recente de um medidor de braço para o anel ajustar os valores dele.", + "Optional. The ring estimates glucose from your profile, not a real sensor. Enter a recent lab/meter reading (mg/dL) to offset the displayed value to match.": "Opcional. O anel estima a glicose a partir do seu perfil, não de um sensor real. Informe uma medição recente de laboratório/glicosímetro (mg/dL) para ajustar o valor exibido.", + "Other": "Outro", + "Other ideas": "Outras ideias", + "Outdoor or treadmill runs": "Corridas ao ar livre ou na esteira", + "Output tokens": "Tokens de saída", + "Own your ring data": "Seus dados do anel são seus", + "Pace": "Ritmo", + "Pair a ring to configure its all-day measurements.": "Pareie um anel para configurar as medições contínuas.", + "Pair your ring first.": "Pareie seu anel primeiro.", + "Pair your ring first: a check compares it against the other device.": "Pareie seu anel primeiro: a verificação o compara com o outro dispositivo.", + "Past checks": "Verificações anteriores", + "Pause": "Pausar", + "Paused by the accuracy check": "Pausado pela verificação de precisão", + "Paused by the accuracy check: ": "Pausado pela verificação de precisão: ", + "Peak": "Pico", + "Per-message breakdown": "Detalhamento por mensagem", + "Period ended today": "Menstruação terminou hoje", + "Period started today": "Menstruação começou hoje", + "Permission needed": "Permissão necessária", + "Permission required": "Permissão obrigatória", + "Phases come only from the dates you log. PulseLoop doesn't predict fertile days, and this isn't contraception or a medical tool.": "As fases vêm só das datas que você registra. O PulseLoop não prevê dias férteis, e isto não é um método contraceptivo nem uma ferramenta médica.", + "Photo": "Foto", + "Physiology": "Fisiologia", + "Pick the number before the first drink. It's easier to keep a number you chose beforehand.": "Escolha o número antes da primeira dose. É mais fácil cumprir um número que você definiu antes.", + "Plan the next few days with the coach.": "Planeje os próximos dias com o coach.", + "Plan tonight": "Planejar esta noite", + "Plan: dry night": "Plano: noite sem álcool", + "Port from iOS · Open Source": "Portado do iOS · Código aberto", + "Possible nap": "Possível cochilo", + "Previous": "Anterior", + "Previous day": "Dia anterior", + "Price each (optional)": "Preço unitário (opcional)", + "Privacy & Data": "Privacidade e dados", + "Privacy first": "Privacidade em primeiro lugar", + "Privacy routing": "Roteamento de privacidade", + "Private to this phone. If you drink most days, cut down gradually and talk to a doctor: stopping suddenly can be dangerous.": "Só fica neste celular. Se você bebe quase todos os dias, reduza aos poucos e converse com um médico: parar de repente pode ser perigoso.", + "Product not found for that barcode. Enter it manually instead.": "Produto não encontrado para esse código de barras. Digite-o manualmente.", + "Profile": "Perfil", + "Protein": "Proteína", + "Protein (g)": "Proteína (g)", + "Provider": "Provedor", + "PulseLoop": "PulseLoop", + "PulseLoop Coach": "PulseLoop Coach", + "PulseLoop checks for new data every hour and whenever you open the app. A night usually appears once ": "O PulseLoop verifica novos dados a cada hora e sempre que você abre o app. Uma noite costuma aparecer quando ", + "PulseLoop isn't allowed to read Health Connect any more.": "O PulseLoop não tem mais permissão para ler o Health Connect.", + "PulseLoop learns your baseline over time": "O PulseLoop aprende sua linha de base com o tempo", + "PulseLoop needs Bluetooth permission to find and connect to your ring. Allow it in Settings, or continue without a ring and pair one later.": "O PulseLoop precisa da permissão de Bluetooth para encontrar e conectar seu anel. Permita nas Configurações ou continue sem anel e pareie um depois.", + "PulseLoop no longer has any Health Connect permissions. Reset the export so a later re-grant re-exports your history?": "O PulseLoop não tem mais nenhuma permissão do Health Connect. Redefinir a exportação para que, se você conceder de novo, seu histórico seja exportado novamente?", + "PulseLoop reads only the app you choose, and doesn't write that data back to Health Connect.": "O PulseLoop lê apenas o app que você escolher e não grava esses dados de volta no Health Connect.", + "PulseLoop shows the day of your cycle and its phase from the dates you log, next to your sleep and recovery.": "O PulseLoop mostra o dia do seu ciclo e a fase dele a partir das datas que você registra, junto ao seu sono e recuperação.", + "PulseLoop uses Bluetooth to find and connect your ring. Allow ": "O PulseLoop usa Bluetooth para encontrar e conectar seu anel. Permita ", + "PulseLoop uses Bluetooth to find and connect your ring. Nothing is shared off your phone.": "O PulseLoop usa Bluetooth para encontrar e conectar seu anel. Nada sai do seu celular.", + "PulseLoop will stop uploading workouts. Workouts already on Strava stay there.": "O PulseLoop vai parar de enviar treinos. Os treinos que já estão no Strava continuam lá.", + "Quick Access": "Acesso rápido", + "Quiet from": "Silêncio a partir de", + "Quiet hours schedule:": "Horário de silêncio:", + "Quiet until": "Silêncio até", + "REFERENCE ZONES": "ZONAS DE REFERÊNCIA", + "Raw Packets": "Pacotes brutos", + "Re-analyze": "Reanalisar", + "Readiness": "Prontidão", + "Reading (mg/dL)": "Medição (mg/dL)", + "Reading your drinks…": "Lendo suas bebidas…", + "Reading your history…": "Lendo seu histórico…", + "Reasoning effort": "Nível de raciocínio", + "Recommended": "Recomendado", + "Recompute": "Recalcular", + "Reconnect last ring": "Reconectar último anel", + "Record activity": "Registrar atividade", + "Recording a workout needs the Physical activity permission. You can allow it in Android Settings › Apps › PulseLoop › Permissions.": "Registrar um treino exige a permissão de Atividade física. Você pode permiti-la em Configurações do Android › Apps › PulseLoop › Permissões.", + "Records": "Registros", + "Reference device": "Dispositivo de referência", + "Refresh": "Atualizar", + "Relaxed": "Relaxado", + "Reliable background sync": "Sincronização em segundo plano confiável", + "Remove": "Remover", + "Remove PulseLoop data": "Remover dados do PulseLoop", + "Remove PulseLoop data?": "Remover dados do PulseLoop?", + "Remove exported data": "Remover dados exportados", + "Remove photo": "Remover foto", + "Removes all demo measurements, activity, sleep, and the demo device. Synced ring data is not affected.": "Remove todas as medições, atividades, sono e o dispositivo de demonstração. Os dados sincronizados do anel não são afetados.", + "Removes health values, ring serial & MAC addresses. Keeps models, opcodes & errors.": "Remove valores de saúde, número de série e endereços MAC do anel. Mantém modelos, opcodes e erros.", + "Removing…": "Removendo…", + "Reorder or hide cards": "Reordenar ou ocultar cartões", + "Replace all data?": "Substituir todos os dados?", + "Report": "Relatório", + "Report ready": "Relatório pronto", + "Reseed": "Recriar", + "Reseed Demo Data": "Recriar dados de demonstração", + "Reseed Demo Data?": "Recriar dados de demonstração?", + "Reset": "Redefinir", + "Reset App Data": "Redefinir dados do app", + "Reset app data": "Redefinir dados do app", + "Reset app data?": "Redefinir dados do app?", + "Reset export": "Redefinir exportação", + "Reset ring": "Redefinir anel", + "Reset units to auto-detect": "Redefinir unidades para detecção automática", + "Reset zoom": "Redefinir zoom", + "Resetting…": "Redefinindo…", + "Resilience": "Resiliência", + "Resources": "Recursos", + "Response format": "Formato da resposta", + "Rest": "Descanso", + "Rest Mode": "Modo descanso", + "Resting heart rate": "Frequência cardíaca em repouso", + "Resting heart rate reflects how hard your heart works at rest. A typical adult range is 60–100 bpm; fitness, medication, caffeine, and stress all shift it.": "A frequência cardíaca em repouso mostra o quanto seu coração trabalha em repouso. A faixa típica de um adulto é de 60–100 bpm; condicionamento, medicamentos, cafeína e estresse a alteram.", + "Resume": "Retomar", + "Retake (every 3 months)": "Refazer (a cada 3 meses)", + "Retry": "Tentar novamente", + "Review & adjust": "Revisar e ajustar", + "Ride it out": "Aguentar firme", + "Ring Events": "Eventos do anel", + "Ring battery alerts": "Alertas de bateria do anel", + "Ring blood pressure is an estimate. Calibrate against a validated cuff in Settings → Calibration, and talk to a clinician about persistent high or low readings.": "A pressão arterial do anel é uma estimativa. Calibre com um medidor de braço validado em Configurações → Calibração e converse com um profissional de saúde sobre leituras persistentemente altas ou baixas.", + "Ring management": "Gerenciamento do anel", + "Ring model estimate": "Estimativa do modelo do anel", + "Ring steps vs your phone": "Passos do anel vs. do seu celular", + "Road, trail, or stationary": "Rua, trilha ou estacionária", + "Route by": "Rotear por", + "Row counts include demo and real rows. Tap a table to see its newest rows. Stored health rows are never included in a diagnostics export.": "A contagem de linhas inclui linhas de demonstração e reais. Toque em uma tabela para ver as linhas mais recentes. Linhas de saúde armazenadas nunca são incluídas em uma exportação de diagnóstico.", + "Running": "Corrida", + "Same as heart rate": "Igual à frequência cardíaca", + "Save": "Salvar", + "Save Key": "Salvar chave", + "Save calibration": "Salvar calibração", + "Save changes": "Salvar alterações", + "Save goals": "Salvar metas", + "Save measurement settings": "Salvar configurações de medição", + "Save plan": "Salvar plano", + "Save profile": "Salvar perfil", + "Saved": "Salvo", + "Saved & sent to ring ✓": "Salvo e enviado ao anel ✓", + "Saved — will sync on next connect": "Salvo — será sincronizado na próxima conexão", + "Saved ✓": "Salvo ✓", + "Saves the same file as Export to a folder you choose, and keeps the latest 5.": "Salva o mesmo arquivo de Exportar em uma pasta que você escolher e mantém os 5 mais recentes.", + "Scan a packaged food": "Escanear um alimento embalado", + "Scan barcode": "Escanear código de barras", + "Scanning unavailable": "Leitura indisponível", + "Searching…": "Procurando…", + "See Raw Packets above.": "Veja Pacotes brutos acima.", + "See Ring Events above.": "Veja Eventos do anel acima.", + "See and edit recent drinks": "Ver e editar bebidas recentes", + "See result": "Ver resultado", + "See what affects you": "Veja o que afeta você", + "See what drinking does to your own nights": "Veja o que beber faz com suas próprias noites", + "See your vitals": "Ver seus sinais vitais", + "Send": "Enviar", + "Send Test Check-in Now": "Enviar check-in de teste agora", + "Sending three tiny test messages. This can take a minute if the model still has to load.": "Enviando três pequenas mensagens de teste. Isso pode levar um minuto se o modelo ainda precisar carregar.", + "Sent to your configured AI provider only when you tap Analyze. Estimates are labeled and editable.": "Enviado ao seu provedor de IA configurado apenas quando você toca em Analisar. As estimativas são identificadas e editáveis.", + "Server address": "Endereço do servidor", + "Server address needed": "Endereço do servidor necessário", + "Session saved": "Sessão salva", + "Set by your goal: ": "Definido pela sua meta: ", + "Set goals, log, edit data": "Defina metas, registre e edite dados", + "Set up PulseLoop": "Configurar o PulseLoop", + "Set up a ring": "Configurar um anel", + "Set up · under a minute": "Configuração · menos de um minuto", + "Set your typical week in settings to see drinks, money and calories saved.": "Defina sua semana típica nas configurações para ver as bebidas, o dinheiro e as calorias economizados.", + "Settings": "Configurações", + "Setup complete": "Configuração concluída", + "Sex": "Sexo", + "Shaded: your usual range over the last 30 days": "Área sombreada: sua faixa habitual nos últimos 30 dias", + "Share": "Compartilhar", + "Share accuracy report": "Compartilhar relatório de precisão", + "Share my week": "Compartilhar minha semana", + "Shot": "Dose", + "Show": "Mostrar", + "Show activity records": "Mostrar registros de atividade", + "Show connection details": "Mostrar detalhes da conexão", + "Show fewer events": "Mostrar menos eventos", + "Show key": "Mostrar chave", + "Show more events": "Mostrar mais eventos", + "Show phone-calibrated steps on Today": "Mostrar passos calibrados pelo celular em Hoje", + "Show readings": "Mostrar leituras", + "Show recent packets": "Mostrar pacotes recentes", + "Skin temperature": "Temperatura da pele", + "Skin temperature from the ring runs cooler than core body temperature. Trends over time matter more than any single reading.": "A temperatura da pele medida pelo anel é mais baixa que a temperatura corporal central. As tendências ao longo do tempo importam mais do que uma leitura isolada.", + "Skip": "Pular", + "Skip for now": "Pular por enquanto", + "Skip these days (recommended)": "Pular estes dias (recomendado)", + "Sleep": "Sono", + "Sleep architecture": "Arquitetura do sono", + "Sleep contributors": "Fatores do sono", + "Sleep debt": "Débito de sono", + "Sleep insights": "Insights de sono", + "Sleep need": "Necessidade de sono", + "Sleep pending": "Sono pendente", + "Sleep quiet hours": "Horário de silêncio do sono", + "Sleep stages and nightly trends": "Estágios do sono e tendências noturnas", + "Sleep synced": "Sono sincronizado", + "Sleep tracking": "Monitoramento do sono", + "Slow breathing: in for 4 seconds, out for 6.": "Respiração lenta: inspire por 4 segundos, expire por 6.", + "Snap your plate; the AI estimates it": "Fotografe seu prato; a IA faz a estimativa", + "So far (preliminary)": "Até agora (preliminar)", + "Some signals look unusual": "Alguns sinais parecem fora do comum", + "Source on GitHub": "Código-fonte no GitHub", + "SpO₂": "SpO₂", + "Speed": "Velocidade", + "Sport": "Esporte", + "Squash": "Squash", + "Stage 1": "Estágio 1", + "Staged photo": "Foto encenada", + "Stages": "Estágios", + "Stages and trends": "Estágios e tendências", + "Standard drink": "Dose padrão", + "Start": "Iniciar", + "Start a breathing session": "Iniciar uma sessão de respiração", + "Start an accuracy check": "Iniciar uma verificação de precisão", + "Start one manually when your ring misses an activity.": "Inicie um manualmente quando o anel não registrar uma atividade.", + "Start time must be before end time.": "O horário de início deve ser anterior ao de término.", + "Start tracking": "Começar a monitorar", + "Start using PulseLoop": "Começar a usar o PulseLoop", + "Start with recommended targets. You can change these anytime.": "Comece com as metas recomendadas. Você pode alterá-las a qualquer momento.", + "Started": "Iniciado", + "Starts": "Início", + "Steady build": "Evolução constante", + "Step progress": "Progresso de passos", + "Steps": "Passos", + "Stop scanning": "Parar busca", + "Stop using Health Connect": "Parar de usar o Health Connect", + "Stored securely in Android Keystore. Never leaves your device except to call the model. Provider changes apply from your next message.": "Armazenada com segurança no Android Keystore. Nunca sai do seu dispositivo, exceto para chamar o modelo. Mudanças de provedor valem a partir da sua próxima mensagem.", + "Strava": "Strava", + "Strava Integration": "Integração com o Strava", + "Strava Not Configured": "Strava não configurado", + "Strength or circuit training": "Musculação ou treino em circuito", + "Stress": "Estresse", + "Studio, cardio, or freestyle": "Aula, cardio ou livre", + "Summarize my week": "Resumir minha semana", + "Summary copied. It holds counts and timings only, no readings.": "Resumo copiado. Ele contém apenas contagens e horários, nenhuma leitura.", + "Sunday evening: your week compared with the last one, and one thing to focus on.": "Domingo à noite: sua semana comparada com a anterior e um ponto para focar.", + "Supplement": "Suplemento", + "Support": "Suporte", + "Support in Brazil": "Suporte no Brasil", + "Swipe to find your model, then tap to connect.\nYou can also explore first and pair later.": "Deslize para encontrar seu modelo e toque para conectar.\nVocê também pode explorar primeiro e parear depois.", + "Symptom Radar": "Radar de sintomas", + "Symptom radar, sleep debt, stress, body clock, cardio capacity": "Radar de sintomas, débito de sono, estresse, relógio biológico, capacidade cardiorrespiratória", + "Sync Now": "Sincronizar agora", + "Sync all history": "Sincronizar todo o histórico", + "Sync failed": "Falha na sincronização", + "Sync from your scale": "Sincronizar com sua balança", + "Sync now": "Sincronizar agora", + "Sync your ring to start collecting movement, heart rate, blood oxygen, and recovery context.": "Sincronize seu anel para começar a coletar movimento, frequência cardíaca, oxigênio no sangue e dados de recuperação.", + "Syncing latest data…": "Sincronizando dados mais recentes…", + "Syncing…": "Sincronizando…", + "System default": "Padrão do sistema", + "Systolic": "Sistólica", + "TAP TO EDIT GOALS": "TOQUE PARA EDITAR AS METAS", + "TODAY'S BRIEF": "RESUMO DE HOJE", + "Tag day": "Marcar dia", + "Tag yesterday": "Marcar ontem", + "Tag your day": "Marque seu dia", + "Tagged as \"Meditation or relaxing\" in today's journal.": "Marcado como \"Meditação ou relaxamento\" no diário de hoje.", + "Take a blood sugar measurement first, then calibrate": "Faça primeiro uma medição de glicose e depois calibre", + "Take it easy": "Vá com calma", + "Take the check": "Fazer o teste", + "Taken": "Tomado", + "Talk it through": "Conversar sobre isso", + "Tatá, te amo!": "Tatá, te amo!", + "Team or racket sports": "Esportes coletivos ou de raquete", + "Tell the coach, and it plans with your scale, ring and food data.": "Conte ao coach, e ele planeja com os dados da sua balança, do anel e da alimentação.", + "Temperature": "Temperatura", + "That app shares nothing PulseLoop can compare.": "Esse app não compartilha nada que o PulseLoop possa comparar.", + "That looks like PulseLoop's own data coming back through a sync app, so this report would compare the ring with itself. Check the sync direction in that app.": "Parecem ser dados do próprio PulseLoop voltando por um app de sincronização, então este relatório compararia o anel com ele mesmo. Verifique a direção da sincronização nesse app.", + "The AI didn't return a usable estimate. Try again or enter the meal manually.": "A IA não retornou uma estimativa utilizável. Tente novamente ou insira a refeição manualmente.", + "The Health Connect app on this device needs an update before it can be used.": "O app Health Connect deste dispositivo precisa ser atualizado antes de ser usado.", + "The WHO's short alcohol check (AUDIT-C). Three questions, under a minute. A screen, not a diagnosis.": "O teste rápido sobre álcool da OMS (AUDIT-C). Três perguntas, menos de um minuto. Uma triagem, não um diagnóstico.", + "The coach also replies in the language you choose.": "O coach também responde no idioma que você escolher.", + "The import failed. Try again in a moment.": "A importação falhou. Tente novamente em instantes.", + "The report covers the days so far. You'll then choose what happens to the paused Health Connect export.": "O relatório abrange os dias até agora. Depois você escolherá o que acontece com a exportação pausada para o Health Connect.", + "The ring disconnected during measurement.": "O anel se desconectou durante a medição.", + "The ring isn't detecting your finger. Put it on snugly, then try again.": "O anel não está detectando seu dedo. Coloque-o bem justo e tente novamente.", + "The ring recorded this as one record": "O anel registrou isto como um único registro", + "The scan failed. Try again in a moment.": "A busca falhou. Tente novamente em instantes.", + "The tile and the morning-after line disappear. Your logged drinks stay on this phone until you delete them or clear your data.": "O bloco e a linha da manhã seguinte desaparecem. Suas bebidas registradas ficam neste celular até você excluí-las ou apagar seus dados.", + "The workout must finish before now.": "O treino deve terminar antes de agora.", + "These are patterns in your own data, not proof of cause and effect. Every tag is checked against your sleep, HRV and resting heart rate together, so a difference that could easily be chance isn't shown. They get more reliable the more days you tag.": "Estes são padrões nos seus próprios dados, não prova de causa e efeito. Cada marcação é verificada em conjunto com seu sono, HRV e frequência cardíaca em repouso, então uma diferença que poderia facilmente ser acaso não é exibida. Eles ficam mais confiáveis quanto mais dias você marcar.", + "This deletes every record PulseLoop wrote to Health Connect and resets the export. It cannot be undone, and your ring data in PulseLoop is not affected.": "Isso exclui todos os registros que o PulseLoop gravou no Health Connect e redefine a exportação. Não é possível desfazer, e os dados do seu anel no PulseLoop não são afetados.", + "This erases all data stored on the ring and resets it to factory state. We'll sync its latest data into the app first, but this can't be undone. The ring will need to be re-paired afterward.": "Isso apaga todos os dados armazenados no anel e o restaura para o estado de fábrica. Primeiro vamos sincronizar os dados mais recentes com o app, mas isso não pode ser desfeito. O anel precisará ser pareado novamente depois.", + "This is a test check-in notification.": "Esta é uma notificação de check-in de teste.", + "This permanently deletes everything currently in the app and replaces it with the contents of this file. This can't be undone.": "Isso exclui permanentemente tudo o que está no app e substitui pelo conteúdo deste arquivo. Não é possível desfazer.", + "This permanently erases all your data — metrics, sleep, activity, coach history, settings, and saved API keys — and can't be undone.": "Isso apaga permanentemente todos os seus dados — métricas, sono, atividade, histórico do coach, configurações e chaves de API salvas — e não pode ser desfeito.", + "This unbinds the ring and removes it from the app. Your synced data is kept, but you'll need to pair the ring again to keep syncing.": "Isso desvincula o anel e o remove do app. Seus dados sincronizados são mantidos, mas você precisará parear o anel novamente para continuar sincronizando.", + "This unpairs your ring, then permanently erases all your data — metrics, sleep, activity, coach history, settings, and saved API keys — and can't be undone.": "Isso despareia seu anel e depois apaga permanentemente todos os seus dados — métricas, sono, atividade, histórico do coach, configurações e chaves de API salvas — e não pode ser desfeito.", + "This week": "Esta semana", + "This will replace all existing demo data. Your synced ring data — including sleep history — will not be affected.": "Isso substituirá todos os dados de demonstração existentes. Os dados sincronizados do anel — incluindo o histórico de sono — não serão afetados.", + "This workout is no longer in local storage. It may have been deleted or replaced.": "Este treino não está mais no armazenamento local. Ele pode ter sido excluído ou substituído.", + "Time": "Horário", + "Timeout (s)": "Tempo limite (s)", + "Times": "Horários", + "To log when Bedtime or Do Not Disturb turns on and off while PulseLoop is in the background, Android requires Notification access. PulseLoop only listens for Mode changes and does not read your notifications.\n\nIf the switch is greyed out, open PulseLoop's App info, tap ⋮ → Allow restricted settings, then come back here.": "Para registrar quando o modo Hora de dormir ou Não perturbe é ativado e desativado com o PulseLoop em segundo plano, o Android exige acesso às notificações. O PulseLoop só detecta mudanças de modo e não lê suas notificações.\n\nSe a chave estiver desativada, abra Informações do app do PulseLoop, toque em ⋮ → Permitir configurações restritas e volte aqui.", + "Today": "Hoje", + "Tool calling": "Chamada de ferramentas", + "Track Bedtime / DND mode": "Monitorar modo Hora de dormir / Não perturbe", + "Trails and elevation": "Trilhas e elevação", + "Treats a low resting heart rate as a sign of fitness rather than a concern, and relaxes the low-HR threshold.": "Trata uma frequência cardíaca em repouso baixa como sinal de condicionamento, e não de preocupação, e flexibiliza o limite de HR baixa.", + "Trends": "Tendências", + "Trigger real-time ring readings": "Acionar leituras do anel em tempo real", + "Try again": "Tentar novamente", + "Turn off": "Desativar", + "Turn off Drinks": "Desativar Bebidas", + "Turn off Drinks?": "Desativar Bebidas?", + "Turn on": "Ativar", + "Turn on Bluetooth to find and connect your ring.": "Ative o Bluetooth para encontrar e conectar seu anel.", + "Type the name and calories": "Digite o nome e as calorias", + "Typical altitude (ft)": "Altitude típica (ft)", + "Typical altitude (m)": "Altitude típica (m)", + "Typical week before": "Semana típica antes", + "Under 100 steps in an hour, 9:00 to 20:00, at most every two hours. Off in Rest Mode.": "Menos de 100 passos em uma hora, das 9:00 às 20:00, no máximo a cada duas horas. Desativado no Modo descanso.", + "Undo": "Desfazer", + "Units": "Unidades", + "Unpair & Reset": "Desparear e redefinir", + "Unpair & reset": "Desparear e redefinir", + "Unpair Ring": "Desparear anel", + "Unpair ring": "Desparear anel", + "Unpair ring & reset app data?": "Desparear anel e redefinir dados do app?", + "Unpair ring?": "Desparear anel?", + "Unpair your ring? The ring will forget this phone; your data stays.": "Desparear seu anel? O anel vai esquecer este celular; seus dados permanecem.", + "Unusual last night: ": "Incomum na última noite: ", + "Unusual signals alert": "Alerta de sinais incomuns", + "Update Health Connect": "Atualizar o Health Connect", + "Update Key": "Atualizar chave", + "Uploaded 1 workout": "1 treino enviado", + "Usage & cost": "Uso e custo", + "Use location & weather": "Usar localização e clima", + "Use the device you already wear": "Use o dispositivo que você já usa", + "Use the fitted value": "Usar o valor ajustado", + "Use without a ring": "Usar sem anel", + "Use your device's data": "Usar os dados do seu dispositivo", + "Used to tune calories, activity goals, and summaries.": "Usado para ajustar calorias, metas de atividade e resumos.", + "User Profile": "Perfil do usuário", + "Uses additional tokens": "Usa tokens adicionais", + "Using your latest ring sync": "Usando a sincronização mais recente do anel", + "Usual price of a drink (optional)": "Preço habitual de uma bebida (opcional)", + "Version": "Versão", + "View": "Ver", + "Vitals": "Sinais vitais", + "WEEKLY GOAL": "META SEMANAL", + "WHAT THIS MEANS": "O QUE ISSO SIGNIFICA", + "Waiting for BLE connection events…": "Aguardando eventos de conexão BLE…", + "Waiting for first sync": "Aguardando a primeira sincronização", + "Waiting for the first import": "Aguardando a primeira importação", + "Wake the ring by tapping or moving it, and keep it close.": "Desperte o anel tocando ou movendo-o, e mantenha-o por perto.", + "Wake-up": "Despertar", + "Walking": "Caminhada", + "Want to drink less? Track drinks, set a weekly limit and see what each drink does to your nights": "Quer beber menos? Registre as bebidas, defina um limite semanal e veja o que cada dose faz com suas noites", + "We suggest a quarter less to start": "Sugerimos um quarto a menos para começar", + "Wear both devices as you normally would, including at night.": "Use os dois dispositivos normalmente, inclusive à noite.", + "Wear the ring and a watch or band you trust for a few days. PulseLoop reads that device's data from Health Connect and shows where the ring agrees and where it falls short.": "Use o anel e um relógio ou pulseira em que você confia por alguns dias. O PulseLoop lê os dados desse dispositivo no Health Connect e mostra onde o anel concorda e onde ele deixa a desejar.", + "Wear your ring during the day and sync after sleep. Trends become more personal after a few days.": "Use o anel durante o dia e sincronize depois de dormir. As tendências ficam mais personalizadas após alguns dias.", + "Wear your ring overnight to see your hypnogram here.": "Use o anel durante a noite para ver seu hipnograma aqui.", + "Wear your ring today. Your baseline builds from here.": "Use o anel hoje. Sua linha de base começa a ser construída a partir daqui.", + "Wearable": "Wearable", + "Web Search": "Pesquisa na web", + "Week": "Semana", + "Weekly limit": "Limite semanal", + "Weekly report": "Relatório semanal", + "Weekly target": "Meta semanal", + "Weight": "Peso", + "Weight, height and body composition from Health Connect (Fitdays and other scale apps).": "Peso, altura e composição corporal do Health Connect (Fitdays e outros apps de balança).", + "What affects you": "O que afeta você", + "What changed": "O que mudou", + "What did you do?": "O que você fez?", + "What's your goal?": "Qual é a sua meta?", + "When": "Quando", + "When did it end?": "Quando terminou?", + "When did it start?": "Quando começou?", + "When on, sleep the ring records outside the window is trimmed off on import — a still wrist reads as sleep, so an evening on the sofa can log a phantom session and run the night high. Set the start to when you actually go to bed. Naps outside the window are skipped too. Already-imported nights are never touched, and what the gate skips while it is narrower stays skipped.": "Quando ativado, o sono que o anel registra fora da janela é cortado na importação — um pulso parado parece sono, então uma noite no sofá pode registrar uma sessão fantasma e inflar a noite. Defina o início para quando você realmente vai para a cama. Cochilos fora da janela também são ignorados. Noites já importadas nunca são alteradas, e o que o filtro ignora enquanto está mais estreito continua ignorado.", + "When the ring is at 30% or less a couple of hours before your usual bedtime.": "Quando o anel estiver com 30% ou menos algumas horas antes do seu horário habitual de dormir.", + "When two or more of last night's signals are outside your usual range.": "Quando dois ou mais sinais da última noite estiverem fora da sua faixa habitual.", + "When you want a drink": "Quando você quiser beber", + "Where the ring falls short": "Onde o anel deixa a desejar", + "While a check runs, PulseLoop stops exporting the types the other device also writes, so Health Connect doesn't count your steps, sleep and heart rate twice.": "Enquanto uma verificação está em andamento, o PulseLoop para de exportar os tipos que o outro dispositivo também grava, para que o Health Connect não conte seus passos, sono e frequência cardíaca em dobro.", + "Why there's no score today": "Por que não há pontuação hoje", + "Wind-down reminder": "Lembrete para relaxar", + "Wine": "Vinho", + "With stages: ": "Com estágios: ", + "Workout": "Treino", + "Workout history": "Histórico de treinos", + "Workout in progress": "Treino em andamento", + "Workout not found": "Treino não encontrado", + "Workouts": "Treinos", + "Workouts / week": "Treinos / semana", + "Write Actions": "Ações de escrita", + "YOUR GOAL": "SUA META", + "Yes, a nap": "Sim, um cochilo", + "Yesterday": "Ontem", + "Yoga": "Ioga", + "You are now a developer!": "Agora você é um desenvolvedor!", + "You can pair a ring later from Settings.": "Você pode parear um anel depois em Configurações.", + "You can use either a comma or a period as the decimal separator.": "Você pode usar vírgula ou ponto como separador decimal.", + "You're all set": "Tudo pronto", + "Your age, sex, height and weight let the ring compute accurate calories (and, on 56ff/Jring rings, blood sugar). Blood pressure is measured directly by the sensor.": "Sua idade, sexo, altura e peso permitem que o anel calcule as calorias com precisão (e, nos anéis 56ff/Jring, a glicose). A pressão arterial é medida diretamente pelo sensor.", + "Your data has been restored from the backup.": "Seus dados foram restaurados a partir do backup.", + "Your drinks stay on this phone. They aren't sent to Health Connect or included in diagnostics.": "Suas bebidas ficam neste celular. Elas não são enviadas ao Health Connect nem incluídas nos diagnósticos.", + "Your goal doesn't set any of these.": "Sua meta não define nenhum destes.", + "Your goal, until 5 recovered nights teach the app yours": "Sua meta, até que 5 noites de recuperação ensinem ao app a sua", + "Your health, on your terms — no subscription, no cloud.": "Sua saúde, do seu jeito — sem assinatura, sem nuvem.", + "Your nights": "Suas noites", + "Your nights against your own normal, kept as a log": "Suas noites comparadas ao seu próprio normal, guardadas como registro", + "Your nights look like your usual. That's an answer too.": "Suas noites parecem as de sempre. Isso também é uma resposta.", + "Your personalized baseline unlocks": "Sua linha de base personalizada é liberada", + "Your phone counts steps too. Comparing the two over a few days shows whether your ring over- or under-counts.": "Seu celular também conta passos. Comparar os dois por alguns dias mostra se o seu anel conta passos a mais ou a menos.", + "Your preference: ": "Sua preferência: ", + "Your ring logs heart rate every few minutes, so short sessions may show none.": "Seu anel registra a frequência cardíaca a cada poucos minutos, então sessões curtas podem não mostrar nenhuma.", + "Your schedule, today's doses and a week's record": "Seus horários, as doses de hoje e o registro da semana", + "Your workout is still recording. Finish it now, or keep recording?": "Seu treino ainda está sendo gravado. Finalizar agora ou continuar gravando?" +} \ No newline at end of file diff --git a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt index 5806b5a5..5c1c34e1 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt @@ -655,11 +655,11 @@ object MealAnalysisLogic { /** Verbatim system prompt (MealAnalysisSheet.swift:338-342). */ val systemPrompt: String = - tr("You are a nutrition estimator. Given a meal description and/or photo, " + + "You are a nutrition estimator. Given a meal description and/or photo, " + "identify the food and estimate total calories and macros for the portion shown or described. " + "Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. " + "Use confidence \"high\" only for clearly identifiable, standard portions. " + - "Return only JSON matching the schema.") + "Return only JSON matching the schema." /** * The verbatim strict meal_estimate json_schema (MealAnalysisSheet.swift:344-362), built @@ -669,12 +669,12 @@ object MealAnalysisLogic { fun described(value: String) = JsonObject(mapOf("type" to JsonPrimitive("string"), "description" to JsonPrimitive(value))) fun number() = JsonObject(mapOf("type" to JsonPrimitive("number"))) val props = JsonObject(mapOf( - "name" to described(tr("Short display name for the meal")), + "name" to described("Short display name for the meal"), "calories" to number(), "protein_g" to number(), "carbs_g" to number(), "fat_g" to number(), - "assumptions" to described(tr("Portion/preparation assumptions, one short sentence, or empty string")), + "assumptions" to described("Portion/preparation assumptions, one short sentence, or empty string"), "confidence" to JsonObject(mapOf( "type" to JsonPrimitive("string"), "enum" to JsonArray(listOf(JsonPrimitive("low"), JsonPrimitive("medium"), JsonPrimitive("high"))), @@ -744,7 +744,7 @@ object MealEstimator { } // iOS :392 — the description, or the photo-only prompt. - val prompt = description.trim().ifEmpty { tr("Estimate the nutrition of the meal in the photo.") } + val prompt = description.trim().ifEmpty { "Estimate the nutrition of the meal in the photo." } val input = JsonArray(listOf( OpenAIRequestBuilder.message("system", MealAnalysisLogic.systemPrompt), OpenAIRequestBuilder.message("user", prompt, images),