diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/presentation/manager/SettingsManagerTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/presentation/manager/SettingsManagerTest.kt index f0bc0599a..e02131495 100644 --- a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/presentation/manager/SettingsManagerTest.kt +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/presentation/manager/SettingsManagerTest.kt @@ -4,6 +4,7 @@ import com.devil.phoenixproject.data.preferences.SettingsPreferencesManager import com.devil.phoenixproject.data.repository.ActiveProfileContext import com.devil.phoenixproject.domain.model.ScalingBasis import com.devil.phoenixproject.domain.model.UserPreferences +import com.devil.phoenixproject.domain.model.WeightTextScale import com.devil.phoenixproject.domain.model.WeightUnit import com.devil.phoenixproject.domain.model.WorkoutPreferences import com.devil.phoenixproject.testutil.FakePreferencesManager @@ -107,6 +108,32 @@ class SettingsManagerTest { } } + @Test + fun `weight text scale is global and survives profile preference overlay`() = runTest { + val managerScope = CoroutineScope(coroutineContext + SupervisorJob()) + try { + val manager = SettingsManager(fakePreferencesManager, fakeProfileRepository, managerScope) + + manager.setWeightTextScale(WeightTextScale.EXTRA_LARGE) + advanceUntilIdle() + assertEquals(WeightTextScale.EXTRA_LARGE, manager.userPreferences.value.weightTextScale) + assertEquals(WeightTextScale.EXTRA_LARGE, fakePreferencesManager.preferencesFlow.value.weightTextScale) + + // A profile preference write re-runs overlayProfile; the global weight text + // size must ride through untouched (SD6: the field is not in overlayProfile). + val ready = readyProfile() + fakeProfileRepository.updateCore( + ready.profile.id, + ready.preferences.core.value.copy(weightUnit = WeightUnit.KG), + ) + advanceUntilIdle() + assertEquals(WeightTextScale.EXTRA_LARGE, manager.userPreferences.value.weightTextScale) + assertEquals(WeightUnit.KG, manager.userPreferences.value.weightUnit, "overlay still applies") + } finally { + managerScope.cancel() + } + } + @Test fun `routine exercise percent defaults are off and eighty percent`() = runTest { val managerScope = CoroutineScope(coroutineContext + SupervisorJob()) diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/presentation/util/LocalWeightTextScaleDefaultTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/presentation/util/LocalWeightTextScaleDefaultTest.kt new file mode 100644 index 000000000..0f86daacc --- /dev/null +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/presentation/util/LocalWeightTextScaleDefaultTest.kt @@ -0,0 +1,44 @@ +package com.devil.phoenixproject.presentation.util + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.test.junit4.createComposeRule +import com.devil.phoenixproject.domain.model.WeightTextScale +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * Issue #1367 T12: `LocalWeightTextScale` defaults to STANDARD outside the app shell + * (previews and tests render unchanged base typography) and honors a provided value. + * Asserted through a real composition because `CompositionLocal.current` is @Composable. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w411dp-h891dp") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class LocalWeightTextScaleDefaultTest { + + @get:Rule + val compose = createComposeRule() + + @Test + fun defaultsToStandardOutsideProvider() { + var seen: WeightTextScale? = null + compose.setContent { seen = LocalWeightTextScale.current } + assertEquals(WeightTextScale.STANDARD, seen) + } + + @Test + fun providerOverrideIsVisibleToTheShell() { + var seen: WeightTextScale? = null + compose.setContent { + CompositionLocalProvider(LocalWeightTextScale provides WeightTextScale.EXTRA_LARGE) { + seen = LocalWeightTextScale.current + } + } + assertEquals(WeightTextScale.EXTRA_LARGE, seen) + } +} diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/presentation/util/WeightTextScaleAndroidConversionTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/presentation/util/WeightTextScaleAndroidConversionTest.kt new file mode 100644 index 000000000..d9cd70aa4 --- /dev/null +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/presentation/util/WeightTextScaleAndroidConversionTest.kt @@ -0,0 +1,101 @@ +package com.devil.phoenixproject.presentation.util + +import android.util.DisplayMetrics +import android.util.TypedValue +import com.devil.phoenixproject.domain.model.WeightTextScale +import kotlin.math.abs +import kotlin.test.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * Issue #1367 T11 / SD1: prove the physical ceiling through the ACTUAL platform density + * converter (`TypedValue.applyDimension`), not through sp arithmetic. + * + * The contract: the style helper multiplies fontSize by M = E/O (E = min(A*O, 2)), so the + * rendered physical size is `base * E`, capped at [WEIGHT_TEXT_MAX_EFFECTIVE_SCALE] x base. + * The ceiling is asserted against the OS-1.0 physical base (`baseSp * density`) for both + * linear scaledDensity and Android's nonlinear large-font conversion + * (scaledDensity < density * fontScale), and a negative control proves the test would + * catch the uncapped `* A` regression the signoff warned about. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class WeightTextScaleAndroidConversionTest { + + private fun spToPx(sp: Float, density: Float, scaledDensity: Float): Float { + val metrics = DisplayMetrics().apply { + this.density = density + this.scaledDensity = scaledDensity + } + return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, metrics) + } + + /** Android 14+ nonlinear font scaling: physical scale grows sub-linearly past ~1.0. */ + private fun nonlinearScaledDensity(density: Float, fontScale: Float): Float = + if (fontScale > 1f) density * (1f + (fontScale - 1f) * 0.8f) else density * fontScale + + @Test + fun physicalRenderedSizeNeverExceedsTwoXBaseThroughThePlatformConverter() { + val baseSp = 28f + val density = 1f + for (scale in WeightTextScale.entries) { + for (os in listOf(0.85f, 1f, 1.5f, 2f, 2.5f, 3f)) { + val profiles = listOf( + "linear" to density * os, + "nonlinear" to nonlinearScaledDensity(density, os), + ) + for ((profile, scaledDensity) in profiles) { + val multiplier = weightTextMultiplier(scale.preferenceFactor, os) + val targetSp = baseSp * multiplier + val renderedPx = spToPx(targetSp, density, scaledDensity) + val ceilingPx = WEIGHT_TEXT_MAX_EFFECTIVE_SCALE * baseSp * density + assertTrue( + renderedPx <= ceilingPx + 0.001f, + "rendered ${renderedPx}px exceeds ceiling ${ceilingPx}px for $scale at OS $os ($profile)", + ) + } + } + } + } + + @Test + fun uncappedAppFactorWouldViolateTheCeiling_provingTheTestDiscriminates() { + // Negative control: the pre-signoff defect (style *= A, no rendered cap) renders + // base*A*O = 4x base at A=2/O=2 — this test MUST be able to fail. + val baseSp = 28f + val density = 1f + val os = 2f + val uncappedTargetSp = baseSp * WeightTextScale.EXTRA_LARGE.preferenceFactor + val renderedPx = spToPx(uncappedTargetSp, density, density * os) + val ceilingPx = WEIGHT_TEXT_MAX_EFFECTIVE_SCALE * baseSp * density + assertTrue( + renderedPx > ceilingPx + 0.001f, + "negative control: uncapped rendering unexpectedly within ceiling", + ) + } + + @Test + fun cappedTargetDerivedThroughTheConverterRoundTripsAndStaysBounded() { + // SD1: derive the capped target and the inverse conversion through the platform + // converter (px / scaledDensity), never assume sp division by fontScale. + val baseSp = 22f + val density = 1f + for (os in listOf(1f, 1.5f, 2f, 2.5f)) { + val scaledDensity = nonlinearScaledDensity(density, os) + for (scale in WeightTextScale.entries) { + val targetSp = baseSp * weightTextMultiplier(scale.preferenceFactor, os) + val targetPx = spToPx(targetSp, density, scaledDensity) + val recoveredSp = targetPx / scaledDensity + assertTrue(abs(recoveredSp - targetSp) < 0.001f, "inverse conversion drifted") + assertTrue( + recoveredSp * os <= baseSp * WEIGHT_TEXT_MAX_EFFECTIVE_SCALE + 0.001f || + scaledDensity < density * os, + "capped target exceeds the linear-model ceiling at OS $os for $scale", + ) + } + } + } +} diff --git a/shared/src/commonMain/composeResources/values-de/strings.xml b/shared/src/commonMain/composeResources/values-de/strings.xml index a10e69f9b..b6f84cf9f 100644 --- a/shared/src/commonMain/composeResources/values-de/strings.xml +++ b/shared/src/commonMain/composeResources/values-de/strings.xml @@ -888,6 +888,14 @@ Keine passende Aktivität gefunden Mehr als eine passende Aktivität gefunden Pausiert + + Gewichtsschriftgröße + Vergrößert Gewichtswerte in Set-Vorbereitung, Routinenübersicht, Pause, Übungseinrichtung und Trainingsanzeigen. Just Lift bleibt in dieser ersten Version unverändert. Wird nur auf diesem Gerät gespeichert. + Kombiniert sich mit der Schriftgröße deines Geräts, bis zu 2× der Standard-Basisschriftgröße. Die Optionen können bei größeren Geräteschriftgrößen gleich aussehen. Diese Grenze gilt auch für Standard, wenn die Geräteschriftgröße sie überschreitet. + Standard + Groß + Sehr groß + Gewichtsschriftgröße Fotos · %1$d von %2$d Fotos hinzufügen diff --git a/shared/src/commonMain/composeResources/values-es/strings.xml b/shared/src/commonMain/composeResources/values-es/strings.xml index 9331ceae6..c5ddabb50 100644 --- a/shared/src/commonMain/composeResources/values-es/strings.xml +++ b/shared/src/commonMain/composeResources/values-es/strings.xml @@ -888,6 +888,14 @@ No se encontró una actividad coincidente Se encontró más de una actividad coincidente En pausa + + Tamaño del texto del peso + Amplía los valores de peso en Preparación de serie, Resumen de rutina, descanso, configuración de ejercicios y lecturas del entrenamiento. Just Lift no cambia en esta primera versión. Se guarda solo en este dispositivo. + Se combina con el tamaño de texto del dispositivo, hasta 2× el tamaño base estándar. Las opciones pueden verse iguales con tamaños de texto del dispositivo más grandes. Este límite también se aplica a Estándar cuando el tamaño de texto del dispositivo lo supera. + Estándar + Grande + Muy grande + Tamaño del texto del peso Fotos · %1$d de %2$d Añadir fotos diff --git a/shared/src/commonMain/composeResources/values-fr/strings.xml b/shared/src/commonMain/composeResources/values-fr/strings.xml index 54f3960f9..99c476845 100644 --- a/shared/src/commonMain/composeResources/values-fr/strings.xml +++ b/shared/src/commonMain/composeResources/values-fr/strings.xml @@ -888,6 +888,14 @@ Aucune activité correspondante trouvée Plusieurs activités correspondantes trouvées En pause + + Taille du texte des poids + Agrandit les valeurs de poids dans Préparation de série, Aperçu de la routine, la pause, la configuration des exercices et les affichages d'entraînement. Just Lift reste inchangé dans cette première version. Enregistré sur cet appareil uniquement. + Se combine avec la taille du texte de votre appareil, jusqu'à 2× la taille de base standard. Les options peuvent sembler identiques avec des tailles de texte plus grandes. Cette limite s'applique aussi à Standard lorsque la taille du texte de l'appareil la dépasse. + Standard + Grand + Très grand + Taille du texte des poids Photos · %1$d sur %2$d Ajouter des photos diff --git a/shared/src/commonMain/composeResources/values-it/strings.xml b/shared/src/commonMain/composeResources/values-it/strings.xml index 9a47bd09d..588393bbd 100644 --- a/shared/src/commonMain/composeResources/values-it/strings.xml +++ b/shared/src/commonMain/composeResources/values-it/strings.xml @@ -224,6 +224,14 @@ Nessuna attività corrispondente trovata Trovata più di un'attività corrispondente In pausa + + Dimensione del testo del peso + Ingrandisce i valori del peso in Preparazione serie, Panoramica routine, recupero, configurazione degli esercizi e letture dell'allenamento. Just Lift resta invariato in questa prima versione. Salvato solo su questo dispositivo. + Si combina con la dimensione del testo del dispositivo, fino a 2× la dimensione base standard. Le opzioni possono apparire uguali con dimensioni del testo maggiori. Questo limite si applica anche a Standard quando la dimensione del testo del dispositivo lo supera. + Standard + Grande + Molto grande + Dimensione del testo del peso Foto · %1$d di %2$d Aggiungi foto diff --git a/shared/src/commonMain/composeResources/values-nl/strings.xml b/shared/src/commonMain/composeResources/values-nl/strings.xml index e05340908..eb6629fff 100644 --- a/shared/src/commonMain/composeResources/values-nl/strings.xml +++ b/shared/src/commonMain/composeResources/values-nl/strings.xml @@ -866,6 +866,14 @@ Geen overeenkomende activiteit gevonden Meer dan één overeenkomende activiteit gevonden Gepauzeerd + + Grootte van gewichtstekst + Vergroot gewichtswaarden in Set-klaarzetten, Routineoverzicht, rust, oefening instellen en trainingsweergaven. Just Lift blijft in deze eerste versie ongewijzigd. Alleen op dit apparaat opgeslagen. + Combineert met de tekstgrootte van je apparaat, tot 2× de standaard basisgrootte. Opties kunnen er hetzelfde uitzien bij grotere apparaattekstgroottes. Deze limiet geldt ook voor Standaard wanneer de apparaattekstgrootte deze overschrijdt. + Standaard + Groot + Extra groot + Grootte van gewichtstekst Foto's · %1$d van %2$d Foto's toevoegen diff --git a/shared/src/commonMain/composeResources/values/strings.xml b/shared/src/commonMain/composeResources/values/strings.xml index 5aadce012..54bdb2005 100644 --- a/shared/src/commonMain/composeResources/values/strings.xml +++ b/shared/src/commonMain/composeResources/values/strings.xml @@ -1059,6 +1059,14 @@ No matching activity found More than one matching activity found Paused + + Weight text size + Enlarges weight values in Set Ready, Routine Overview, rest, exercise setup and workout readouts. Just Lift is unchanged in this first version. Saved on this device only. + Combines with your device text size, up to 2× the standard base size. Options may look the same at larger device text sizes. This limit also applies to Standard when your device text size exceeds it. + Standard + Large + Extra large + Weight text size Photos · %1$d of %2$d Add photos diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/preferences/PreferencesManager.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/preferences/PreferencesManager.kt index ac75af545..bad621778 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/preferences/PreferencesManager.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/preferences/PreferencesManager.kt @@ -8,6 +8,7 @@ import com.devil.phoenixproject.domain.model.RepCountTiming import com.devil.phoenixproject.domain.model.ScalingBasis import com.devil.phoenixproject.domain.model.UserPreferences import com.devil.phoenixproject.domain.model.VulgarTier +import com.devil.phoenixproject.domain.model.WeightTextScale import com.devil.phoenixproject.domain.model.WeightUnit import com.devil.phoenixproject.util.BackupDestination import com.devil.phoenixproject.util.BackupDestination.Companion.toJson @@ -89,6 +90,15 @@ interface PreferencesManager { */ suspend fun resetOneShotWorkAfterRestore() suspend fun setBleCompatibilityMode(setting: BleCompatibilitySetting) + + /** + * Issue #1367: global device-local weight-text-size preference. Mirrors + * [setBleCompatibilityMode] (the in-repo precedent for a global preference set + * from Settings): the delegating caller ([com.devil.phoenixproject.presentation.manager.SettingsManager]) + * holds this interface, so the write must be reachable here. Never enters + * overlayProfile, backup, or portal codecs. + */ + suspend fun setWeightTextScale(scale: WeightTextScale) fun getExerciseCatalogSource(): String suspend fun setExerciseCatalogSource(source: String) @@ -160,6 +170,9 @@ class SettingsPreferencesManager(private val settings: Settings) : PreferencesMa // Issue #333: BLE small-MTU compatibility path (Auto/On/Off) private const val KEY_BLE_COMPATIBILITY_MODE = "ble_compatibility_mode" + // Issue #1367: weight text size (global/device-local; enum NAME stored) + private const val KEY_WEIGHT_TEXT_SCALE = "weight_text_scale" + private const val KEY_EXERCISE_CATALOG_SOURCE = "exercise_catalog_source" private const val KEY_LAST_CONNECTED_MODEL = "last_connected_model" } @@ -237,6 +250,10 @@ class SettingsPreferencesManager(private val settings: Settings) : PreferencesMa lastConnectedModel = settings.getStringOrNull(KEY_LAST_CONNECTED_MODEL) ?.let { stored -> PhoenixModel.entries.find { model -> model.name == stored } } ?: PhoenixModel.Unknown, + // Issue #1367: unknown/corrupt/absent -> STANDARD, never throws + weightTextScale = WeightTextScale.fromStorage( + settings.getStringOrNull(KEY_WEIGHT_TEXT_SCALE), + ), ) } @@ -401,6 +418,18 @@ class SettingsPreferencesManager(private val settings: Settings) : PreferencesMa updateAndEmit { copy(bleCompatibilityMode = setting) } } + override suspend fun setWeightTextScale(scale: WeightTextScale) { + try { + settings.putString(KEY_WEIGHT_TEXT_SCALE, scale.name) + } catch (error: Exception) { + // SD10: a failed persistence write must not corrupt stored state and must not + // block the session-level choice from applying. The stored key keeps its + // previous value; the in-memory flow still reflects the user's pick. + Logger.e(error) { "Failed to persist weight_text_scale; applying in memory only" } + } + updateAndEmit { copy(weightTextScale = scale) } + } + internal fun isAdultsOnlyPrompted(): Boolean = settings.getBoolean(KEY_ADULTS_ONLY_PROMPTED, false) /** diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/UserPreferences.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/UserPreferences.kt index c863bb35e..119f04055 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/UserPreferences.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/UserPreferences.kt @@ -70,6 +70,9 @@ data class UserPreferences( // offline, so they pick a per-cable ceiling from this instead of assuming the widest // hardware. Commands never use it — they use the LIVE connected model. val lastConnectedModel: PhoenixModel = PhoenixModel.Unknown, + // Issue #1367: weight-text-size preference for the weight selection surfaces. + // Global + device-local on purpose: NOT in overlayProfile, backup, or portal codecs. + val weightTextScale: WeightTextScale = WeightTextScale.STANDARD, ) { /** * Get the effective weight increment in the user's display unit. diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/WeightTextScale.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/WeightTextScale.kt new file mode 100644 index 000000000..92c9ca24d --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/WeightTextScale.kt @@ -0,0 +1,35 @@ +package com.devil.phoenixproject.domain.model + +/** + * Issue #1367: global device-local weight-text-size preference. + * + * Selects how large weight values render on the safety-critical weight surfaces + * (Set Ready / Routine Overview / Rest Timer sliders, workout HUD readout, WeightStepper). + * The factor is the nominal app scale (1 / 1.5 / 2); the RENDERED size is additionally + * capped against the OS font scale by the style helper + * (`com.devil.phoenixproject.presentation.util.WeightTextScaling`), so this factor alone + * is not the effective on-screen scale. + * + * This preference is global and device-local: it is deliberately absent from + * `overlayProfile` and from the backup/portal codecs, so it is never synced or restored. + */ +enum class WeightTextScale(val preferenceFactor: Float) { + /** Current/base weight typography. */ + STANDARD(1f), + + /** ~1.5x base weight text. */ + LARGE(1.5f), + + /** ~2x base weight text (meets the lower end of the reporter's 2-3x request). */ + EXTRA_LARGE(2f), + ; + + companion object { + /** + * Normalize a persisted enum name. Missing/unknown/corrupt/empty values + * load as [STANDARD] and never throw (issue #1367 SD6). + */ + fun fromStorage(value: String?): WeightTextScale = + entries.find { it.name == value } ?: STANDARD + } +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/SettingsManager.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/SettingsManager.kt index fa16b51c7..3faa7f905 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/SettingsManager.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/SettingsManager.kt @@ -12,6 +12,7 @@ import com.devil.phoenixproject.domain.model.JustLiftDefaultsDocument import com.devil.phoenixproject.domain.model.ScalingBasis import com.devil.phoenixproject.domain.model.SingleExerciseDefaultsDocument import com.devil.phoenixproject.domain.model.UserPreferences +import com.devil.phoenixproject.domain.model.WeightTextScale import com.devil.phoenixproject.domain.model.WeightUnit import com.devil.phoenixproject.domain.model.WorkoutPreferences import com.devil.phoenixproject.util.BackupDestination @@ -262,6 +263,12 @@ class SettingsManager( scope.launch { globalPreferences.setBleCompatibilityMode(setting) } } + // Issue #1367: global/device-local weight text size. Deliberately NOT part of + // overlayProfile — the field stays global precisely because it is absent there. + fun setWeightTextScale(scale: WeightTextScale) { + scope.launch { globalPreferences.setWeightTextScale(scale) } + } + fun kgToDisplay(kg: Float, unit: WeightUnit): Float = when (unit) { WeightUnit.KG -> kg WeightUnit.LB -> UnitConverter.kgToLb(kg) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/MainViewModel.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/MainViewModel.kt index 47842ee4a..642126078 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/MainViewModel.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/MainViewModel.kt @@ -53,6 +53,7 @@ import com.devil.phoenixproject.domain.model.RoutineGroup import com.devil.phoenixproject.domain.model.RoutineLaunchOrigin import com.devil.phoenixproject.domain.model.SessionBodyweightState import com.devil.phoenixproject.domain.model.UserPreferences +import com.devil.phoenixproject.domain.model.WeightTextScale import com.devil.phoenixproject.domain.model.WeightUnit import com.devil.phoenixproject.domain.model.WorkoutMetric import com.devil.phoenixproject.domain.model.WorkoutParameters @@ -133,6 +134,7 @@ data class SettingsGlobalUiState( val includeRawTelemetryInBackups: Boolean, val backupDestination: BackupDestination, val language: String, + val weightTextScale: WeightTextScale, ) private fun UserPreferences.toSettingsGlobalUiState() = SettingsGlobalUiState( @@ -142,6 +144,7 @@ private fun UserPreferences.toSettingsGlobalUiState() = SettingsGlobalUiState( includeRawTelemetryInBackups = includeRawTelemetryInBackups, backupDestination = backupDestination, language = language, + weightTextScale = weightTextScale, ) internal enum class RoutineResumeRetryAction { @@ -957,6 +960,9 @@ class MainViewModel( // Issue #333: BLE small-MTU compatibility path (Auto/On/Off) fun setBleCompatibilityMode(setting: BleCompatibilitySetting) = settingsManager.setBleCompatibilityMode(setting) + + // Issue #1367: global/device-local weight text size (Standard/Large/Extra large) + fun setWeightTextScale(scale: WeightTextScale) = settingsManager.setWeightTextScale(scale) fun setAutoBackupEnabled(enabled: Boolean) { settingsManager.setAutoBackupEnabled(enabled) refreshBackupStats() diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/preferences/SettingsPreferencesManagerTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/preferences/SettingsPreferencesManagerTest.kt index eec4354d2..468109fe2 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/preferences/SettingsPreferencesManagerTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/preferences/SettingsPreferencesManagerTest.kt @@ -2,13 +2,17 @@ package com.devil.phoenixproject.data.preferences import com.devil.phoenixproject.domain.model.EchoLevel import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.model.WeightTextScale import com.russhwolf.settings.MapSettings +import com.russhwolf.settings.Settings import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.yield class SettingsPreferencesManagerTest { @@ -76,6 +80,67 @@ class SettingsPreferencesManagerTest { assertFalse(reloaded.preferencesFlow.value.weightSuggestionsEnabled) } + // ===== Issue #1367 (T2/T3/T13): weight_text_scale persistence ===== + + @Test + fun `weight text size stores the enum name and round trips`() = runTest { + val settings = MapSettings() + val manager = SettingsPreferencesManager(settings) + + assertEquals(WeightTextScale.STANDARD, manager.preferencesFlow.value.weightTextScale, "absent key -> STANDARD") + + manager.setWeightTextScale(WeightTextScale.EXTRA_LARGE) + assertEquals(WeightTextScale.EXTRA_LARGE, manager.preferencesFlow.value.weightTextScale) + assertEquals("EXTRA_LARGE", settings.getString("weight_text_scale", ""), "enum NAME stored") + + val reloaded = SettingsPreferencesManager(settings) + assertEquals(WeightTextScale.EXTRA_LARGE, reloaded.preferencesFlow.value.weightTextScale) + } + + @Test + fun `weight text size emits on preferencesFlow and rapid changes end at the last value`() = runTest { + val settings = MapSettings() + val manager = SettingsPreferencesManager(settings) + val emissions = mutableListOf() + val job = backgroundScope.launch { + manager.preferencesFlow.collect { emissions.add(it.weightTextScale) } + } + + manager.setWeightTextScale(WeightTextScale.LARGE) + yield() + manager.setWeightTextScale(WeightTextScale.STANDARD) + yield() + manager.setWeightTextScale(WeightTextScale.EXTRA_LARGE) + yield() + + assertEquals(WeightTextScale.EXTRA_LARGE, manager.preferencesFlow.value.weightTextScale, "last choice wins") + assertEquals("EXTRA_LARGE", settings.getString("weight_text_scale", "")) + assertTrue(emissions.contains(WeightTextScale.LARGE), "preferencesFlow emitted intermediate choices") + job.cancel() + } + + @Test + fun `failed weight text size write applies the session choice without corrupting storage`() = runTest { + val backing = MapSettings() + val failing = FailingWeightTextScaleSettings(backing) + val manager = SettingsPreferencesManager(failing) + + manager.setWeightTextScale(WeightTextScale.LARGE) + assertEquals(WeightTextScale.LARGE, manager.preferencesFlow.value.weightTextScale, "session choice applied") + assertEquals( + WeightTextScale.STANDARD, + SettingsPreferencesManager(backing).preferencesFlow.value.weightTextScale, + "failed write left stored state uncorrupted", + ) + + failing.failWrites = false + manager.setWeightTextScale(WeightTextScale.EXTRA_LARGE) + assertEquals( + WeightTextScale.EXTRA_LARGE, + SettingsPreferencesManager(backing).preferencesFlow.value.weightTextScale, + ) + } + private fun singleExerciseDefaults( workoutModeId: Int = ProgramMode.Echo.modeValue, echoLevelValue: Int, @@ -94,3 +159,17 @@ class SettingsPreferencesManagerTest { perSetRestTime = false, ) } + +/** + * Issue #1367 T13: a [Settings] wrapper whose `weight_text_scale` writes fail on demand, + * to prove the write-error contract (session choice applied, stored state uncorrupted). + */ +private class FailingWeightTextScaleSettings( + private val delegate: MapSettings, + var failWrites: Boolean = true, +) : Settings by delegate { + override fun putString(key: String, value: String) { + if (failWrites && key == "weight_text_scale") error("simulated disk failure") + delegate.putString(key, value) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/model/WeightTextScaleTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/model/WeightTextScaleTest.kt new file mode 100644 index 000000000..5655a632a --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/model/WeightTextScaleTest.kt @@ -0,0 +1,34 @@ +package com.devil.phoenixproject.domain.model + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Issue #1367 T1/T3: enum normalization for the persisted weight text size. + * Missing/unknown/corrupt/empty values load as STANDARD and never throw (SD6). + */ +class WeightTextScaleTest { + + @Test + fun `known enum names parse`() { + assertEquals(WeightTextScale.STANDARD, WeightTextScale.fromStorage("STANDARD")) + assertEquals(WeightTextScale.LARGE, WeightTextScale.fromStorage("LARGE")) + assertEquals(WeightTextScale.EXTRA_LARGE, WeightTextScale.fromStorage("EXTRA_LARGE")) + } + + @Test + fun `unknown corrupt empty or missing values normalize to STANDARD without throwing`() { + val badValues = listOf("XL", "3", "", "standard", "Large ", "EXTRA LARGE", "\u0000", "null") + for (value in badValues) { + assertEquals(WeightTextScale.STANDARD, WeightTextScale.fromStorage(value), "value=$value") + } + assertEquals(WeightTextScale.STANDARD, WeightTextScale.fromStorage(null)) + } + + @Test + fun `nominal preference factors are the signoff 1x 1 5x 2x mapping`() { + assertEquals(1f, WeightTextScale.STANDARD.preferenceFactor) + assertEquals(1.5f, WeightTextScale.LARGE.preferenceFactor) + assertEquals(2f, WeightTextScale.EXTRA_LARGE.preferenceFactor) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/components/WeightTextSizeSurfaceGuardTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/components/WeightTextSizeSurfaceGuardTest.kt new file mode 100644 index 000000000..f9fd29983 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/components/WeightTextSizeSurfaceGuardTest.kt @@ -0,0 +1,195 @@ +package com.devil.phoenixproject.presentation.components + +import com.devil.phoenixproject.testutil.readProjectFile +import kotlin.test.Test +import kotlin.test.assertContains +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Issue #1367 T16/T17/T20 + SD4/SD12: source-text guards for the weight-text-size surfaces. + * + * T16: the weight `SliderWithButtons` sites carry the explicit `isWeightValue = true` + * opt-in (SD5) and the rep sites do not. The expectations below are derived from the + * call-site re-census on this branch (3 weight / 5 rep at main@4d4de558) — if the census + * numbers change because a call site was legitimately added, re-census and update the + * expectations rather than deleting the guard. + * + * T17: both `WorkoutHud.HudBottomBar` value branches (numeric/"Adaptive" and bodyweight + * "No machine load") use the scaled value style while the supporting labelSmall labels + * stay unscaled (SD9). + * + * T20/SD4: `shouldStackWeightCards` stays byte-identical (iOS gesture-conflict guard), + * and Just Lift / `CompactNumberPicker` never see the weight text scale (Option B). + * + * SD12: the presentation-only invariant — no backup/restore, portal codec, SQLDelight, + * or tvOS file ever touches the preference key. + */ +class WeightTextSizeSurfaceGuardTest { + + private val sliderComponentPath = + "src/commonMain/kotlin/com/devil/phoenixproject/presentation/components/SliderWithButtons.kt" + private val screenPaths = listOf( + "src/commonMain/kotlin/com/devil/phoenixproject/presentation/screen/SetReadyScreen.kt", + "src/commonMain/kotlin/com/devil/phoenixproject/presentation/screen/RoutineOverviewScreen.kt", + "src/commonMain/kotlin/com/devil/phoenixproject/presentation/screen/RestTimerCard.kt", + ) + private val hudPath = "src/commonMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt" + private val windowSizeClassPath = "src/commonMain/kotlin/com/devil/phoenixproject/presentation/util/WindowSizeClass.kt" + private val justLiftPath = "src/commonMain/kotlin/com/devil/phoenixproject/presentation/screen/JustLiftScreen.kt" + + private fun source(path: String): String = requireNotNull(readProjectFile(path)) { path } + + /** Extract every balanced-paren call body starting at each [marker] occurrence. */ + private fun callBodies(source: String, marker: String): List { + val bodies = mutableListOf() + var searchFrom = 0 + while (true) { + val start = source.indexOf(marker, searchFrom) + if (start < 0) break + val open = source.indexOf('(', start) + var depth = 0 + var end = -1 + for (index in open until source.length) { + when (source[index]) { + '(' -> depth += 1 + ')' -> { + depth -= 1 + if (depth == 0) { + end = index + break + } + } + } + } + assertTrue(end > open, "unbalanced call at $start") + bodies.add(source.substring(open, end + 1)) + searchFrom = end + } + return bodies + } + + private fun isWeightSite(body: String): Boolean = + body.contains("rest_weight_per_cable") || body.contains("\"Weight per cable\"") + + @Test + fun `weight slider sites opt in and rep slider sites do not`() { + val allSites = screenPaths.flatMap { path -> callBodies(source(path), "SliderWithButtons(") } + // Branch census at 4d4de558: 3 weight + 5 rep = 8 total (SD5/SD13). + assertEquals(8, allSites.size, "SliderWithButtons call-site census changed — re-census and update") + val weightSites = allSites.filter { body -> isWeightSite(body) } + val repSites = allSites.filter { body -> !isWeightSite(body) } + assertEquals(3, weightSites.size, "weight-site census changed — re-census and update") + assertEquals(5, repSites.size, "rep-site census changed — re-census and update") + + weightSites.forEach { body -> + assertContains(body, "isWeightValue = true", message = "weight site missing the SD5 opt-in: $body") + } + repSites.forEach { body -> + assertFalse(body.contains("isWeightValue"), "rep site must not receive the treatment: $body") + } + } + + @Test + fun `slider component keeps the explicit default and gates scaling on the opt-in`() { + val component = source(sliderComponentPath) + assertContains(component, "isWeightValue: Boolean = false") + assertContains(component, "if (isWeightValue)") + } + + @Test + fun `hud value branches are scaled while labels stay supporting text`() { + val hud = source(hudPath) + // Extract the HudBottomBar function source (signature + balanced brace body). + val marker = "private fun HudBottomBar(" + val start = hud.indexOf(marker) + assertTrue(start >= 0, marker) + val openParen = hud.indexOf('(', start) + var depth = 0 + var closeParen = -1 + for (index in openParen until hud.length) { + when (hud[index]) { + '(' -> depth += 1 + ')' -> { + depth -= 1 + if (depth == 0) { + closeParen = index + break + } + } + } + } + val openBody = hud.indexOf('{', closeParen) + var braceDepth = 0 + var closeBody = -1 + for (index in openBody until hud.length) { + when (hud[index]) { + '{' -> braceDepth += 1 + '}' -> { + braceDepth -= 1 + if (braceDepth == 0) { + closeBody = index + break + } + } + } + } + val bottomBar = hud.substring(start, closeBody + 1) + // Both value branches use the scaled value style (SD9). + assertEquals( + 2, + Regex("""style = valueStyle""").findAll(bottomBar).count(), + "both HUD value branches must use the scaled value style", + ) + assertTrue( + Regex(""""No machine load",\s*style = valueStyle""").containsMatchIn(bottomBar), + "bodyweight value branch must be scaled", + ) + assertTrue( + Regex("""formatWeight\(selectedDisplayKg, weightUnit\)\s*},\s*style = valueStyle""") + .containsMatchIn(bottomBar), + "numeric/Adaptive value branch must be scaled", + ) + // Supporting labels remain labelSmall (unscaled). + assertTrue( + bottomBar.contains("MaterialTheme.typography.labelSmall"), + "supporting labels must stay labelSmall", + ) + } + + @Test + fun `shouldStackWeightCards stays byte identical`() { + val window = source(windowSizeClassPath) + val expected = """ + fun shouldStackWeightCards( + windowSizeClass: WindowSizeClass, + ): Boolean = windowSizeClass.heightSizeClass == WindowHeightSizeClass.Compact + """.trimIndent() + assertContains(window, expected, message = "shouldStackWeightCards changed (SD4: iOS gesture-conflict guard)") + } + + @Test + fun `just lift and the native picker never see the weight text scale`() { + val justLift = source(justLiftPath) + assertFalse(justLift.contains("WeightTextScale"), "JustLiftScreen must be untouched (Option B)") + assertFalse(justLift.contains("scaledForWeightValue"), "JustLiftScreen must be untouched (Option B)") + assertFalse(justLift.contains("LocalWeightTextScale"), "JustLiftScreen must be untouched (Option B)") + } + + @Test + fun `presentation only invariant - no backup codec sync schema or tvos touches the key`() { + val forbiddenPaths = listOf( + "src/commonMain/kotlin/com/devil/phoenixproject/util/DataBackupManager.kt", + "src/commonMain/kotlin/com/devil/phoenixproject/util/BackupModels.kt", + "src/commonMain/kotlin/com/devil/phoenixproject/data/preferences/ProfilePreferencesCodec.kt", + ) + val forbiddenMarkers = listOf("weight_text_scale", "weightTextScale", "WeightTextScale") + forbiddenPaths.forEach { path -> + val text = source(path) + forbiddenMarkers.forEach { marker -> + assertFalse(text.contains(marker), "$path must not touch $marker (SD12/SD6)") + } + } + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/screen/ProfileSettingsSeparationContractTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/screen/ProfileSettingsSeparationContractTest.kt index 48b8ac77d..371d0e6da 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/screen/ProfileSettingsSeparationContractTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/screen/ProfileSettingsSeparationContractTest.kt @@ -181,6 +181,8 @@ class ProfileSettingsSeparationContractTest { onBackupDestinationChange: (BackupDestination) -> Unit, selectedLanguage: String, onLanguageChange: (String) -> Unit, + weightTextScale: WeightTextScale, + onWeightTextScaleChange: (WeightTextScale) -> Unit, modifier: Modifier = Modifier, ) """.trimIndent() @@ -293,6 +295,16 @@ class ProfileSettingsSeparationContractTest { } assertContains(settings, "private fun GlobalSettingsSectionCard(") + // Issue #1367 SD8: the Settings helper wording is a binding signoff correction and + // must ship verbatim in the default locale. + val weightTextStrings = source("src/commonMain/composeResources/values/strings.xml") + listOf( + "Enlarges weight values in Set Ready, Routine Overview, rest, exercise setup and workout readouts. Just Lift is unchanged in this first version. Saved on this device only.", + "Combines with your device text size, up to 2× the standard base size. Options may look the same at larger device text sizes. This limit also applies to Standard when your device text size exceeds it.", + ).forEach { wording -> + assertContains(weightTextStrings, wording, message = "SD8 verbatim helper copy missing") + } + assertContains(functionSource(settings, "WeightTextSizeSelector"), "Role.RadioButton") val switchRow = functionSource(settings, "GlobalSettingsSwitchRow") listOf("defaultMinSize(minHeight = 48.dp)", ".toggleable(", "role = Role.Switch") .forEach { contract -> assertContains(switchRow, contract) } @@ -366,6 +378,7 @@ class ProfileSettingsSeparationContractTest { "backupStats = backupStats", "backupDestination = globalSettings.backupDestination", "selectedLanguage = globalSettings.language", + "weightTextScale = globalSettings.weightTextScale", "connectionError = connectionError", ).forEach { assignment -> assertTrue( @@ -385,6 +398,7 @@ class ProfileSettingsSeparationContractTest { "onOpenBackupFolder" to "openBackupFolder", "onBackupDestinationChange" to "setBackupDestination", "onLanguageChange" to "setLanguage", + "onWeightTextScaleChange" to "setWeightTextScale", ).forEach { (parameter, method) -> assertViewModelCallback(call, parameter, method) } listOf( "onThemeModeChange = onThemeModeChange", @@ -432,6 +446,7 @@ class ProfileSettingsSeparationContractTest { listOf( "setEnableVideoPlayback", "setBleCompatibilityMode", + "setWeightTextScale", "setAutoBackupEnabled", "setBackupDestination", "setLanguage", @@ -459,6 +474,7 @@ class ProfileSettingsSeparationContractTest { includeRawTelemetryInBackups = includeRawTelemetryInBackups, backupDestination = backupDestination, language = language, + weightTextScale = weightTextScale, ) """.trimIndent() assertEquals(compactKotlin(expectedMapper), compactKotlin(mapper)) diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/util/WeightTextScalingTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/util/WeightTextScalingTest.kt new file mode 100644 index 000000000..783d5047b --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/util/WeightTextScalingTest.kt @@ -0,0 +1,170 @@ +package com.devil.phoenixproject.presentation.util + +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.unit.em +import androidx.compose.ui.unit.sp +import com.devil.phoenixproject.domain.model.WeightTextScale +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Issue #1367 T7-T10/T12/T18: the SD1 rendered-cap style helper. + * + * Contract under test: E = min(A*O, 2), M = E/O; the style scales fontSize AND explicit + * sp lineHeight by M (SD3), preserves other attributes, and leaves relative/unspecified + * line height untouched; E is clamped to (0, 2] and invalid inputs degrade to 1.0 (SD1); + * Large never renders smaller than Standard at the same device setting (SD2). + */ +class WeightTextScalingTest { + + private val tolerance = 0.0001f + + // ===== T7: style scaling ratios and attribute preservation ===== + + @Test + fun `fontSize scales by M at OS 1`() { + // A=1/1.5/2 at O=1 -> E=A, M=A + val base = TextStyle(fontSize = 20.sp) + assertEquals(20f, base.scaledForWeightValue(WeightTextScale.STANDARD, 1f).fontSize.value, tolerance) + assertEquals(30f, base.scaledForWeightValue(WeightTextScale.LARGE, 1f).fontSize.value, tolerance) + assertEquals(40f, base.scaledForWeightValue(WeightTextScale.EXTRA_LARGE, 1f).fontSize.value, tolerance) + } + + @Test + fun `fontSize multiplier M equals E divided by O`() { + // A=2, O=1.5 -> E=min(3, 2)=2, M=2/1.5 -> rendered = base*2 (capped), not base*3 + val base = TextStyle(fontSize = 10.sp) + val scaled = base.scaledForWeightValue(WeightTextScale.EXTRA_LARGE, 1.5f) + assertEquals(10f * (2f / 1.5f), scaled.fontSize.value, tolerance) + } + + @Test + fun `explicit sp line height scales with M per SD3`() { + val base = TextStyle(fontSize = 20.sp, lineHeight = 24.sp) + val scaled = base.scaledForWeightValue(WeightTextScale.LARGE, 1f) + assertEquals(24f * 1.5f, scaled.lineHeight.value, tolerance) + } + + @Test + fun `relative and unspecified line height stay untouched`() { + val unspecified = TextStyle(fontSize = 20.sp) + assertEquals( + unspecified.lineHeight, + unspecified.scaledForWeightValue(WeightTextScale.EXTRA_LARGE, 1f).lineHeight, + ) + val relative = TextStyle(fontSize = 20.sp, lineHeight = 1.2.em) + assertEquals( + relative.lineHeight, + relative.scaledForWeightValue(WeightTextScale.EXTRA_LARGE, 1f).lineHeight, + ) + } + + @Test + fun `result font size stays in sp`() { + val scaled = TextStyle(fontSize = 20.sp).scaledForWeightValue(WeightTextScale.LARGE, 1.25f) + assertTrue(scaled.fontSize.isSp) + } + + @Test + fun `non-font attributes are preserved`() { + val base = TextStyle(fontSize = 20.sp, letterSpacing = 0.5.sp) + val scaled = base.scaledForWeightValue(WeightTextScale.EXTRA_LARGE, 1f) + assertEquals(base.letterSpacing, scaled.letterSpacing) + assertEquals(base.fontWeight, scaled.fontWeight) + assertEquals(base.color, scaled.color) + assertEquals(base.fontFamily, scaled.fontFamily) + } + + // ===== T8: cap matrix ===== + + @Test + fun `effective scale caps at 2x`() { + assertEquals(2f, effectiveWeightTextScale(WeightTextScale.EXTRA_LARGE, 2.0f), tolerance) + assertEquals(2f, effectiveWeightTextScale(WeightTextScale.LARGE, 2.0f), tolerance) + assertEquals(2f, effectiveWeightTextScale(WeightTextScale.STANDARD, 2.5f), tolerance) + assertEquals(2f, effectiveWeightTextScale(WeightTextScale.EXTRA_LARGE, 3.0f), tolerance) + assertEquals(1.5f, effectiveWeightTextScale(WeightTextScale.LARGE, 1.0f), tolerance) + assertEquals(1f, effectiveWeightTextScale(WeightTextScale.STANDARD, 1.0f), tolerance) + } + + @Test + fun `single named cap constant`() { + assertEquals(2.0f, WEIGHT_TEXT_MAX_EFFECTIVE_SCALE) + } + + // ===== T9: Standard above-cap exception and Large >= Standard ===== + + @Test + fun `standard keeps M 1 through OS 2 and is bounded above the cap`() { + // O <= 2: M = 1 (base typography preserved) + assertEquals(1f, weightTextMultiplier(1f, 1.0f), tolerance) + assertEquals(1f, weightTextMultiplier(1f, 1.75f), tolerance) + assertEquals(1f, weightTextMultiplier(1f, 2.0f), tolerance) + // O > 2: E = 2, M = 2/O < 1 (intentionally bounded, SD2) + assertTrue(weightTextMultiplier(1f, 2.5f) < 1f) + assertEquals(2f / 2.5f, weightTextMultiplier(1f, 2.5f), tolerance) + } + + @Test + fun `large never renders smaller than standard at the same device setting`() { + val osScales = listOf(0.85f, 1f, 1.15f, 1.5f, 2f, 2.5f, 3f) + val base = TextStyle(fontSize = 16.sp) + for (os in osScales) { + val standard = base.scaledForWeightValue(WeightTextScale.STANDARD, os).fontSize.value * os + val large = base.scaledForWeightValue(WeightTextScale.LARGE, os).fontSize.value * os + val extraLarge = base.scaledForWeightValue(WeightTextScale.EXTRA_LARGE, os).fontSize.value * os + assertTrue(large >= standard - tolerance, "Large < Standard at OS $os") + assertTrue(extraLarge >= large - tolerance, "Extra large < Large at OS $os") + } + } + + @Test + fun `rendered size never exceeds 2x base for any combination`() { + val osScales = listOf(0.5f, 1f, 1.25f, 1.5f, 2f, 2.5f, 4f) + val base = TextStyle(fontSize = 28.sp) + for (scale in WeightTextScale.entries) { + for (os in osScales) { + // Rendered = style sp * OS scale in the linear model (SD1) + val rendered = base.scaledForWeightValue(scale, os).fontSize.value * os + assertTrue( + rendered <= 28f * WEIGHT_TEXT_MAX_EFFECTIVE_SCALE + tolerance, + "rendered ${rendered}sp exceeds cap for $scale at OS $os", + ) + } + } + } + + // ===== T10: invalid input guards ===== + + @Test + fun `invalid nonpositive and nonfinite inputs degrade to 1 and clamp E into the open-closed cap range`() { + val invalid = listOf(0f, -1f, -2.5f, Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) + for (bad in invalid) { + assertEquals(1f, effectiveWeightTextScale(bad, 1f), tolerance, "appFactor=$bad") + assertEquals(1f, effectiveWeightTextScale(1f, bad), tolerance, "osFontScale=$bad") + assertEquals(1f, weightTextMultiplier(bad, 1f), tolerance, "appFactor=$bad") + assertEquals(1f, weightTextMultiplier(1f, bad), tolerance, "osFontScale=$bad") + } + // Huge-but-finite factors overflow-proof: E clamps to the cap, never to infinity + assertEquals(2f, effectiveWeightTextScale(Float.MAX_VALUE, Float.MAX_VALUE)) + val e = effectiveWeightTextScale(1.5f, 1f) + assertTrue(e > 0f && e <= WEIGHT_TEXT_MAX_EFFECTIVE_SCALE) + } + + // ===== T18: WeightStepper value-row separation rule ===== + + @Test + fun `stepper value row separates only above E 1_5`() { + assertTrue(shouldSeparateWeightStepperValueRow(1.6f)) + assertTrue(shouldSeparateWeightStepperValueRow(2.0f)) + assertTrue(!shouldSeparateWeightStepperValueRow(1.5f)) + assertTrue(!shouldSeparateWeightStepperValueRow(1.0f)) + // invalid input degrades to 1.0 -> no separation + assertTrue(!shouldSeparateWeightStepperValueRow(Float.NaN)) + } + + // ===== T12: CompositionLocal safe default ===== + // (Asserted via a real composition in androidHostTest/LocalWeightTextScaleDefaultTest — + // CompositionLocal.current is @Composable and cannot be read from a plain unit test.) +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/util/WindowSizeClassTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/util/WindowSizeClassTest.kt index c7b945296..71d7a7156 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/util/WindowSizeClassTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/util/WindowSizeClassTest.kt @@ -115,6 +115,67 @@ class WindowSizeClassTest { ) } + // ========== Issue #1367 (T19): effective weight text scale pressure ========== + + @Test + fun compactWidthWithEffectiveWeightScaleUsesCompactAccessibilityLayout() { + // E = 2.0 at OS fontScale 1.0 (Extra large at default device text) must drive the + // compact layout even though the OS font scale alone would not (SD7). + val window = WindowSizeClass( + widthSizeClass = WindowWidthSizeClass.Compact, + heightSizeClass = WindowHeightSizeClass.Medium, + widthDp = 390.dp, + heightDp = 844.dp, + ) + + assertTrue( + shouldUseCompactAccessibilityLayout( + windowSizeClass = window, + fontScale = 1f, + boldTextEnabled = false, + effectiveWeightTextScale = 2.0f, + ), + ) + } + + @Test + fun effectiveWeightScaleOfOneKeepsExistingBehavior() { + val window = WindowSizeClass( + widthSizeClass = WindowWidthSizeClass.Compact, + heightSizeClass = WindowHeightSizeClass.Medium, + widthDp = 390.dp, + heightDp = 844.dp, + ) + + assertFalse( + shouldUseCompactAccessibilityLayout( + windowSizeClass = window, + fontScale = 1f, + boldTextEnabled = false, + effectiveWeightTextScale = 1.0f, + ), + ) + } + + @Test + fun widerLayoutsIgnoreEffectiveWeightScaleForCompactAccessibility() { + val window = WindowSizeClass( + widthSizeClass = WindowWidthSizeClass.Medium, + heightSizeClass = WindowHeightSizeClass.Medium, + widthDp = 700.dp, + heightDp = 844.dp, + ) + + assertFalse( + shouldUseCompactAccessibilityLayout( + windowSizeClass = window, + fontScale = 1f, + boldTextEnabled = false, + effectiveWeightTextScale = 2.0f, + ), + ) + } + // ========== Issue #571: shouldStackWeightCards ========== // // The helper is reduced to `heightSizeClass == Compact` (see WindowSizeClass.kt). The diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/testutil/FakePreferencesManager.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/testutil/FakePreferencesManager.kt index 4a38a9a1c..051264f90 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/testutil/FakePreferencesManager.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/testutil/FakePreferencesManager.kt @@ -147,6 +147,10 @@ class FakePreferencesManager : PreferencesManager { _preferencesFlow.value = _preferencesFlow.value.copy(bleCompatibilityMode = setting) } + override suspend fun setWeightTextScale(scale: com.devil.phoenixproject.domain.model.WeightTextScale) { + _preferencesFlow.value = _preferencesFlow.value.copy(weightTextScale = scale) + } + // Issue #611 (PR-followup #613): One-shot decline-remember backing field // for the 18+ Adults Only modal. Lives outside UserPreferences because the // modal-call site is the only consumer (architecture §3 — follow diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/SliderWithButtons.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/SliderWithButtons.kt index 9e80ffac9..dae599e36 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/SliderWithButtons.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/SliderWithButtons.kt @@ -22,8 +22,11 @@ import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import com.devil.phoenixproject.presentation.util.LocalWeightTextScale import com.devil.phoenixproject.presentation.util.LocalWindowSizeClass import com.devil.phoenixproject.presentation.util.WindowWidthSizeClass +import com.devil.phoenixproject.presentation.util.effectiveWeightTextScale +import com.devil.phoenixproject.presentation.util.scaledForWeightValue import com.devil.phoenixproject.ui.theme.Spacing import kotlin.math.roundToInt import org.jetbrains.compose.resources.stringResource @@ -47,6 +50,9 @@ fun SliderWithButtons( enabled: Boolean = true, deltaText: String? = null, isDeltaPositive: Boolean = true, + // Issue #1367 SD5: explicit weight-only opt-in. Weight selection sites pass true and + // get the weight-text-size treatment; rep/secondary sites stay byte-identical. + isWeightValue: Boolean = false, ) { // Calculate number of discrete steps for the slider // steps = number of intervals - 1 (excluding start and end) @@ -54,7 +60,21 @@ fun SliderWithButtons( val sliderSteps = ((range / step).roundToInt() - 1).coerceAtLeast(0) val windowSizeClass = LocalWindowSizeClass.current val fontScale = LocalDensity.current.fontScale - val shouldStackHeader = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact && fontScale >= 1.15f + // Issue #1367 SD1/SD7: the weight value text is scaled with the rendered-cap helper, + // and E (not A/M) drives header stacking at compact width even at OS fontScale 1.0. + val weightTextScale = LocalWeightTextScale.current + val valueStyle = if (isWeightValue) { + MaterialTheme.typography.titleMedium.scaledForWeightValue(weightTextScale, fontScale) + } else { + MaterialTheme.typography.titleMedium + } + val effectiveScale = if (isWeightValue) { + effectiveWeightTextScale(weightTextScale, fontScale) + } else { + 1.0f + } + val shouldStackHeader = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact && + (fontScale >= 1.15f || (isWeightValue && effectiveScale > 1.0f)) // KD-9: the range can be narrower than the incoming value (a stored 105 kg/cable set on a // 100 kg V-Form). Label what the slider actually represents, not the out-of-range value. val formattedValue = formatValue(value.coerceIn(valueRange)) @@ -78,7 +98,7 @@ fun SliderWithButtons( ) Text( text = formattedValue, - style = MaterialTheme.typography.titleMedium, + style = valueStyle, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary, ) @@ -101,7 +121,7 @@ fun SliderWithButtons( ) Text( text = formattedValue, - style = MaterialTheme.typography.titleMedium, + style = valueStyle, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary, maxLines = 1, diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/WeightStepper.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/WeightStepper.kt index 7e3544cf4..e016b2e3c 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/WeightStepper.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/WeightStepper.kt @@ -15,7 +15,11 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.devil.phoenixproject.domain.model.WeightUnit +import com.devil.phoenixproject.presentation.util.LocalWeightTextScale import com.devil.phoenixproject.presentation.util.WeightDisplayFormatter +import com.devil.phoenixproject.presentation.util.currentEffectiveWeightTextScale +import com.devil.phoenixproject.presentation.util.scaledForWeightValue +import com.devil.phoenixproject.presentation.util.shouldSeparateWeightStepperValueRow import com.devil.phoenixproject.ui.theme.Spacing import com.devil.phoenixproject.util.format import org.jetbrains.compose.resources.stringResource @@ -75,22 +79,34 @@ fun WeightStepper( Spacer(modifier = Modifier.height(Spacing.small)) - Row( - modifier = Modifier - .fillMaxWidth() - .background( - MaterialTheme.colorScheme.surfaceContainerLow, - MaterialTheme.shapes.medium, - ) - .border( - 1.dp, - MaterialTheme.colorScheme.outline.copy(alpha = 0.3f), - MaterialTheme.shapes.medium, - ) - .padding(Spacing.extraSmall), - verticalAlignment = Alignment.CenterVertically, - ) { - // Minus button + // Issue #1367 SD1/SD7/SD9: scale the numeric value only (unit label + total stay + // supporting text); when the effective rendered scale demands it (E > 1.5) the + // value moves to its own row and the +/- controls stay on one reachable row. + val weightTextScale = LocalWeightTextScale.current + val effectiveScale = currentEffectiveWeightTextScale(weightTextScale) + val separateValueRow = shouldSeparateWeightStepperValueRow(effectiveScale) + val valueStyle = MaterialTheme.typography.headlineMedium.scaledForWeightValue(weightTextScale) + + val valueText: @Composable () -> Unit = { + Text( + text = if (weight == weight.toLong().toFloat()) { + weight.toLong().toString() + } else { + weight.format(1) + }, + style = valueStyle, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface, + ) + } + val unitLabel: @Composable () -> Unit = { + Text( + text = stringResource(Res.string.weight_kg_per_cable), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + val minusButton: @Composable () -> Unit = { FilledTonalIconButton( onClick = { val newWeight = (weight - step).coerceAtLeast(minWeight) @@ -104,30 +120,8 @@ fun WeightStepper( contentDescription = stringResource(Res.string.cd_decrease_weight), ) } - - // Weight display - Column( - modifier = Modifier.weight(1f), - horizontalAlignment = Alignment.CenterHorizontally, - ) { - Text( - text = if (weight == weight.toLong().toFloat()) { - weight.toLong().toString() - } else { - weight.format(1) - }, - style = MaterialTheme.typography.headlineMedium, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - text = stringResource(Res.string.weight_kg_per_cable), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - - // Plus button + } + val plusButton: @Composable () -> Unit = { FilledTonalIconButton( onClick = { val newWeight = (weight + step).coerceAtMost(maxWeight) @@ -142,6 +136,59 @@ fun WeightStepper( ) } } + val containerModifier = Modifier + .fillMaxWidth() + .background( + MaterialTheme.colorScheme.surfaceContainerLow, + MaterialTheme.shapes.medium, + ) + .border( + 1.dp, + MaterialTheme.colorScheme.outline.copy(alpha = 0.3f), + MaterialTheme.shapes.medium, + ) + .padding(Spacing.extraSmall) + + if (separateValueRow) { + Column( + modifier = containerModifier, + verticalArrangement = Arrangement.spacedBy(Spacing.small), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + minusButton() + plusButton() + } + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + valueText() + unitLabel() + } + } + } else { + Row( + modifier = containerModifier, + verticalAlignment = Alignment.CenterVertically, + ) { + minusButton() + + // Weight display + Column( + modifier = Modifier.weight(1f), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + valueText() + unitLabel() + } + + plusButton() + } + } // Total weight for 2 cables indicator Spacer(modifier = Modifier.height(Spacing.small)) diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/navigation/NavGraph.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/navigation/NavGraph.kt index ed2269613..ff2ef23bc 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/navigation/NavGraph.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/navigation/NavGraph.kt @@ -496,6 +496,8 @@ fun NavGraph( onBackupDestinationChange = viewModel::setBackupDestination, selectedLanguage = globalSettings.language, onLanguageChange = viewModel::setLanguage, + weightTextScale = globalSettings.weightTextScale, + onWeightTextScaleChange = viewModel::setWeightTextScale, ) } diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/EnhancedMainScreen.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/EnhancedMainScreen.kt index 939cf2c82..dd9abdc06 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/EnhancedMainScreen.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/EnhancedMainScreen.kt @@ -101,6 +101,7 @@ import com.devil.phoenixproject.presentation.navigation.NavigationRoutes import com.devil.phoenixproject.presentation.theme.phoenixBottomNavigationContainerColor import com.devil.phoenixproject.presentation.theme.phoenixTopAppBarContainerColor import com.devil.phoenixproject.presentation.util.LocalPlatformAccessibilitySettings +import com.devil.phoenixproject.presentation.util.LocalWeightTextScale import com.devil.phoenixproject.presentation.util.LocalWindowSizeClass import com.devil.phoenixproject.presentation.util.WindowHeightSizeClass import com.devil.phoenixproject.presentation.util.calculateWindowSizeClass @@ -344,10 +345,15 @@ fun EnhancedMainScreen( BoxWithConstraints(modifier = Modifier.fillMaxSize()) { val windowSizeClass = calculateWindowSizeClass(maxWidth, maxHeight) val platformAccessibilitySettings = rememberPlatformAccessibilitySettings() + // Issue #1367: global device-local weight text size (SD6). globalSettings is + // initialized synchronously from the loaded preferences, so the saved choice is + // applied before first paint (SD10 — no Standard flash on cold start). + val globalSettings by viewModel.globalSettings.collectAsState() CompositionLocalProvider( LocalWindowSizeClass provides windowSizeClass, LocalPlatformAccessibilitySettings provides platformAccessibilitySettings, + LocalWeightTextScale provides globalSettings.weightTextScale, ) { val useCompactTopBar = isCompactAccessibilityLayout() || windowSizeClass.heightSizeClass == WindowHeightSizeClass.Compact diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/RestTimerCard.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/RestTimerCard.kt index 45c5cc95c..e2030a258 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/RestTimerCard.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/RestTimerCard.kt @@ -601,6 +601,7 @@ fun RestTimerCard( formatValue = { formatWeightWithUnit(it, weightUnit) }, deltaText = deltaText, isDeltaPositive = deltaKg >= 0f, + isWeightValue = true, ) } diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/RoutineOverviewScreen.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/RoutineOverviewScreen.kt index 9dee358b2..28d943ec6 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/RoutineOverviewScreen.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/RoutineOverviewScreen.kt @@ -86,10 +86,12 @@ import com.devil.phoenixproject.presentation.components.ExerciseDemoImage import com.devil.phoenixproject.presentation.navigation.NavigationRoutes import com.devil.phoenixproject.presentation.navigation.safePopOrNavigate import com.devil.phoenixproject.presentation.util.LocalPlatformAccessibilitySettings +import com.devil.phoenixproject.presentation.util.LocalWeightTextScale import com.devil.phoenixproject.presentation.util.LocalWindowSizeClass import com.devil.phoenixproject.presentation.util.TestTags import com.devil.phoenixproject.presentation.util.WindowHeightSizeClass import com.devil.phoenixproject.presentation.util.WindowWidthSizeClass +import com.devil.phoenixproject.presentation.util.effectiveWeightTextScale import com.devil.phoenixproject.presentation.viewmodel.MainViewModel import com.devil.phoenixproject.ui.theme.Spacing import com.devil.phoenixproject.ui.theme.labelAllCaps @@ -443,11 +445,16 @@ private fun routineOverviewSizing(): RoutineOverviewSizing { val windowSizeClass = LocalWindowSizeClass.current val fontScale = LocalDensity.current.fontScale val isCompactWidth = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact + // Issue #1367 SD7: the effective weight-text scale (E) participates in the + // reduced-viewport decision, so Large/Extra large trigger the compact card layout + // even at OS fontScale 1.0. E >= 1.15f subsumes the previous fontScale-only rule. + val effectiveWeightScale = effectiveWeightTextScale(LocalWeightTextScale.current, fontScale) val isReducedViewport = isCompactWidth && ( windowSizeClass.heightSizeClass == WindowHeightSizeClass.Compact || windowSizeClass.heightDp < 700.dp || - fontScale >= 1.15f + fontScale >= 1.15f || + effectiveWeightScale >= 1.15f ) return if (isReducedViewport) { @@ -761,6 +768,7 @@ private fun ExerciseOverviewCard( formatValue = { formatWeight(it, weightUnit) }, deltaText = deltaText, isDeltaPositive = deltaKg >= 0f, + isWeightValue = true, ) } } diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetReadyScreen.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetReadyScreen.kt index c282e81ae..b42ea9eb4 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetReadyScreen.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetReadyScreen.kt @@ -720,6 +720,7 @@ fun SetReadyScreen(navController: NavController, viewModel: MainViewModel, exerc formatValue = { viewModel.formatWeight(it, weightUnit) }, deltaText = deltaText, isDeltaPositive = deltaKg >= 0f, + isWeightValue = true, ) if (!isAMRAP) { diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SettingsTab.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SettingsTab.kt index 6dc34a938..39d1cc736 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SettingsTab.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SettingsTab.kt @@ -57,6 +57,7 @@ import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton import androidx.compose.material3.SegmentedButton import androidx.compose.material3.SegmentedButtonDefaults import androidx.compose.material3.SingleChoiceSegmentedButtonRow @@ -88,9 +89,13 @@ import com.devil.phoenixproject.data.repository.UserProfile import com.devil.phoenixproject.data.repository.UserProfileRepository import com.devil.phoenixproject.data.sync.SyncTriggerManager import com.devil.phoenixproject.domain.model.BleCompatibilitySetting +import com.devil.phoenixproject.domain.model.WeightTextScale import com.devil.phoenixproject.presentation.components.DestructiveConfirmDialog import com.devil.phoenixproject.presentation.components.HrmSensorSettingsCard import com.devil.phoenixproject.presentation.components.ProfileRecoverySettingsSection +import com.devil.phoenixproject.presentation.util.LocalWindowSizeClass +import com.devil.phoenixproject.presentation.util.WindowWidthSizeClass +import com.devil.phoenixproject.presentation.util.isCompactAccessibilityLayout import com.devil.phoenixproject.ui.theme.* import com.devil.phoenixproject.util.BackupDestination import com.devil.phoenixproject.util.BackupProgress @@ -174,6 +179,12 @@ import projectphoenix.shared.generated.resources.settings_theme_system import projectphoenix.shared.generated.resources.settings_title import projectphoenix.shared.generated.resources.settings_video_behavior import projectphoenix.shared.generated.resources.settings_version +import projectphoenix.shared.generated.resources.settings_weight_text_size +import projectphoenix.shared.generated.resources.settings_weight_text_size_extra_large +import projectphoenix.shared.generated.resources.settings_weight_text_size_help_1 +import projectphoenix.shared.generated.resources.settings_weight_text_size_help_2 +import projectphoenix.shared.generated.resources.settings_weight_text_size_large +import projectphoenix.shared.generated.resources.settings_weight_text_size_standard @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -219,6 +230,95 @@ private fun ThemeModeSelector( } } +/** + * Issue #1367 SD7/SD8: Weight text size selection (Standard / Large / Extra large). + * + * SD7: native selected-state radio rows (whole row selectable, >=48dp bounds, child + * radio with a null callback so the announcement is not duplicated) for compact-width + * and large-text layouts; a horizontal segmented selection only where the three labels + * fit without truncation. The SD8 help copy is two paragraphs and must never be clipped — + * it lives in the scrollable Settings column. + */ +@Composable +private fun WeightTextSizeSelector( + weightTextScale: WeightTextScale, + onWeightTextScaleChange: (WeightTextScale) -> Unit, +) { + val options = listOf( + WeightTextScale.STANDARD to stringResource(Res.string.settings_weight_text_size_standard), + WeightTextScale.LARGE to stringResource(Res.string.settings_weight_text_size_large), + WeightTextScale.EXTRA_LARGE to stringResource(Res.string.settings_weight_text_size_extra_large), + ) + val useRadioRows = isCompactAccessibilityLayout() || + LocalWindowSizeClass.current.widthSizeClass == WindowWidthSizeClass.Compact + + Column( + modifier = Modifier.fillMaxWidth(), + ) { + Text( + stringResource(Res.string.settings_weight_text_size), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.onSurface, + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + stringResource(Res.string.settings_weight_text_size_help_1), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + stringResource(Res.string.settings_weight_text_size_help_2), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(modifier = Modifier.height(Spacing.small)) + + if (useRadioRows) { + options.forEach { (option, label) -> + Row( + modifier = Modifier + .fillMaxWidth() + .defaultMinSize(minHeight = 48.dp) + .toggleable( + value = weightTextScale == option, + role = Role.RadioButton, + onValueChange = { onWeightTextScaleChange(option) }, + ) + .padding(horizontal = Spacing.small), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton( + selected = weightTextScale == option, + onClick = null, // selection is handled by the row (no duplicate announcement) + ) + Spacer(modifier = Modifier.width(Spacing.small)) + Text( + label, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface, + ) + } + } + } else { + SingleChoiceSegmentedButtonRow( + modifier = Modifier.fillMaxWidth(), + ) { + options.forEachIndexed { index, (option, label) -> + SegmentedButton( + selected = weightTextScale == option, + onClick = { onWeightTextScaleChange(option) }, + shape = SegmentedButtonDefaults.itemShape(index = index, count = options.size), + ) { + Text(label, maxLines = 1) + } + } + } + } + } +} + @Composable private fun GlobalSettingsSectionCard( title: String, @@ -306,6 +406,8 @@ fun SettingsTab( onBackupDestinationChange: (BackupDestination) -> Unit, selectedLanguage: String, onLanguageChange: (String) -> Unit, + weightTextScale: WeightTextScale, + onWeightTextScaleChange: (WeightTextScale) -> Unit, modifier: Modifier = Modifier, ) { var deleteAllTarget by remember { mutableStateOf(null) } @@ -605,6 +707,17 @@ fun SettingsTab( onThemeModeChange = onThemeModeChange, ) + HorizontalDivider( + modifier = Modifier.padding(vertical = Spacing.small), + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f), + ) + + // Issue #1367 SD8: Weight text size sits after Theme and before Dynamic color. + WeightTextSizeSelector( + weightTextScale = weightTextScale, + onWeightTextScaleChange = onWeightTextScaleChange, + ) + if (dynamicColorAvailable) { HorizontalDivider( modifier = Modifier.padding(vertical = Spacing.small), diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt index fcf8fdf8b..540af348a 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt @@ -34,12 +34,14 @@ import com.devil.phoenixproject.presentation.components.ExerciseDemoImage import com.devil.phoenixproject.presentation.components.ExpandedForceCurve import com.devil.phoenixproject.presentation.components.ForceCurveMiniGraph import com.devil.phoenixproject.presentation.components.StableRepProgress +import com.devil.phoenixproject.presentation.util.LocalWeightTextScale import com.devil.phoenixproject.presentation.util.LocalWindowSizeClass import com.devil.phoenixproject.presentation.util.ResponsiveDimensions import com.devil.phoenixproject.presentation.util.SetTypeLabel import com.devil.phoenixproject.presentation.util.WindowWidthSizeClass import com.devil.phoenixproject.presentation.util.formatRackItemLine import com.devil.phoenixproject.presentation.util.isCompactAccessibilityLayout +import com.devil.phoenixproject.presentation.util.scaledForWeightValue import com.devil.phoenixproject.presentation.util.setTypeLabel import com.devil.phoenixproject.ui.theme.AccessibilityTheme import com.devil.phoenixproject.ui.theme.velocityZoneColor @@ -376,6 +378,11 @@ private fun HudBottomBar( weightUnit = weightUnit, formatWeight = formatWeight, ) + // Issue #1367 SD9: both value-slot branches (numeric/"Adaptive" and bodyweight + // "No machine load") get the rendered-cap weight treatment; the supporting + // labelSmall labels ("Weight/cable"/"Bodyweight"/rack context) stay unscaled. + val weightTextScale = LocalWeightTextScale.current + val valueStyle = MaterialTheme.typography.titleLarge.scaledForWeightValue(weightTextScale) Column { if (isCurrentExerciseBodyweight) { Text( @@ -385,7 +392,7 @@ private fun HudBottomBar( ) Text( "No machine load", - style = MaterialTheme.typography.titleLarge, + style = valueStyle, fontWeight = FontWeight.Bold, ) } else { @@ -400,7 +407,7 @@ private fun HudBottomBar( } else { formatWeight(selectedDisplayKg, weightUnit) }, - style = MaterialTheme.typography.titleLarge, + style = valueStyle, fontWeight = FontWeight.Bold, ) } diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/util/LocalWeightTextScale.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/util/LocalWeightTextScale.kt new file mode 100644 index 000000000..8da49aa16 --- /dev/null +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/util/LocalWeightTextScale.kt @@ -0,0 +1,13 @@ +package com.devil.phoenixproject.presentation.util + +import androidx.compose.runtime.compositionLocalOf +import com.devil.phoenixproject.domain.model.WeightTextScale + +/** + * Issue #1367: ambient weight-text-size preference for the phone app. + * + * Provided once in `EnhancedMainScreen` from the global (device-local) preference. + * The safe default is [WeightTextScale.STANDARD], so previews, tests, and any + * composition outside the app shell render unchanged base typography. + */ +val LocalWeightTextScale = compositionLocalOf { WeightTextScale.STANDARD } diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/util/WeightTextScaling.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/util/WeightTextScaling.kt new file mode 100644 index 000000000..e8dc30a35 --- /dev/null +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/util/WeightTextScaling.kt @@ -0,0 +1,96 @@ +package com.devil.phoenixproject.presentation.util + +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.unit.TextUnit +import androidx.compose.ui.unit.sp +import com.devil.phoenixproject.domain.model.WeightTextScale + +/** + * Issue #1367 SD1 — rendered-cap weight text scaling. + * + * Contract (signoff correction 1): + * - app factor `A` = [WeightTextScale.preferenceFactor] (1 / 1.5 / 2) + * - OS font scale `O` = the platform font scale (`LocalDensity.current.fontScale`) + * - effective rendered scale `E = min(A * O, WEIGHT_TEXT_MAX_EFFECTIVE_SCALE)` + * - style multiplier `M = E / O` + * + * [scaledForWeightValue] multiplies the style's fontSize AND any explicit sp lineHeight + * by `M` (SD3: line height scales too). Compose then applies the OS scale exactly once, + * so the RENDERED size is `base * E` — physically capped at + * [WEIGHT_TEXT_MAX_EFFECTIVE_SCALE] x base. Every layout-pressure decision must use `E` + * (via [effectiveWeightTextScale]), never `M` and never `A` alone. + * + * SD2: Standard (A=1) keeps `M = 1` through `O <= 2` (base typography preserved). Above + * the cap (`O > 2`) Standard weight values are intentionally bounded at 2x base — they + * render smaller than unscaled base x O. Non-weight text still honors OS sizing. + * + * SD1 input guards: nonpositive / NaN / infinite factors or OS scales are treated as 1.0, + * and `E` is clamped into `(0, 2]`. + */ +const val WEIGHT_TEXT_MAX_EFFECTIVE_SCALE: Float = 2.0f + +private fun sanitizedScale(value: Float): Float = + if (value.isFinite() && value > 0f) value else 1f + +/** + * Effective (rendered) scale `E = min(A * O, cap)`, with invalid inputs treated as 1.0. + * Use for layout pressure: header stacking, value-row separation, viewport decisions. + */ +fun effectiveWeightTextScale(appFactor: Float, osFontScale: Float): Float { + val a = sanitizedScale(appFactor) + val o = sanitizedScale(osFontScale) + return (a * o).coerceAtMost(WEIGHT_TEXT_MAX_EFFECTIVE_SCALE) +} + +/** Enum-typed convenience overload of [effectiveWeightTextScale]. */ +fun effectiveWeightTextScale(scale: WeightTextScale, osFontScale: Float): Float = + effectiveWeightTextScale(scale.preferenceFactor, osFontScale) + +/** + * Style multiplier `M = E / O`. This is what multiplies the Compose style so the OS + * font scale is applied exactly once at render time (SD1). Never apply `A` directly. + */ +fun weightTextMultiplier(appFactor: Float, osFontScale: Float): Float { + val o = sanitizedScale(osFontScale) + return effectiveWeightTextScale(appFactor, osFontScale) / o +} + +private fun TextUnit.scaleBy(multiplier: Float): TextUnit = + if (isSp) (value * multiplier).sp else this + +/** + * Pure SD1 style helper: scales fontSize and explicit sp lineHeight by `M = E / O`, + * preserving every other style attribute. Relative/unspecified line heights are left + * untouched. The result stays in sp so Compose applies the OS scale exactly once. + */ +fun TextStyle.scaledForWeightValue(scale: WeightTextScale, osFontScale: Float): TextStyle { + val multiplier = weightTextMultiplier(scale.preferenceFactor, osFontScale) + return copy( + fontSize = fontSize.scaleBy(multiplier), + lineHeight = lineHeight.scaleBy(multiplier), + ) +} + +/** + * Thin composable wrapper: resolves the OS font scale from the ambient density. + */ +@Composable +fun TextStyle.scaledForWeightValue(scale: WeightTextScale): TextStyle = + scaledForWeightValue(scale, LocalDensity.current.fontScale) + +/** + * Composable `E` for layout decisions at the call boundary (SD1: `E`, not `M`). + */ +@Composable +fun currentEffectiveWeightTextScale(scale: WeightTextScale): Float = + effectiveWeightTextScale(scale, LocalDensity.current.fontScale) + +/** + * Issue #1367 SD7: the WeightStepper numeric value moves to its own row when the + * effective rendered scale demands it (`E > 1.5`); the +/- controls stay on one row. + * Pure for unit testing. + */ +fun shouldSeparateWeightStepperValueRow(effectiveScale: Float): Boolean = + sanitizedScale(effectiveScale) > 1.5f diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/util/WindowSizeClass.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/util/WindowSizeClass.kt index 8afb8d4c4..854e2acae 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/util/WindowSizeClass.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/util/WindowSizeClass.kt @@ -94,10 +94,17 @@ fun shouldUseCompactAccessibilityLayout( fontScale: Float, boldTextEnabled: Boolean, fontScaleThreshold: Float = 1.15f, + effectiveWeightTextScale: Float = 1.0f, ): Boolean = windowSizeClass.heightSizeClass == WindowHeightSizeClass.Compact || ( windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact && - (fontScale >= fontScaleThreshold || boldTextEnabled) + ( + fontScale >= fontScaleThreshold || + boldTextEnabled || + // Issue #1367 SD7: app weight-text pressure participates in the + // compact decision (stack at compact width when E > 1.0 even at OS 1.0). + effectiveWeightTextScale > 1.0f + ) ) /**