Modern Apps git

← Modern-Apps.git

weather: use units from device settings

Commit
3432fd05e252cf7a923dd1bdb66ae3235dac6ebd
Author
Vayun Mathur <[email protected]>
When
2026-05-30 15:42 UTC (6 months ago)
Parents
730f0f3

Diff

weather/src/main/java/com/vayunmathur/weather/MainActivity.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt b/weather/src/main/java/com/vayunmathur/weather/MainActivity.ktindex 800533d0f9..14f3829b71 100644--- a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt+++ b/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt@@ -8,7 +8,6 @@ import androidx.activity.viewModels import androidx.compose.runtime.Composable import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.DialogPage-import com.vayunmathur.library.util.ListDetailPage import com.vayunmathur.library.util.ListPage import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavKey@@ -17,7 +16,6 @@ import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.weather.data.WeatherDatabase import com.vayunmathur.weather.ui.HomePage import com.vayunmathur.weather.ui.SearchLocationPage-import com.vayunmathur.weather.ui.SettingsPage import com.vayunmathur.weather.util.WeatherViewModel import com.vayunmathur.weather.util.WeatherViewModelFactory import kotlinx.serialization.Serializable@@ -43,7 +41,6 @@ class MainActivity : ComponentActivity() { sealed interface Route : NavKey {     @Serializable data object Home : Route     @Serializable data object SearchLocation : Route-    @Serializable data object Settings : Route }  @Composable@@ -52,6 +49,5 @@ fun Navigation(viewModel: WeatherViewModel) {     MainNavigation(backStack) {         entry<Route.Home>(metadata = ListPage()) { HomePage(backStack, viewModel) }         entry<Route.SearchLocation>(metadata = DialogPage()) { SearchLocationPage(backStack, viewModel) }-        entry<Route.Settings>(metadata = ListDetailPage()) { SettingsPage(backStack, viewModel) }     } }
weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.ktindex 53f33f7bce..54195c5cdb 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt@@ -129,8 +129,8 @@ private fun LocationPage(     paddingValues: androidx.compose.foundation.layout.PaddingValues, ) {     val forecasts by viewModel.forecasts.collectAsState()-    val tempUnit by viewModel.tempUnit.collectAsState()-    val windUnit by viewModel.windUnit.collectAsState()+    val tempUnit = com.vayunmathur.weather.util.rememberTempUnit()+    val windUnit = com.vayunmathur.weather.util.rememberWindUnit()      LaunchedEffect(location.id) { viewModel.ensureForecast(location) } @@ -143,7 +143,6 @@ private fun LocationPage(             paddingValues = paddingValues,             drawerState = drawerState,             activeLocation = location,-            backStack = backStack,         )          if (forecast == null) {
weather/src/main/java/com/vayunmathur/weather/ui/SettingsPage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/SettingsPage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/SettingsPage.ktdeleted file mode 100644index 0da9792f86..0000000000--- a/weather/src/main/java/com/vayunmathur/weather/ui/SettingsPage.kt+++ /dev/null@@ -1,84 +0,0 @@-package com.vayunmathur.weather.ui--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.material3.ExperimentalMaterial3Api-import androidx.compose.material3.FilterChip-import androidx.compose.material3.MaterialTheme-import androidx.compose.material3.Scaffold-import androidx.compose.material3.Text-import androidx.compose.material3.TopAppBar-import androidx.compose.runtime.Composable-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.text.font.FontWeight-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.IconNavigation-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.weather.Route-import com.vayunmathur.weather.util.TemperatureUnit-import com.vayunmathur.weather.util.WeatherViewModel-import com.vayunmathur.weather.util.WindUnit--@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun SettingsPage(backStack: NavBackStack<Route>, viewModel: WeatherViewModel) {-    val tempUnit by viewModel.tempUnit.collectAsState()-    val windUnit by viewModel.windUnit.collectAsState()--    Scaffold(-        topBar = {-            TopAppBar(-                title = { Text("Settings") },-                navigationIcon = { IconNavigation(backStack) },-            )-        },-    ) { padding ->-        Column(-            modifier = Modifier.fillMaxSize().padding(padding).padding(16.dp),-            verticalArrangement = Arrangement.spacedBy(12.dp),-        ) {-            Text(-                "Temperature",-                style = MaterialTheme.typography.titleSmall,-                fontWeight = FontWeight.SemiBold,-            )-            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {-                FilterChip(-                    selected = tempUnit == TemperatureUnit.Celsius,-                    onClick = { viewModel.setTempUnit(TemperatureUnit.Celsius) },-                    label = { Text("°C") },-                )-                FilterChip(-                    selected = tempUnit == TemperatureUnit.Fahrenheit,-                    onClick = { viewModel.setTempUnit(TemperatureUnit.Fahrenheit) },-                    label = { Text("°F") },-                )-            }--            Text(-                "Wind",-                style = MaterialTheme.typography.titleSmall,-                fontWeight = FontWeight.SemiBold,-                modifier = Modifier.padding(top = 16.dp),-            )-            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {-                FilterChip(-                    selected = windUnit == WindUnit.KmH,-                    onClick = { viewModel.setWindUnit(WindUnit.KmH) },-                    label = { Text("km/h") },-                )-                FilterChip(-                    selected = windUnit == WindUnit.Mph,-                    onClick = { viewModel.setWindUnit(WindUnit.Mph) },-                    label = { Text("mph") },-                )-            }-        }-    }-}
weather/src/main/java/com/vayunmathur/weather/ui/components/MainSearchBar.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/MainSearchBar.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/MainSearchBar.ktindex aba06ecfa3..7b6c039a0d 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/MainSearchBar.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/MainSearchBar.kt@@ -24,18 +24,13 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.library.R as LibraryR-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.weather.R-import com.vayunmathur.weather.Route import com.vayunmathur.weather.data.SavedLocation import kotlinx.coroutines.launch  /**- * Direct port of WeatherMaster's `MainSearchBar` — a 56 dp `CircleShape`- * pill `Surface` with a hamburger icon, the active location's name in the- * middle, and a settings icon at the right. The whole surface is also- * clickable to toggle the drawer (matching WeatherMaster's- * tap-anywhere-to-open behavior).+ * 56 dp `CircleShape` pill `Surface` with a hamburger icon on the left and+ * the active location name centered. The whole surface is also clickable+ * to toggle the drawer.  */ @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -43,7 +38,6 @@ fun MainSearchBar(     paddingValues: PaddingValues,     drawerState: DrawerState,     activeLocation: SavedLocation?,-    backStack: NavBackStack<Route>, ) {     val scope = rememberCoroutineScope()     val toggleDrawer = {@@ -98,13 +92,6 @@ fun MainSearchBar(                 overflow = TextOverflow.Ellipsis,             )             Spacer(Modifier.width(4.dp))-            IconButton(onClick = { backStack.add(Route.Settings) }) {-                Icon(-                    painter = painterResource(LibraryR.drawable.settings_24px),-                    contentDescription = "Settings",-                    tint = MaterialTheme.colorScheme.onSurfaceVariant,-                )-            }         }     } }
weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlocks.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlocks.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlocks.ktindex e308827d8b..9afb7a40f4 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlocks.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlocks.kt@@ -54,7 +54,7 @@ fun WeatherBlocks(         item { UvIndexBlock(uvIndex = today?.uvIndexMax?.firstOrNull()) }         item { WindBlock(current = current, unit = windUnit) }         item { PressureBlock(current = current) }-        item { VisibilityBlock(current = current) }+        item { VisibilityBlock(current = current, useMiles = windUnit == WindUnit.Mph) }         item { SunBlock(sunriseEpochSec = sunriseEpochSec, sunsetEpochSec = sunsetEpochSec) }         item { AirQualityBlock(air = air) }         item { PollenBlock(air = air) }
weather/src/main/java/com/vayunmathur/weather/util/SystemUnits.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/util/SystemUnits.kt b/weather/src/main/java/com/vayunmathur/weather/util/SystemUnits.ktnew file mode 100644index 0000000000..29f6ef3d01--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/util/SystemUnits.kt@@ -0,0 +1,56 @@+package com.vayunmathur.weather.util++import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalConfiguration+import androidx.core.text.util.LocalePreferences+import java.util.Locale++/**+ * Resolve the display units from the device's regional preferences (set+ * via Android 14's *Settings → System → Languages → Regional preferences*,+ * and inferred from the active locale on earlier versions). Reading via+ * Compose's `LocalConfiguration` ensures we re-resolve on configuration+ * changes when the user flips a setting at runtime.+ *+ * Temperature comes from [LocalePreferences.getTemperatureUnit].+ *+ * Wind speed (and any other distance-based units) comes from the+ * **measurement system** preference, which Android writes to the active+ * locale as the Unicode extension `-u-ms-{metric|ussystem|uksystem}`. We+ * read it directly via [Locale.getUnicodeLocaleType] since the androidx+ * helper doesn't expose it yet — falling back to the locale's country code+ * (US/LR/MM → US system) for devices where the extension is absent.+ */+@Composable+fun rememberTempUnit(): TemperatureUnit {+    LocalConfiguration.current+    return remember(LocalConfiguration.current) {+        when (LocalePreferences.getTemperatureUnit()) {+            LocalePreferences.TemperatureUnit.FAHRENHEIT -> TemperatureUnit.Fahrenheit+            else -> TemperatureUnit.Celsius+        }+    }+}++@Composable+fun rememberWindUnit(): WindUnit {+    LocalConfiguration.current+    return remember(LocalConfiguration.current) {+        if (isImperialMeasurementSystem(Locale.getDefault())) WindUnit.Mph else WindUnit.KmH+    }+}++/**+ * True when the locale opts into a non-metric measurement system, either+ * via the explicit `-u-ms-…` Unicode extension that Android 14's regional+ * preference sets, or by virtue of being one of the three remaining+ * predominantly-imperial country codes.+ */+private fun isImperialMeasurementSystem(locale: Locale): Boolean {+    val extension = locale.getUnicodeLocaleType("ms")+    if (extension != null) {+        return extension == "ussystem" || extension == "uksystem"+    }+    return locale.country in setOf("US", "LR", "MM")+}
weather/src/main/java/com/vayunmathur/weather/util/UnitsPrefs.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/util/UnitsPrefs.kt b/weather/src/main/java/com/vayunmathur/weather/util/UnitsPrefs.ktdeleted file mode 100644index 03e61d54c2..0000000000--- a/weather/src/main/java/com/vayunmathur/weather/util/UnitsPrefs.kt+++ /dev/null@@ -1,36 +0,0 @@-package com.vayunmathur.weather.util--import android.content.Context-import androidx.datastore.preferences.core.booleanPreferencesKey-import androidx.datastore.preferences.core.edit-import androidx.datastore.preferences.preferencesDataStore-import kotlinx.coroutines.flow.Flow-import kotlinx.coroutines.flow.map--private val Context.unitsDataStore by preferencesDataStore(name = "weather_units")-private val KEY_FAHRENHEIT = booleanPreferencesKey("use_fahrenheit")-private val KEY_MPH = booleanPreferencesKey("use_mph")--/**- * User-selected display units. Defaults follow Pixel Weather: °F + mph in the- * US, °C + km/h elsewhere — approximated here as "default to metric" since we- * don't want to introduce locale-detection logic on the hot path.- */-class UnitsPrefs(private val context: Context) {--    val tempUnit: Flow<TemperatureUnit> = context.unitsDataStore.data.map {-        if (it[KEY_FAHRENHEIT] == true) TemperatureUnit.Fahrenheit else TemperatureUnit.Celsius-    }--    val windUnit: Flow<WindUnit> = context.unitsDataStore.data.map {-        if (it[KEY_MPH] == true) WindUnit.Mph else WindUnit.KmH-    }--    suspend fun setTempUnit(unit: TemperatureUnit) {-        context.unitsDataStore.edit { it[KEY_FAHRENHEIT] = (unit == TemperatureUnit.Fahrenheit) }-    }--    suspend fun setWindUnit(unit: WindUnit) {-        context.unitsDataStore.edit { it[KEY_MPH] = (unit == WindUnit.Mph) }-    }-}
weather/src/main/java/com/vayunmathur/weather/util/WeatherViewModel.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/util/WeatherViewModel.kt b/weather/src/main/java/com/vayunmathur/weather/util/WeatherViewModel.ktindex c5210eb4fd..9a7b890d3c 100644--- a/weather/src/main/java/com/vayunmathur/weather/util/WeatherViewModel.kt+++ b/weather/src/main/java/com/vayunmathur/weather/util/WeatherViewModel.kt@@ -42,15 +42,8 @@ class WeatherViewModel(     private val dao: WeatherDao, ) : AndroidViewModel(application) { -    private val prefs = UnitsPrefs(application)     private val json = Json { ignoreUnknownKeys = true } -    val tempUnit: StateFlow<TemperatureUnit> = prefs.tempUnit-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), TemperatureUnit.Celsius)--    val windUnit: StateFlow<WindUnit> = prefs.windUnit-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), WindUnit.KmH)-     val savedLocations: StateFlow<List<SavedLocation>> = dao.observeLocations()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) @@ -58,14 +51,6 @@ class WeatherViewModel(     private val _forecasts = MutableStateFlow<Map<Long, ForecastUiState>>(emptyMap())     val forecasts: StateFlow<Map<Long, ForecastUiState>> = _forecasts.asStateFlow() -    fun setTempUnit(unit: TemperatureUnit) {-        viewModelScope.launch { prefs.setTempUnit(unit) }-    }--    fun setWindUnit(unit: WindUnit) {-        viewModelScope.launch { prefs.setWindUnit(unit) }-    }-     /**      * Ensure there's a forecast for [location] — hydrate from the on-disk      * cache first so the UI gets something immediately, then kick off a