Modern Apps git

← Modern-Apps.git

weather: new app

Commit
eb627c2179c965f41d4f10ac110c52e70d09b1cb
Author
Vayun Mathur <[email protected]>
When
2026-05-30 04:23 UTC (6 months ago)
Parents
4ea7842

Diff

gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 1112634d6f..4d0f2ea9d3 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -57,6 +57,7 @@ libphonenumber = "9.0.30" material3AdaptiveNavigationSuite = "1.4.0" maplibre = "0.13.0" foundation = "1.11.2"+materialkolor = "4.1.1"  [libraries] # AndroidX Core & Lifecycle@@ -155,6 +156,7 @@ kotlin-serialization-gradle = { module = "org.jetbrains.kotlin:kotlin-serializat sqlcipher-android = { module = "net.zetetic:sqlcipher-android", version.ref = "sqlcipherAndroid" } symbol-processing-gradle-plugin = { module = "com.google.devtools.ksp:symbol-processing-gradle-plugin", version.ref = "ksp" } androidx-compose-foundation = { group = "androidx.compose.foundation", name = "foundation", version.ref = "foundation" }+materialkolor = { module = "com.materialkolor:material-kolor", version.ref = "materialkolor" }  [plugins] android-application = { id = "com.android.application", version.ref = "agp" }
library/src/main/java/com/vayunmathur/library/intents/weather/WeatherData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/weather/WeatherData.kt b/library/src/main/java/com/vayunmathur/library/intents/weather/WeatherData.ktnew file mode 100644index 0000000000..19c044af9d--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/weather/WeatherData.kt@@ -0,0 +1,36 @@+package com.vayunmathur.library.intents.weather++import kotlinx.serialization.Serializable++/**+ * Cross-app weather payload returned by the Weather app's+ * `GetWeatherIntent` and `GetWeatherByNameIntent` activities to anything that+ * launches them via `IntentLauncher` — currently OpenAssistant's `get_weather`+ * / `get_weather_by_name` tools.+ *+ * All temperatures are in Celsius, all wind speeds in km/h. The receiving+ * caller (typically the LLM via `toString()`) is responsible for any unit+ * conversion shown to the user. Sunrise/sunset are epoch seconds in UTC, so+ * the caller renders them in whichever timezone is appropriate.+ *+ * [error] is non-null only when the lookup failed (e.g. city not found, no+ * network). The other numeric fields will be at their defaults in that case;+ * callers should check [error] first.+ */+@Serializable+data class WeatherData(+    val locationName: String?,+    val temperatureCelsius: Double,+    val feelsLikeCelsius: Double,+    val condition: String,+    val highCelsius: Double,+    val lowCelsius: Double,+    val precipitationChancePercent: Int,+    val humidityPercent: Int,+    val windKph: Double,+    val windDirection: String,+    val uvIndex: Double,+    val sunriseEpochSec: Long? = null,+    val sunsetEpochSec: Long? = null,+    val error: String? = null,+)
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.ktindex c559c77100..1e761cef44 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt@@ -14,6 +14,7 @@ import com.vayunmathur.library.intents.contacts.ContactData import com.vayunmathur.library.intents.findfamily.FamilyMemberData import com.vayunmathur.library.intents.music.MusicSearchResult import com.vayunmathur.library.intents.music.PlayMusicData+import com.vayunmathur.library.intents.weather.WeatherData import com.vayunmathur.openassistant.MainActivity import com.vayunmathur.library.intents.notes.NoteData import com.vayunmathur.openassistant.data.Memory@@ -202,6 +203,7 @@ class AssistantToolSet(                 "com.vayunmathur.calendar" -> "Calendar"                 "com.vayunmathur.findfamily" -> "FindFamily"                 "com.vayunmathur.music" -> "Music"+                "com.vayunmathur.weather" -> "Weather"                 else -> packageName             }             return "The $appName app is required but not installed. [Download from GitHub](https://github.com/vayun-mathur/Modern-Apps)."@@ -409,8 +411,33 @@ class AssistantToolSet(         return "Conversation title set successfully"     } -    @Tool(description = "Get weather")-    fun get_weather(latitude: Double, longitude: Double): String = "Weather: 22°C, Sunny."+    @Tool(description = "Get the current weather conditions at a specific latitude/longitude. Returns temperature, feels-like, condition, hi/lo, humidity, wind, UV, sunrise and sunset.")+    fun get_weather(latitude: Double, longitude: Double): String = runBlocking {+        try {+            val result: WeatherData = launchIntent(+                context,+                "com.vayunmathur.weather",+                "com.vayunmathur.weather.intents.GetWeatherIntent",+                WeatherLatLonRequest(latitude, longitude)+            )+            result.error ?: result.toString()+        } catch (e: MissingAppException) { handleMissingApp(e.packageName) }+        catch (e: Exception) { "Error: ${e.message}" }+    }++    @Tool(description = "Get the current weather conditions for a named place (city, address, landmark). Prefer this over get_weather when the user says a place name instead of coordinates.")+    fun get_weather_by_name(@ToolParam(description = "city or place name") location: String): String = runBlocking {+        try {+            val result: WeatherData = launchIntent(+                context,+                "com.vayunmathur.weather",+                "com.vayunmathur.weather.intents.GetWeatherByNameIntent",+                WeatherNameRequest(location)+            )+            result.error ?: result.toString()+        } catch (e: MissingAppException) { handleMissingApp(e.packageName) }+        catch (e: Exception) { "Error: ${e.message}" }+    }      @Tool(description = "Get a list of all memories")     fun get_memories(): String = runBlocking {@@ -443,6 +470,18 @@ class AssistantToolSet( class MissingAppException(val packageName: String) : Exception("App $packageName is not installed.") class StopInferenceException : Exception("STOP") +/**+ * Mirror of the input payload that [GetWeatherIntent] in the Weather app+ * expects. kotlinx.serialization is structural, so JSON written from here+ * deserializes into the other side as long as field names + types match.+ */[email protected]+data class WeatherLatLonRequest(val latitude: Double, val longitude: Double)++/** Mirror of the [GetWeatherByNameIntent] input. */[email protected]+data class WeatherNameRequest(val name: String)+ inline fun <reified Input : Any, reified Output : Any> launchIntent(     context: Context,     packageName: String,
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 0434956bfb..c952d66c73 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -48,3 +48,5 @@ include(":music") include(":clock") include(":games:alchemist") include(":email")+include(":weather")+include(":messages")
weather/build.gradle.kts
diff --git a/weather/build.gradle.kts b/weather/build.gradle.ktsnew file mode 100644index 0000000000..2333939afe--- /dev/null+++ b/weather/build.gradle.kts@@ -0,0 +1,18 @@+plugins {+    id("common-conventions-app")+    alias(libs.plugins.ksp)+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.weather"+    }+}++dependencies {+    implementation(project(":library:network"))+    implementation(libs.androidx.datastore.preferences)+    implementation(libs.materialkolor)+    implementation(libs.reorderable)+    implementRoom(libs)+}
weather/src/main/AndroidManifest.xml
diff --git a/weather/src/main/AndroidManifest.xml b/weather/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..5c3de700d9--- /dev/null+++ b/weather/src/main/AndroidManifest.xml@@ -0,0 +1,37 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:name=".MainActivity"+            android:exported="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>++        <activity+            android:name=".intents.GetWeatherIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay" />++        <activity+            android:name=".intents.GetWeatherByNameIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay" />+    </application>+</manifest>
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.ktnew file mode 100644index 0000000000..5d56ae978b--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt@@ -0,0 +1,59 @@+package com.vayunmathur.weather++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.library.util.ListDetailPage+import com.vayunmathur.library.util.ListPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.buildDatabase+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.weather.data.WeatherDatabase+import com.vayunmathur.weather.ui.AddLocationPage+import com.vayunmathur.weather.ui.HomePage+import com.vayunmathur.weather.ui.LocationListPage+import com.vayunmathur.weather.ui.SettingsPage+import com.vayunmathur.weather.ui.WeatherTheme+import com.vayunmathur.weather.util.WeatherViewModel+import com.vayunmathur.weather.util.WeatherViewModelFactory+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+    private val db by lazy { buildDatabase<WeatherDatabase>(dbName = "weather-db") }+    private val viewModel: WeatherViewModel by viewModels {+        WeatherViewModelFactory(application, db.weatherDao())+    }++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            WeatherTheme {+                Navigation(viewModel)+            }+        }+    }+}++@Serializable+sealed interface Route : NavKey {+    @Serializable data object Home : Route+    @Serializable data object Locations : Route+    @Serializable data object AddLocation : Route+    @Serializable data object Settings : Route+}++@Composable+fun Navigation(viewModel: WeatherViewModel) {+    val backStack = rememberNavBackStack<Route>(Route.Home)+    MainNavigation(backStack) {+        entry<Route.Home>(metadata = ListPage()) { HomePage(backStack, viewModel) }+        entry<Route.Locations>(metadata = ListPage()) { LocationListPage(backStack, viewModel) }+        entry<Route.AddLocation>(metadata = ListDetailPage()) { AddLocationPage(backStack, viewModel) }+        entry<Route.Settings>(metadata = ListDetailPage()) { SettingsPage(backStack, viewModel) }+    }+}
weather/src/main/java/com/vayunmathur/weather/data/SavedLocation.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/data/SavedLocation.kt b/weather/src/main/java/com/vayunmathur/weather/data/SavedLocation.ktnew file mode 100644index 0000000000..9ae5f3baec--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/data/SavedLocation.kt@@ -0,0 +1,24 @@+package com.vayunmathur.weather.data++import androidx.room.Entity+import androidx.room.PrimaryKey++/**+ * A place the user has pinned in the weather app — either added by city+ * search ([isCurrent] = false) or auto-tracked from the device location+ * ([isCurrent] = true, single-row constraint enforced at the DAO level).+ *+ * [latitude] / [longitude] are what the Open-Meteo forecast endpoint accepts+ * directly. [name] / [country] are what the UI shows; for the current-device+ * row [name] is left blank until reverse geocoding fills it in.+ */+@Entity+data class SavedLocation(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    val name: String,+    val country: String = "",+    val latitude: Double,+    val longitude: Double,+    val displayOrder: Int = 0,+    val isCurrent: Boolean = false,+)
weather/src/main/java/com/vayunmathur/weather/data/WeatherCache.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/data/WeatherCache.kt b/weather/src/main/java/com/vayunmathur/weather/data/WeatherCache.ktnew file mode 100644index 0000000000..4804965336--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/data/WeatherCache.kt@@ -0,0 +1,19 @@+package com.vayunmathur.weather.data++import androidx.room.Entity++/**+ * Most-recent forecast JSON for a (lat, lon) point. Lets the home pager+ * render instantly while a refresh runs in the background, and lets the+ * OpenAssistant intent return the cached value when the network is down.+ *+ * Coordinates are rounded to 4 decimals (≈11 m) before insertion so we don't+ * cache 1000 near-identical rows for tiny GPS jitter.+ */+@Entity(primaryKeys = ["latRounded", "lonRounded"])+data class WeatherCache(+    val latRounded: Double,+    val lonRounded: Double,+    val forecastJson: String,+    val fetchedAtEpochMs: Long,+)
weather/src/main/java/com/vayunmathur/weather/data/WeatherDao.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/data/WeatherDao.kt b/weather/src/main/java/com/vayunmathur/weather/data/WeatherDao.ktnew file mode 100644index 0000000000..2a32d61260--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/data/WeatherDao.kt@@ -0,0 +1,58 @@+package com.vayunmathur.weather.data++import androidx.room.Dao+import androidx.room.Delete+import androidx.room.Insert+import androidx.room.OnConflictStrategy+import androidx.room.Query+import androidx.room.Upsert+import kotlinx.coroutines.flow.Flow++@Dao+interface WeatherDao {++    // ---- SavedLocation ----++    @Query("SELECT * FROM SavedLocation ORDER BY displayOrder ASC, id ASC")+    fun observeLocations(): Flow<List<SavedLocation>>++    @Query("SELECT * FROM SavedLocation ORDER BY displayOrder ASC, id ASC")+    suspend fun getLocations(): List<SavedLocation>++    @Query("SELECT * FROM SavedLocation WHERE id = :id LIMIT 1")+    suspend fun getLocationById(id: Long): SavedLocation?++    @Query("SELECT * FROM SavedLocation WHERE isCurrent = 1 LIMIT 1")+    suspend fun getCurrentDeviceLocation(): SavedLocation?++    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun insertLocation(location: SavedLocation): Long++    @Upsert+    suspend fun upsertLocation(location: SavedLocation)++    @Delete+    suspend fun deleteLocation(location: SavedLocation)++    @Query("UPDATE SavedLocation SET displayOrder = :order WHERE id = :id")+    suspend fun setOrder(id: Long, order: Int)++    /**+     * Replaces the existing "current device" row (if any) with [newRow] in a+     * single transaction. Used by the location provider when it gets a fresh+     * GPS fix.+     */+    @androidx.room.Transaction+    suspend fun replaceCurrentDeviceLocation(newRow: SavedLocation) {+        getCurrentDeviceLocation()?.let { deleteLocation(it) }+        insertLocation(newRow.copy(isCurrent = true))+    }++    // ---- WeatherCache ----++    @Upsert+    suspend fun upsertCache(cache: WeatherCache)++    @Query("SELECT * FROM WeatherCache WHERE latRounded = :lat AND lonRounded = :lon LIMIT 1")+    suspend fun getCache(lat: Double, lon: Double): WeatherCache?+}
weather/src/main/java/com/vayunmathur/weather/data/WeatherDatabase.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/data/WeatherDatabase.kt b/weather/src/main/java/com/vayunmathur/weather/data/WeatherDatabase.ktnew file mode 100644index 0000000000..56f3a00716--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/data/WeatherDatabase.kt@@ -0,0 +1,13 @@+package com.vayunmathur.weather.data++import androidx.room.Database+import androidx.room.RoomDatabase++@Database(+    entities = [SavedLocation::class, WeatherCache::class],+    version = 1,+    exportSchema = true,+)+abstract class WeatherDatabase : RoomDatabase() {+    abstract fun weatherDao(): WeatherDao+}
weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherByNameIntent.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherByNameIntent.kt b/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherByNameIntent.ktnew file mode 100644index 0000000000..f86599ea72--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherByNameIntent.kt@@ -0,0 +1,64 @@+package com.vayunmathur.weather.intents++import com.vayunmathur.library.intents.weather.WeatherData+import com.vayunmathur.library.util.AssistantIntent+import com.vayunmathur.weather.network.WeatherApi+import kotlinx.serialization.InternalSerializationApi+import kotlinx.serialization.Serializable+import kotlinx.serialization.serializer++/** Input payload for [GetWeatherByNameIntent]: a free-form city/place name. */+@Serializable+data class LocationQueryInput(val name: String)++/**+ * "Headless" activity launched by OpenAssistant's `get_weather_by_name`+ * tool. Resolves [LocationQueryInput.name] via Open-Meteo's geocoding API,+ * then fetches a forecast for the first match. Returns [WeatherData] with+ * `error` set if no place matched or the network call failed.+ */+@OptIn(InternalSerializationApi::class)+class GetWeatherByNameIntent : AssistantIntent<LocationQueryInput, WeatherData>(+    inputSerializer = serializer<LocationQueryInput>(),+    outputSerializer = serializer<WeatherData>(),+) {+    override suspend fun performCalculation(input: LocationQueryInput): WeatherData {+        return try {+            val matches = WeatherApi.geocode(input.name, limit = 1).results+            val place = matches.firstOrNull() ?: return WeatherData(+                locationName = input.name,+                temperatureCelsius = 0.0,+                feelsLikeCelsius = 0.0,+                condition = "",+                highCelsius = 0.0,+                lowCelsius = 0.0,+                precipitationChancePercent = 0,+                humidityPercent = 0,+                windKph = 0.0,+                windDirection = "",+                uvIndex = 0.0,+                error = "No location matched '${input.name}'",+            )+            val forecast = WeatherApi.forecast(place.latitude, place.longitude)+            val label = listOfNotNull(place.name, place.country)+                .filter { it.isNotBlank() }+                .joinToString(", ")+            forecast.toWeatherData(locationName = label.ifBlank { place.name })+        } catch (e: Exception) {+            WeatherData(+                locationName = input.name,+                temperatureCelsius = 0.0,+                feelsLikeCelsius = 0.0,+                condition = "",+                highCelsius = 0.0,+                lowCelsius = 0.0,+                precipitationChancePercent = 0,+                humidityPercent = 0,+                windKph = 0.0,+                windDirection = "",+                uvIndex = 0.0,+                error = e.message ?: "Failed to fetch forecast",+            )+        }+    }+}
weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherIntent.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherIntent.kt b/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherIntent.ktnew file mode 100644index 0000000000..760159b762--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherIntent.kt@@ -0,0 +1,101 @@+package com.vayunmathur.weather.intents++import com.vayunmathur.library.intents.weather.WeatherData+import com.vayunmathur.library.util.AssistantIntent+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.WeatherApi+import com.vayunmathur.weather.util.compassDirection+import com.vayunmathur.weather.util.weatherConditionForCode+import kotlinx.serialization.InternalSerializationApi+import kotlinx.serialization.Serializable+import kotlinx.serialization.serializer+import kotlin.time.Instant++/** Input payload for [GetWeatherIntent]: a single coordinate pair. */+@Serializable+data class LatLonInput(val latitude: Double, val longitude: Double)++/**+ * "Headless" activity launched by OpenAssistant's `get_weather` tool. Fetches+ * a fresh forecast from Open-Meteo for the supplied lat/lon and returns it as+ * a [WeatherData] payload. No UI — the activity finishes immediately as+ * dictated by the [AssistantIntent] base class.+ */+@OptIn(InternalSerializationApi::class)+class GetWeatherIntent : AssistantIntent<LatLonInput, WeatherData>(+    inputSerializer = serializer<LatLonInput>(),+    outputSerializer = serializer<WeatherData>(),+) {+    override suspend fun performCalculation(input: LatLonInput): WeatherData {+        return try {+            val forecast = WeatherApi.forecast(input.latitude, input.longitude)+            forecast.toWeatherData(locationName = null)+        } catch (e: Exception) {+            WeatherData(+                locationName = null,+                temperatureCelsius = 0.0,+                feelsLikeCelsius = 0.0,+                condition = "",+                highCelsius = 0.0,+                lowCelsius = 0.0,+                precipitationChancePercent = 0,+                humidityPercent = 0,+                windKph = 0.0,+                windDirection = "",+                uvIndex = 0.0,+                error = e.message ?: "Failed to fetch forecast",+            )+        }+    }+}++/**+ * Open-Meteo returns sunrise/sunset as local-time ISO strings with no offset+ * (`2024-05-30T05:42`). Combine with `utc_offset_seconds` from the response+ * to get a real epoch.+ */+internal fun parseLocalIsoToEpochSec(iso: String, utcOffsetSec: Int): Long? {+    val padded = if (iso.length == 16) "$iso:00" else iso+    return runCatching { Instant.parse("${padded}Z").epochSeconds - utcOffsetSec }.getOrNull()+}++/** Distill a full [ForecastResponse] into the cross-app [WeatherData] payload. */+internal fun ForecastResponse.toWeatherData(locationName: String?): WeatherData {+    val current = current ?: return WeatherData(+        locationName = locationName,+        temperatureCelsius = 0.0,+        feelsLikeCelsius = 0.0,+        condition = "",+        highCelsius = 0.0,+        lowCelsius = 0.0,+        precipitationChancePercent = 0,+        humidityPercent = 0,+        windKph = 0.0,+        windDirection = "",+        uvIndex = 0.0,+        error = "No current observations available",+    )+    val condition = weatherConditionForCode(current.weatherCode).label+    val hi = daily?.temperatureMax?.firstOrNull() ?: current.temperature+    val lo = daily?.temperatureMin?.firstOrNull() ?: current.temperature+    val precip = daily?.precipitationProbabilityMax?.firstOrNull() ?: 0+    val uv = daily?.uvIndexMax?.firstOrNull() ?: 0.0+    val sunrise = daily?.sunrise?.firstOrNull()?.let { parseLocalIsoToEpochSec(it, utcOffsetSeconds) }+    val sunset = daily?.sunset?.firstOrNull()?.let { parseLocalIsoToEpochSec(it, utcOffsetSeconds) }++    return WeatherData(+        locationName = locationName,+        temperatureCelsius = current.temperature,+        feelsLikeCelsius = current.apparentTemperature,+        condition = condition,+        highCelsius = hi,+        lowCelsius = lo,+        precipitationChancePercent = precip,+        humidityPercent = current.relativeHumidity,+        windKph = current.windSpeed,+        windDirection = compassDirection(current.windDirection),+        uvIndex = uv,+        sunriseEpochSec = sunrise,+        sunsetEpochSec = sunset,+    )+}
weather/src/main/java/com/vayunmathur/weather/network/AirQualityDto.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/AirQualityDto.kt b/weather/src/main/java/com/vayunmathur/weather/network/AirQualityDto.ktnew file mode 100644index 0000000000..dd6bd8adc7--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/network/AirQualityDto.kt@@ -0,0 +1,29 @@+package com.vayunmathur.weather.network++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Subset of Open-Meteo's `/v1/air-quality` response we use. Endpoint:+ * https://air-quality-api.open-meteo.com/v1/air-quality+ *+ * Provides US AQI (0..500 with 0..50 = good, 51..100 = moderate, …) plus+ * tree/grass/weed/ragweed/birch/olive/mugwort/alder pollen concentrations+ * (grains/m³). We collapse pollens into the standard three "categories"+ * for display: grass, tree (= max of tree species), weed (= max of weed+ * species). Open-Meteo returns nulls outside coverage areas.+ */+@Serializable+data class AirQualityResponse(val current: AirQualityCurrent? = null)++@Serializable+data class AirQualityCurrent(+    val time: String,+    @SerialName("us_aqi") val usAqi: Int? = null,+    @SerialName("alder_pollen") val alderPollen: Double? = null,+    @SerialName("birch_pollen") val birchPollen: Double? = null,+    @SerialName("grass_pollen") val grassPollen: Double? = null,+    @SerialName("mugwort_pollen") val mugwortPollen: Double? = null,+    @SerialName("olive_pollen") val olivePollen: Double? = null,+    @SerialName("ragweed_pollen") val ragweedPollen: Double? = null,+)
weather/src/main/java/com/vayunmathur/weather/network/GeocodingDto.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/GeocodingDto.kt b/weather/src/main/java/com/vayunmathur/weather/network/GeocodingDto.ktnew file mode 100644index 0000000000..3dd7b87ef6--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/network/GeocodingDto.kt@@ -0,0 +1,23 @@+package com.vayunmathur.weather.network++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Open-Meteo geocoding API response for `/v1/search?name=...`.+ * Endpoint: https://geocoding-api.open-meteo.com/v1/search+ */+@Serializable+data class GeocodingResponse(val results: List<GeocodingResult> = emptyList())++@Serializable+data class GeocodingResult(+    val id: Long,+    val name: String,+    val latitude: Double,+    val longitude: Double,+    val country: String? = null,+    @SerialName("country_code") val countryCode: String? = null,+    @SerialName("admin1") val admin1: String? = null,+    val timezone: String? = null,+)
weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt b/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.ktnew file mode 100644index 0000000000..f17bbe811a--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt@@ -0,0 +1,60 @@+package com.vayunmathur.weather.network++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Subset of the Open-Meteo `/v1/forecast` response we actually use.+ * Endpoint: https://api.open-meteo.com/v1/forecast+ *+ * We always request: current weather + hourly arrays + daily arrays in metric+ * units. Unit conversion for the UI happens at display time so swapping+ * Settings doesn't require a re-fetch.+ */+@Serializable+data class ForecastResponse(+    val latitude: Double,+    val longitude: Double,+    val timezone: String? = null,+    @SerialName("timezone_abbreviation") val timezoneAbbreviation: String? = null,+    @SerialName("utc_offset_seconds") val utcOffsetSeconds: Int = 0,+    val current: Current? = null,+    val hourly: Hourly? = null,+    val daily: Daily? = null,+)++@Serializable+data class Current(+    val time: String,+    @SerialName("temperature_2m") val temperature: Double,+    @SerialName("apparent_temperature") val apparentTemperature: Double,+    @SerialName("relative_humidity_2m") val relativeHumidity: Int,+    @SerialName("dew_point_2m") val dewPoint: Double = 0.0,+    @SerialName("weather_code") val weatherCode: Int,+    @SerialName("wind_speed_10m") val windSpeed: Double,+    @SerialName("wind_direction_10m") val windDirection: Int,+    @SerialName("pressure_msl") val pressureMsl: Double = 0.0,+    @SerialName("visibility") val visibility: Double = 0.0,+    @SerialName("is_day") val isDay: Int = 1,+)++@Serializable+data class Hourly(+    val time: List<String> = emptyList(),+    @SerialName("temperature_2m") val temperature: List<Double> = emptyList(),+    @SerialName("weather_code") val weatherCode: List<Int> = emptyList(),+    @SerialName("precipitation_probability") val precipitationProbability: List<Int> = emptyList(),+    @SerialName("is_day") val isDay: List<Int> = emptyList(),+)++@Serializable+data class Daily(+    val time: List<String> = emptyList(),+    @SerialName("weather_code") val weatherCode: List<Int> = emptyList(),+    @SerialName("temperature_2m_max") val temperatureMax: List<Double> = emptyList(),+    @SerialName("temperature_2m_min") val temperatureMin: List<Double> = emptyList(),+    @SerialName("sunrise") val sunrise: List<String> = emptyList(),+    @SerialName("sunset") val sunset: List<String> = emptyList(),+    @SerialName("uv_index_max") val uvIndexMax: List<Double> = emptyList(),+    @SerialName("precipitation_probability_max") val precipitationProbabilityMax: List<Int> = emptyList(),+)
weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt b/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.ktnew file mode 100644index 0000000000..555bb15a61--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt@@ -0,0 +1,110 @@+package com.vayunmathur.weather.network++import com.vayunmathur.library.network.NetworkClient++/**+ * Thin wrapper over the shared [NetworkClient] for the two Open-Meteo+ * endpoints we use. Open-Meteo requires no API key and returns JSON, so this+ * is just URL construction + delegation to the existing Ktor client.+ *+ * Everything is requested in metric units; the UI converts at display time so+ * toggling °C/°F doesn't trigger another HTTP call.+ */+object WeatherApi {++    private const val FORECAST_BASE = "https://api.open-meteo.com/v1/forecast"+    private const val GEOCODE_BASE = "https://geocoding-api.open-meteo.com/v1/search"+    private const val AIR_QUALITY_BASE = "https://air-quality-api.open-meteo.com/v1/air-quality"++    /**+     * Fetch the current conditions + 24h hourly + 7-day daily forecast for a+     * single coordinate. Throws on network / parse failure — callers wrap in+     * try/catch and fall back to cache.+     */+    suspend fun forecast(latitude: Double, longitude: Double): ForecastResponse {+        val url = buildString {+            append(FORECAST_BASE)+            append("?latitude=").append(latitude)+            append("&longitude=").append(longitude)+            append("&current=").append(+                listOf(+                    "temperature_2m",+                    "apparent_temperature",+                    "relative_humidity_2m",+                    "dew_point_2m",+                    "weather_code",+                    "wind_speed_10m",+                    "wind_direction_10m",+                    "pressure_msl",+                    "visibility",+                    "is_day",+                ).joinToString(",")+            )+            append("&hourly=").append(+                listOf(+                    "temperature_2m",+                    "weather_code",+                    "precipitation_probability",+                    "is_day",+                ).joinToString(",")+            )+            append("&daily=").append(+                listOf(+                    "weather_code",+                    "temperature_2m_max",+                    "temperature_2m_min",+                    "sunrise",+                    "sunset",+                    "uv_index_max",+                    "precipitation_probability_max",+                ).joinToString(",")+            )+            append("&timezone=auto")+            append("&forecast_days=7")+        }+        return NetworkClient.getJson(url)+    }++    /**+     * Look up up to [limit] places that match the user-typed [query]. Used by+     * the in-app city search and by the OpenAssistant+     * `get_weather_by_name` intent.+     */+    suspend fun geocode(query: String, limit: Int = 5): GeocodingResponse {+        if (query.isBlank()) return GeocodingResponse(emptyList())+        val url = buildString {+            append(GEOCODE_BASE)+            append("?name=").append(java.net.URLEncoder.encode(query, "UTF-8"))+            append("&count=").append(limit)+            append("&format=json")+            append("&language=en")+        }+        return NetworkClient.getJson(url)+    }++    /**+     * Air quality + pollen for a coordinate. Best-effort: the air-quality+     * service has gaps outside Europe/North America, so callers should treat+     * the whole response as optional.+     */+    suspend fun airQuality(latitude: Double, longitude: Double): AirQualityResponse {+        val url = buildString {+            append(AIR_QUALITY_BASE)+            append("?latitude=").append(latitude)+            append("&longitude=").append(longitude)+            append("&current=").append(+                listOf(+                    "us_aqi",+                    "alder_pollen",+                    "birch_pollen",+                    "grass_pollen",+                    "mugwort_pollen",+                    "olive_pollen",+                    "ragweed_pollen",+                ).joinToString(",")+            )+            append("&timezone=auto")+        }+        return NetworkClient.getJson(url)+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/AddLocationPage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/AddLocationPage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/AddLocationPage.ktnew file mode 100644index 0000000000..707d47517d--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/AddLocationPage.kt@@ -0,0 +1,187 @@+package com.vayunmathur.weather.ui++import android.Manifest+import android.widget.Toast+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material3.Button+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.ListItem+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.snapshotFlow+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.weather.Route+import com.vayunmathur.weather.network.GeocodingResult+import com.vayunmathur.weather.network.WeatherApi+import com.vayunmathur.weather.util.LocationProvider+import com.vayunmathur.weather.util.WeatherViewModel+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.debounce+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.flatMapLatest+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.launch++/** Search by city name OR pull from the device's current location. */+@OptIn(ExperimentalMaterial3Api::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class,+    kotlinx.coroutines.FlowPreview::class)+@Composable+fun AddLocationPage(backStack: NavBackStack<Route>, viewModel: WeatherViewModel) {+    val context = LocalContext.current+    val scope = rememberCoroutineScope()++    var query by remember { mutableStateOf("") }+    var results by remember { mutableStateOf<List<GeocodingResult>>(emptyList()) }+    var searching by remember { mutableStateOf(false) }++    LaunchedEffect(Unit) {+        snapshotFlow { query }+            .debounce(300)+            .distinctUntilChanged()+            .flatMapLatest { q ->+                flow {+                    if (q.isBlank()) {+                        emit(emptyList<GeocodingResult>())+                    } else {+                        searching = true+                        val res = runCatching { WeatherApi.geocode(q).results }.getOrDefault(emptyList())+                        searching = false+                        emit(res)+                    }+                }+            }+            .collect { results = it }+    }++    val permissionLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.RequestMultiplePermissions()+    ) { granted ->+        if (granted.values.any { it }) {+            scope.launch { useCurrentLocation(context, viewModel, backStack) }+        } else {+            Toast.makeText(context, "Location permission denied", Toast.LENGTH_SHORT).show()+        }+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text("Add location") },+                navigationIcon = { IconNavigation(backStack) },+            )+        },+    ) { padding ->+        Column(modifier = Modifier.fillMaxSize().padding(padding)) {+            Button(+                onClick = {+                    if (LocationProvider.hasPermission(context)) {+                        scope.launch { useCurrentLocation(context, viewModel, backStack) }+                    } else {+                        permissionLauncher.launch(+                            arrayOf(+                                Manifest.permission.ACCESS_FINE_LOCATION,+                                Manifest.permission.ACCESS_COARSE_LOCATION,+                            )+                        )+                    }+                },+                modifier = Modifier.fillMaxWidth().padding(16.dp),+            ) { Text("Use current location") }++            HorizontalDivider()++            CommonSearchBar(+                value = query,+                onValueChange = { query = it },+                placeholder = "Search city",+            )++            Box(modifier = Modifier.fillMaxSize()) {+                if (searching && results.isEmpty()) {+                    CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))+                } else if (query.isNotBlank() && results.isEmpty()) {+                    Text(+                        "No matches",+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                        modifier = Modifier.align(Alignment.Center),+                    )+                } else {+                    LazyColumn(modifier = Modifier.fillMaxSize()) {+                        items(results, key = { it.id }) { r ->+                            ListItem(+                                headlineContent = { Text(r.name) },+                                supportingContent = {+                                    val parts = listOfNotNull(r.admin1, r.country).filter { it.isNotBlank() }+                                    if (parts.isNotEmpty()) Text(parts.joinToString(", "))+                                },+                                modifier = Modifier.clickable {+                                    viewModel.addLocation(+                                        name = r.name,+                                        country = r.country.orEmpty(),+                                        latitude = r.latitude,+                                        longitude = r.longitude,+                                    )+                                    backStack.pop()+                                },+                            )+                        }+                    }+                }+            }+        }+    }+}++private suspend fun useCurrentLocation(+    context: android.content.Context,+    viewModel: WeatherViewModel,+    backStack: NavBackStack<Route>,+) {+    val loc = LocationProvider.currentLocation(context)+    if (loc == null) {+        Toast.makeText(context, "Couldn't determine location", Toast.LENGTH_SHORT).show()+        return+    }+    // Best-effort name via reverse geocoding via Open-Meteo (matches the nearest place).+    val name = runCatching {+        WeatherApi.geocode(+            // Approximate reverse: search for the lat,lon string isn't supported by /search.+            // Just use a placeholder; the user can rename later. We'll fill from any nearby+            // result if the user has typed something previously — but for "use current+            // location" the simplest UX is a fixed label.+            query = "",+        ).results.firstOrNull()?.name+    }.getOrNull() ?: "Current location"+    viewModel.setCurrentLocation(name = name, latitude = loc.latitude, longitude = loc.longitude)+    backStack.pop()+}
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.ktnew file mode 100644index 0000000000..ffec520342--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt@@ -0,0 +1,217 @@+package com.vayunmathur.weather.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+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.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.pager.HorizontalPager+import androidx.compose.foundation.pager.rememberPagerState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Button+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.weather.Route+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.ui.components.CurrentHero+import com.vayunmathur.weather.ui.components.DailyList+import com.vayunmathur.weather.ui.components.HourlyStrip+import com.vayunmathur.weather.ui.components.PrecipChart+import com.vayunmathur.weather.ui.components.SunriseSunsetCard+import com.vayunmathur.weather.ui.components.WeatherBlocksGrid+import com.vayunmathur.weather.util.WeatherViewModel+import kotlin.time.Instant++/**+ * Pixel-Weather-inspired home page rendered against the standard Material+ * surface (no condition tinting). Layout follows the Health app's rhythm:+ *   - Top app bar with the location name centered+ *   - Hero block (no card) with the current temp + condition + Hi/Lo pill+ *   - A stack of sectioned cards: HOURLY → DETAILS → PRECIPITATION → SUN → 7-DAY+ *+ * Horizontal pager swipes between saved locations; small dot indicators in+ * the top app bar show which page you're on.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun HomePage(backStack: NavBackStack<Route>, viewModel: WeatherViewModel) {+    val locations by viewModel.savedLocations.collectAsState()++    if (locations.isEmpty()) {+        EmptyHome(onAddLocation = { backStack.add(Route.AddLocation) })+        return+    }++    val pagerState = rememberPagerState(initialPage = 0) { locations.size }+    val current = locations.getOrNull(pagerState.currentPage)++    Scaffold(+        topBar = {+            TopAppBar(+                title = {+                    Column(horizontalAlignment = Alignment.CenterHorizontally) {+                        Text(+                            text = current?.name.orEmpty(),+                            style = MaterialTheme.typography.titleLarge,+                            fontWeight = FontWeight.SemiBold,+                        )+                        if (locations.size > 1) {+                            Row(+                                horizontalArrangement = Arrangement.spacedBy(6.dp),+                                verticalAlignment = Alignment.CenterVertically,+                                modifier = Modifier.padding(top = 4.dp),+                            ) {+                                LocationDots(locations.size, pagerState.currentPage)+                            }+                        }+                    }+                },+                actions = {+                    IconButton(onClick = { backStack.add(Route.Locations) }) { IconAdd() }+                    IconButton(onClick = { backStack.add(Route.Settings) }) { IconSettings() }+                },+            )+        },+    ) { padding ->+        HorizontalPager(+            state = pagerState,+            modifier = Modifier.fillMaxSize().padding(padding),+        ) { pageIndex ->+            LocationPage(viewModel = viewModel, location = locations[pageIndex])+        }+    }+}++@Composable+private fun LocationDots(count: Int, selectedIndex: Int) {+    Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {+        repeat(count) { i ->+            val selected = i == selectedIndex+            Surface(+                modifier = Modifier+                    .size(if (selected) 7.dp else 5.dp)+                    .clip(CircleShape),+                color = if (selected) MaterialTheme.colorScheme.onSurface+                else MaterialTheme.colorScheme.outlineVariant,+                content = {},+            )+        }+    }+}++@Composable+private fun LocationPage(viewModel: WeatherViewModel, location: SavedLocation) {+    val forecasts by viewModel.forecasts.collectAsState()+    val tempUnit by viewModel.tempUnit.collectAsState()+    val windUnit by viewModel.windUnit.collectAsState()++    LaunchedEffect(location.id) { viewModel.ensureForecast(location) }++    val state = forecasts[location.id]+    val forecast = state?.forecast++    if (forecast == null) {+        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+            if (state?.error != null) {+                Text(state.error, color = MaterialTheme.colorScheme.error)+            } else {+                CircularProgressIndicator()+            }+        }+        return+    }++    val current = forecast.current+    val daily = forecast.daily+    val sunriseEpoch = daily?.sunrise?.firstOrNull()?.let { parseLocalIsoToEpochSec(it, forecast.utcOffsetSeconds) }+    val sunsetEpoch = daily?.sunset?.firstOrNull()?.let { parseLocalIsoToEpochSec(it, forecast.utcOffsetSeconds) }++    LazyColumn(+        modifier = Modifier.fillMaxSize(),+        contentPadding = PaddingValues(bottom = 24.dp, top = 8.dp),+        verticalArrangement = Arrangement.spacedBy(12.dp),+    ) {+        if (current != null) {+            item { CurrentHero(location, current, daily, tempUnit) }+        }+        if (forecast.hourly != null) {+            item { HourlyStrip(forecast.hourly, tempUnit) }+        }+        if (current != null) {+            item {+                WeatherBlocksGrid(+                    current = current,+                    today = daily,+                    air = state.airQuality?.current,+                    sunriseEpochSec = sunriseEpoch,+                    sunsetEpochSec = sunsetEpoch,+                    tempUnit = tempUnit,+                    windUnit = windUnit,+                    viewModel = viewModel,+                )+            }+        }+        if (forecast.hourly != null) {+            item { PrecipChart(forecast.hourly) }+        }+        if (daily != null) {+            item { DailyList(daily, tempUnit) }+        }+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun EmptyHome(onAddLocation: () -> Unit) {+    Scaffold(+        topBar = { TopAppBar(title = { Text("Weather") }) },+    ) { padding ->+        Box(modifier = Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {+            Column(horizontalAlignment = Alignment.CenterHorizontally) {+                Text("No locations yet", style = MaterialTheme.typography.titleMedium)+                Text(+                    "Add a city or use your current location to see the forecast.",+                    style = MaterialTheme.typography.bodyMedium,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                    modifier = Modifier.padding(horizontal = 32.dp, vertical = 8.dp),+                )+                Button(onClick = onAddLocation) { Text("Add a location") }+            }+        }+    }+}++/**+ * Open-Meteo returns ISO local-time strings (no offset) when timezone=auto is+ * requested. Combine with the response's `utc_offset_seconds` to produce an+ * actual epoch.+ */+private fun parseLocalIsoToEpochSec(iso: String, utcOffsetSec: Int): Long? {+    val padded = if (iso.length == 16) "$iso:00" else iso+    return runCatching {+        Instant.parse("${padded}Z").epochSeconds - utcOffsetSec+    }.getOrNull()+}
weather/src/main/java/com/vayunmathur/weather/ui/LocationListPage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/LocationListPage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/LocationListPage.ktnew file mode 100644index 0000000000..7b4d447f0c--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/LocationListPage.kt@@ -0,0 +1,228 @@+package com.vayunmathur.weather.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.FloatingActionButton+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.weather.R+import com.vayunmathur.weather.Route+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.util.TemperatureUnit+import com.vayunmathur.weather.util.WeatherViewModel+import com.vayunmathur.weather.util.formatTemperatureCompact+import com.vayunmathur.weather.util.weatherConditionForCode++/**+ * Manage saved locations — pill-shaped cards mirroring the Pixel Weather+ * screen. Current device row gets a "Current location" section header with+ * a target icon; user-added rows go under "Saved locations" with a pin icon.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun LocationListPage(backStack: NavBackStack<Route>, viewModel: WeatherViewModel) {+    val locations by viewModel.savedLocations.collectAsState()+    val (currentDevice, saved) = locations.partition { it.isCurrent }++    LaunchedEffect(locations) {+        locations.forEach { viewModel.ensureForecast(it) }+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text("Weather") },+                navigationIcon = { IconNavigation(backStack) },+            )+        },+        floatingActionButton = {+            FloatingActionButton(+                onClick = { backStack.add(Route.AddLocation) },+                containerColor = MaterialTheme.colorScheme.primaryContainer,+                contentColor = MaterialTheme.colorScheme.onPrimaryContainer,+                shape = RoundedCornerShape(20.dp),+            ) { IconAdd() }+        },+    ) { padding ->+        if (locations.isEmpty()) {+            Box(modifier = Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {+                Text(+                    "No locations yet. Tap + to add one.",+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }+            return@Scaffold+        }+        LazyColumn(+            modifier = Modifier.fillMaxSize().padding(padding),+            contentPadding = PaddingValues(vertical = 8.dp),+            verticalArrangement = Arrangement.spacedBy(8.dp),+        ) {+            if (currentDevice.isNotEmpty()) {+                item {+                    SmallSectionLabel(+                        text = "Current location",+                        iconRes = R.drawable.outline_my_location_24,+                    )+                }+                items(currentDevice, key = { it.id }) { loc ->+                    LocationPillCard(loc, viewModel) { viewModel.deleteLocation(loc) }+                }+            }+            if (saved.isNotEmpty()) {+                item {+                    SmallSectionLabel(+                        text = "Saved locations",+                        iconRes = R.drawable.outline_location_on_24,+                    )+                }+                items(saved, key = { it.id }) { loc ->+                    LocationPillCard(loc, viewModel) { viewModel.deleteLocation(loc) }+                }+            }+        }+    }+}++@Composable+private fun SmallSectionLabel(text: String, iconRes: Int) {+    Row(+        modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 4.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        Icon(+            painter = painterResource(iconRes),+            contentDescription = null,+            modifier = Modifier.size(16.dp),+            tint = MaterialTheme.colorScheme.onSurfaceVariant,+        )+        Spacer(Modifier.width(8.dp))+        Text(+            text,+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+    }+}++/**+ * Pill-shaped card with a circular condition glyph, location name, condition+ * + hi/lo subtitle, and big temperature on the right. Long-press could+ * delete; for v1 we just expose a trailing delete button.+ */+@Composable+private fun LocationPillCard(+    location: SavedLocation,+    viewModel: WeatherViewModel,+    onDelete: () -> Unit,+) {+    val forecasts by viewModel.forecasts.collectAsState()+    val tempUnit by viewModel.tempUnit.collectAsState()+    val state = forecasts[location.id]+    val current = state?.forecast?.current+    val daily = state?.forecast?.daily+    val condition = current?.weatherCode?.let { weatherConditionForCode(it) }++    Surface(+        modifier = Modifier+            .fillMaxWidth()+            .padding(horizontal = 16.dp)+            .clip(RoundedCornerShape(28.dp))+            .clickable { /* tap → could navigate to that page; for now just no-op */ },+        shape = RoundedCornerShape(28.dp),+        color = MaterialTheme.colorScheme.surfaceContainer,+    ) {+        Row(+            modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 10.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            Box(+                modifier = Modifier+                    .size(48.dp)+                    .clip(CircleShape)+                    .background(MaterialTheme.colorScheme.onSurface.copy(alpha = 0.10f)),+                contentAlignment = Alignment.Center,+            ) {+                if (condition != null) {+                    Icon(+                        painter = painterResource(condition.iconRes(current?.isDay == 1)),+                        contentDescription = condition.label,+                        modifier = Modifier.size(24.dp),+                        tint = MaterialTheme.colorScheme.onSurface,+                    )+                }+            }+            Spacer(Modifier.width(12.dp))+            Column(modifier = Modifier.weight(1f)) {+                Text(+                    location.name,+                    style = MaterialTheme.typography.titleMedium,+                    fontWeight = FontWeight.Medium,+                )+                if (condition != null) {+                    Text(+                        condition.label,+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                    )+                }+                if (daily != null) {+                    val hi = daily.temperatureMax.firstOrNull()+                    val lo = daily.temperatureMin.firstOrNull()+                    if (hi != null && lo != null) {+                        Text(+                            "${formatTemperatureCompact(hi, tempUnit)}  ${formatTemperatureCompact(lo, tempUnit)}",+                            style = MaterialTheme.typography.bodySmall,+                            color = MaterialTheme.colorScheme.onSurfaceVariant,+                        )+                    }+                }+            }+            if (current != null) {+                Text(+                    formatTemperatureCompact(current.temperature, tempUnit),+                    style = MaterialTheme.typography.headlineMedium,+                    fontWeight = FontWeight.Light,+                )+            }+            IconButton(onClick = onDelete, modifier = Modifier.size(40.dp)) {+                IconDelete()+            }+        }+    }+}
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.ktnew file mode 100644index 0000000000..0da9792f86--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/SettingsPage.kt@@ -0,0 +1,84 @@+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/WeatherTheme.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/WeatherTheme.kt b/weather/src/main/java/com/vayunmathur/weather/ui/WeatherTheme.ktnew file mode 100644index 0000000000..aefd0a4acd--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/WeatherTheme.kt@@ -0,0 +1,41 @@+package com.vayunmathur.weather.ui++import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.MaterialExpressiveTheme+import androidx.compose.material3.MotionScheme+import androidx.compose.foundation.isSystemInDarkTheme+import androidx.compose.runtime.Composable+import androidx.compose.ui.graphics.Color+import com.materialkolor.PaletteStyle+import com.materialkolor.dynamiccolor.ColorSpec+import com.materialkolor.rememberDynamicColorScheme++/**+ * Theme mirrors WeatherMaster's `WeatherMasterTheme`: a Material 3 Expressive+ * theme whose color scheme is generated from a single seed color via+ * `materialkolor`. WeatherMaster's default seed is `#2196f3` (Material+ * Blue 500) with the user's pick of palette style — we use the same seed+ * but force [PaletteStyle.TonalSpot], which is the more muted Material You+ * default (vs WeatherMaster's user-selectable Vibrant/Expressive+ * variants).+ */+@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun WeatherTheme(+    darkTheme: Boolean = isSystemInDarkTheme(),+    content: @Composable () -> Unit,+) {+    val colorScheme = rememberDynamicColorScheme(+        seedColor = Color(0xFF2196F3),+        isDark = darkTheme,+        specVersion = ColorSpec.SpecVersion.SPEC_2025,+        style = PaletteStyle.TonalSpot,+    )++    MaterialExpressiveTheme(+        colorScheme = colorScheme,+        motionScheme = MotionScheme.expressive(),+        content = content,+    )+}
weather/src/main/java/com/vayunmathur/weather/ui/components/AirQualityTile.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/AirQualityTile.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/AirQualityTile.ktnew file mode 100644index 0000000000..c62972731b--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/AirQualityTile.kt@@ -0,0 +1,49 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.offset+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.MaterialShapes+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.material3.toShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.R++@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun AirQualityBlock(aqi: Int?, modifier: Modifier = Modifier) {+    val v = aqi ?: 0+    val label = when {+        aqi == null -> "—"+        v <= 50 -> "Good"+        v <= 100 -> "Moderate"+        v <= 150 -> "Sensitive"+        v <= 200 -> "Unhealthy"+        v <= 300 -> "Very unhealthy"+        else -> "Hazardous"+    }+    WeatherBlock(+        title = "Air quality",+        iconRes = R.drawable.outline_air_24,+        modifier = modifier,+        shape = MaterialShapes.Cookie12Sided.toShape(),+        containerColor = MaterialTheme.colorScheme.secondaryContainer,+        contentColor = MaterialTheme.colorScheme.onSecondaryContainer,+    ) {+        Text(+            aqi?.toString() ?: "—",+            style = MaterialTheme.typography.displayMedium,+            color = MaterialTheme.colorScheme.onSecondaryContainer,+            modifier = Modifier.align(Alignment.Center).offset(y = 4.dp),+        )+        Text(+            label,+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.75f),+            modifier = Modifier.align(Alignment.BottomCenter).offset(y = (-20).dp),+        )+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/CurrentHero.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/CurrentHero.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/CurrentHero.ktnew file mode 100644index 0000000000..c6523a1736--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/CurrentHero.kt@@ -0,0 +1,93 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.util.TemperatureUnit+import com.vayunmathur.weather.util.formatTemperatureCompact+import com.vayunmathur.weather.util.weatherConditionForCode++/**+ * Hero — direct port of WeatherMaster's `PixelStyleCurrentWeatherCard`:+ * icon + condition label in a row, 136sp primary-color bold temperature,+ * "Feels like" titleLarge, then a single "Max X° Min Y°" row.+ */+@Composable+fun CurrentHero(+    location: SavedLocation,+    current: Current,+    today: Daily?,+    tempUnit: TemperatureUnit,+) {+    val condition = weatherConditionForCode(current.weatherCode)+    val high = today?.temperatureMax?.firstOrNull()+    val low = today?.temperatureMin?.firstOrNull()++    Column(+        modifier = Modifier+            .fillMaxWidth()+            .padding(start = 16.dp, end = 16.dp, top = 24.dp),+        horizontalAlignment = Alignment.CenterHorizontally,+    ) {+        Row(verticalAlignment = Alignment.CenterVertically) {+            Icon(+                painter = painterResource(condition.iconRes(current.isDay == 1)),+                contentDescription = condition.label,+                modifier = Modifier.size(32.dp),+                tint = MaterialTheme.colorScheme.onSurface,+            )+            Spacer(Modifier.width(6.dp))+            Text(+                text = condition.label,+                color = MaterialTheme.colorScheme.onSurface,+                style = MaterialTheme.typography.titleLarge,+                fontWeight = FontWeight.Medium,+            )+        }+        Text(+            text = formatTemperatureCompact(current.temperature, tempUnit),+            color = MaterialTheme.colorScheme.primary,+            fontSize = 136.sp,+            fontWeight = FontWeight.Bold,+        )+        Text(+            text = "Feels like ${formatTemperatureCompact(current.apparentTemperature, tempUnit)}",+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            style = MaterialTheme.typography.titleLarge,+            fontWeight = FontWeight.Medium,+        )+        Spacer(Modifier.height(6.dp))+        if (high != null && low != null) {+            Row(+                modifier = Modifier.fillMaxWidth(),+                horizontalArrangement = Arrangement.Center,+                verticalAlignment = Alignment.CenterVertically,+            ) {+                Text(+                    text = "Max ${formatTemperatureCompact(high, tempUnit)} Min ${formatTemperatureCompact(low, tempUnit)}",+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                    style = MaterialTheme.typography.titleLarge,+                )+            }+        }+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/DailyList.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/DailyList.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/DailyList.ktnew file mode 100644index 0000000000..592c1e3c1d--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/DailyList.kt@@ -0,0 +1,155 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.util.TemperatureUnit+import com.vayunmathur.weather.util.formatTemperatureCompact+import com.vayunmathur.weather.util.weatherConditionForCode+import kotlinx.datetime.LocalDate++/**+ * 7-day forecast list inside a [WeatherSection]. Each row mirrors Health's+ * `HealthRow` rhythm: 36dp circular tinted icon badge, label column, range+ * bar in the middle, hi/lo on the right. Inset hairline dividers between+ * rows.+ */+@Composable+fun DailyList(daily: Daily, tempUnit: TemperatureUnit) {+    if (daily.time.isEmpty()) return++    val weekLow = daily.temperatureMin.minOrNull() ?: 0.0+    val weekHigh = daily.temperatureMax.maxOrNull() ?: 0.0+    val span = (weekHigh - weekLow).takeIf { it > 0 } ?: 1.0++    WeatherSection(+        title = "7-day forecast",+        leadingIconRes = com.vayunmathur.weather.R.drawable.outline_calendar_24,+        surfacePadding = PaddingValues(vertical = 4.dp),+    ) {+        daily.time.forEachIndexed { i, dateStr ->+            val code = daily.weatherCode.getOrNull(i) ?: 0+            val hi = daily.temperatureMax.getOrNull(i) ?: 0.0+            val lo = daily.temperatureMin.getOrNull(i) ?: 0.0+            DailyRow(+                label = if (i == 0) "Today" else dayLabel(dateStr),+                weatherCode = code,+                lo = lo,+                hi = hi,+                weekLow = weekLow,+                span = span,+                tempUnit = tempUnit,+            )+            if (i < daily.time.size - 1) WeatherSectionDivider(insetStart = 60.dp)+        }+    }+}++@Composable+private fun DailyRow(+    label: String,+    weatherCode: Int,+    lo: Double,+    hi: Double,+    weekLow: Double,+    span: Double,+    tempUnit: TemperatureUnit,+) {+    val condition = weatherConditionForCode(weatherCode)+    val accent = MaterialTheme.colorScheme.onSurface+    val trackColor = MaterialTheme.colorScheme.surfaceContainerHighest+    val barColor = MaterialTheme.colorScheme.onSurface++    Row(+        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        Box(+            modifier = Modifier+                .size(36.dp)+                .clip(CircleShape)+                .background(accent.copy(alpha = 0.10f)),+            contentAlignment = Alignment.Center,+        ) {+            Icon(+                painter = painterResource(condition.iconRes(true)),+                contentDescription = condition.label,+                tint = accent,+                modifier = Modifier.size(20.dp),+            )+        }+        Spacer(Modifier.width(12.dp))+        Text(+            label,+            modifier = Modifier.width(56.dp),+            style = MaterialTheme.typography.bodyLarge,+            fontWeight = FontWeight.Medium,+        )+        Text(+            formatTemperatureCompact(lo, tempUnit),+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            modifier = Modifier.width(36.dp),+        )+        Canvas(+            modifier = Modifier+                .weight(1f)+                .height(6.dp)+                .padding(horizontal = 4.dp),+        ) {+            val w = size.width+            val h = size.height+            drawRoundRect(+                color = trackColor,+                size = Size(w, h),+                cornerRadius = CornerRadius(h / 2),+            )+            val startFrac = ((lo - weekLow) / span).toFloat().coerceIn(0f, 1f)+            val endFrac = ((hi - weekLow) / span).toFloat().coerceIn(0f, 1f)+            val left = w * startFrac+            val widthF = (w * (endFrac - startFrac)).coerceAtLeast(h)+            drawRoundRect(+                color = barColor,+                topLeft = Offset(left, 0f),+                size = Size(widthF, h),+                cornerRadius = CornerRadius(h / 2),+            )+        }+        Text(+            formatTemperatureCompact(hi, tempUnit),+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurface,+            fontWeight = FontWeight.Medium,+            modifier = Modifier.width(36.dp),+        )+    }+}++private fun dayLabel(dateStr: String): String {+    val date = runCatching { LocalDate.parse(dateStr) }.getOrNull() ?: return dateStr+    return date.dayOfWeek.name.take(3).lowercase().replaceFirstChar { it.uppercase() }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyStrip.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyStrip.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyStrip.ktnew file mode 100644index 0000000000..974d1aac64--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyStrip.kt@@ -0,0 +1,142 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.network.Hourly+import com.vayunmathur.weather.util.TemperatureUnit+import com.vayunmathur.weather.util.formatTemperatureCompact+import com.vayunmathur.weather.util.weatherConditionForCode+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant++/**+ * 24-hour preview rendered inside a [WeatherSection] card. First cell shows+ * "Now" and is filled with `surfaceContainerHighest` so the user's gaze+ * lands there first (mirrors Pixel Weather's "now" pill).+ */+@Composable+fun HourlyStrip(hourly: Hourly, tempUnit: TemperatureUnit) {+    val now = System.currentTimeMillis() / 1000+    val cells = remember(hourly) {+        hourly.time.indices+            .mapNotNull { i ->+                val ts = parseIsoToEpochSec(hourly.time.getOrNull(i)) ?: return@mapNotNull null+                if (ts < now - 3600) return@mapNotNull null+                HourlyCell(+                    epochSec = ts,+                    temperature = hourly.temperature.getOrNull(i) ?: 0.0,+                    weatherCode = hourly.weatherCode.getOrNull(i) ?: 0,+                    precip = hourly.precipitationProbability.getOrNull(i) ?: 0,+                    isDay = (hourly.isDay.getOrNull(i) ?: 1) == 1,+                )+            }+            .take(24)+    }+    if (cells.isEmpty()) return++    WeatherSection(+        title = "Hourly forecast",+        leadingIconRes = com.vayunmathur.weather.R.drawable.outline_schedule_24,+        surfacePadding = PaddingValues(vertical = 8.dp),+    ) {+        LazyRow(+            contentPadding = PaddingValues(horizontal = 8.dp),+            horizontalArrangement = Arrangement.spacedBy(0.dp),+        ) {+            itemsIndexed(cells) { index, cell ->+                HourlyCellView(cell, tempUnit, highlightAsNow = index == 0)+            }+        }+    }+}++@Composable+private fun HourlyCellView(cell: HourlyCell, tempUnit: TemperatureUnit, highlightAsNow: Boolean) {+    val condition = weatherConditionForCode(cell.weatherCode)+    val label = if (highlightAsNow) "Now" else formatHour(cell.epochSec)+    val timeColor = if (highlightAsNow) MaterialTheme.colorScheme.primary+                    else MaterialTheme.colorScheme.primary.copy(alpha = 0.75f)+    Column(+        modifier = Modifier+            .padding(horizontal = 4.dp, vertical = 8.dp)+            .width(60.dp),+        horizontalAlignment = Alignment.CenterHorizontally,+        verticalArrangement = Arrangement.spacedBy(8.dp),+    ) {+        // Pixel order: temp on top, condition icon, precip %, then time.+        Text(+            formatTemperatureCompact(cell.temperature, tempUnit),+            style = MaterialTheme.typography.titleMedium,+            color = MaterialTheme.colorScheme.onSurface,+            fontWeight = FontWeight.Medium,+        )+        Icon(+            painter = painterResource(condition.iconRes(cell.isDay)),+            contentDescription = condition.label,+            modifier = Modifier.size(28.dp),+            tint = MaterialTheme.colorScheme.onSurface,+        )+        Text(+            text = if (cell.precip >= 10) "${cell.precip}%" else "",+            style = MaterialTheme.typography.labelSmall,+            color = MaterialTheme.colorScheme.primary,+        )+        Text(+            label,+            style = MaterialTheme.typography.labelMedium,+            color = timeColor,+            fontWeight = if (highlightAsNow) FontWeight.SemiBold else FontWeight.Normal,+        )+    }+}++private data class HourlyCell(+    val epochSec: Long,+    val temperature: Double,+    val weatherCode: Int,+    val precip: Int,+    val isDay: Boolean,+)++private fun parseIsoToEpochSec(iso: String?): Long? {+    if (iso == null) return null+    return runCatching { Instant.parse("$iso:00Z").epochSeconds }.getOrNull()+        ?: runCatching { Instant.parse(iso).epochSeconds }.getOrNull()+}++private fun formatHour(epochSec: Long): String {+    val ldt = Instant.fromEpochSeconds(epochSec)+        .toLocalDateTime(kotlinx.datetime.TimeZone.currentSystemDefault())+    val h = ldt.hour+    val ampm = if (h < 12) "AM" else "PM"+    val display = if (h % 12 == 0) 12 else h % 12+    return "$display $ampm"+}++private inline fun <T> androidx.compose.foundation.lazy.LazyListScope.itemsIndexed(+    items: List<T>,+    crossinline content: @Composable (Int, T) -> Unit,+) {+    items(items.size) { content(it, items[it]) }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/HumidityTile.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/HumidityTile.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/HumidityTile.ktnew file mode 100644index 0000000000..849cfd4bbc--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/HumidityTile.kt@@ -0,0 +1,46 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.offset+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.MaterialShapes+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.material3.toShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.R+import com.vayunmathur.weather.util.TemperatureUnit+import com.vayunmathur.weather.util.formatTemperatureCompact++@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun HumidityBlock(+    relativeHumidity: Int,+    dewPointCelsius: Double,+    tempUnit: TemperatureUnit,+    modifier: Modifier = Modifier,+) {+    WeatherBlock(+        title = "Humidity",+        iconRes = R.drawable.outline_drizzle_24,+        modifier = modifier,+        shape = MaterialShapes.Cookie12Sided.toShape(),+        containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,+        contentColor = MaterialTheme.colorScheme.onSurface,+    ) {+        Text(+            "$relativeHumidity%",+            style = MaterialTheme.typography.displayMedium,+            color = MaterialTheme.colorScheme.onSurface,+            modifier = Modifier.align(Alignment.Center).offset(y = 4.dp),+        )+        Text(+            "Dew point ${formatTemperatureCompact(dewPointCelsius, tempUnit)}",+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            modifier = Modifier.align(Alignment.BottomCenter).offset(y = (-20).dp),+        )+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/MetricBlobGrid.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/MetricBlobGrid.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/MetricBlobGrid.ktnew file mode 100644index 0000000000..7eebe8b688--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/MetricBlobGrid.kt@@ -0,0 +1,110 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.foundation.lazy.grid.rememberLazyGridState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.network.AirQualityCurrent+import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.util.TemperatureUnit+import com.vayunmathur.weather.util.WeatherTile+import com.vayunmathur.weather.util.WeatherViewModel+import com.vayunmathur.weather.util.WindUnit+import sh.calvin.reorderable.DragGestureDetector+import sh.calvin.reorderable.ReorderableItem+import sh.calvin.reorderable.rememberReorderableLazyGridState++/**+ * Adaptive grid of WeatherMaster-style cookie blocks, draggable via+ * `sh.calvin.reorderable` long-press. Mirrors WeatherMaster's `WeatherBlocks`+ * layout: `GridCells.Adaptive(140.dp)`, 14dp spacing, `userScrollEnabled = false`,+ * `heightIn(max = 1500.dp)` so the grid plays nicely inside the parent+ * vertical `LazyColumn`.+ */+@Composable+fun WeatherBlocksGrid(+    current: Current,+    today: Daily?,+    air: AirQualityCurrent?,+    sunriseEpochSec: Long?,+    sunsetEpochSec: Long?,+    tempUnit: TemperatureUnit,+    windUnit: WindUnit,+    viewModel: WeatherViewModel,+    modifier: Modifier = Modifier,+) {+    val savedOrder by viewModel.tileOrder.collectAsState()+    val items = remember(savedOrder) { mutableStateListOf<WeatherTile>().apply { addAll(savedOrder) } }+    LaunchedEffect(savedOrder) {+        if (items.toList() != savedOrder) {+            items.clear(); items.addAll(savedOrder)+        }+    }++    val gridState = rememberLazyGridState()+    val reorderableState = rememberReorderableLazyGridState(gridState) { from, to ->+        items.add(to.index, items.removeAt(from.index))+        viewModel.setTileOrder(items.toList())+    }++    LazyVerticalGrid(+        state = gridState,+        columns = GridCells.Adaptive(minSize = 140.dp),+        modifier = modifier+            .fillMaxWidth()+            .padding(horizontal = 24.dp)+            .heightIn(max = 1500.dp),+        horizontalArrangement = Arrangement.spacedBy(16.dp),+        verticalArrangement = Arrangement.spacedBy(16.dp),+        contentPadding = PaddingValues(bottom = 8.dp),+        userScrollEnabled = false,+    ) {+        items(items = items, key = { it.name }) { tile ->+            ReorderableItem(reorderableState, key = tile.name) {+                Box(+                    modifier = Modifier+                        .fillMaxWidth()+                        .draggableHandle(dragGestureDetector = DragGestureDetector.LongPress),+                ) {+                    when (tile) {+                        WeatherTile.AirQuality -> AirQualityBlock(aqi = air?.usAqi)+                        WeatherTile.Sun -> SunBlock(+                            sunriseEpochSec = sunriseEpochSec,+                            sunsetEpochSec = sunsetEpochSec,+                        )+                        WeatherTile.Visibility -> VisibilityBlock(visibilityMeters = current.visibility)+                        WeatherTile.Pressure -> PressureBlock(pressureHpa = current.pressureMsl)+                        WeatherTile.Humidity -> HumidityBlock(+                            relativeHumidity = current.relativeHumidity,+                            dewPointCelsius = current.dewPoint,+                            tempUnit = tempUnit,+                        )+                        WeatherTile.Pollen -> PollenBlock(air = air)+                        WeatherTile.UV -> UVBlock(uvIndex = today?.uvIndexMax?.firstOrNull())+                        WeatherTile.Wind -> WindBlock(+                            speedKph = current.windSpeed,+                            directionDeg = current.windDirection,+                            unit = windUnit,+                        )+                    }+                }+            }+        }+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/PollenTile.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/PollenTile.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/PollenTile.ktnew file mode 100644index 0000000000..42bde942a6--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/PollenTile.kt@@ -0,0 +1,62 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.offset+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.MaterialShapes+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.material3.toShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.R+import com.vayunmathur.weather.network.AirQualityCurrent++@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun PollenBlock(air: AirQualityCurrent?, modifier: Modifier = Modifier) {+    val worst = listOfNotNull(+        air?.grassPollen,+        air?.alderPollen,+        air?.birchPollen,+        air?.olivePollen,+        air?.ragweedPollen,+        air?.mugwortPollen,+    ).maxOrNull() ?: 0.0+    val level = when {+        worst <= 0.0 -> 0+        worst < 10 -> 1+        worst < 50 -> 2+        worst < 200 -> 3+        else -> 4+    }+    val label = when (level) {+        0 -> "None"+        1 -> "Low"+        2 -> "Medium"+        3 -> "High"+        else -> "Severe"+    }+    WeatherBlock(+        title = "Pollen",+        iconRes = R.drawable.outline_grass_24,+        modifier = modifier,+        shape = MaterialShapes.Cookie12Sided.toShape(),+        containerColor = MaterialTheme.colorScheme.errorContainer,+        contentColor = MaterialTheme.colorScheme.onErrorContainer,+    ) {+        Text(+            "$level/4",+            style = MaterialTheme.typography.displayMedium,+            color = MaterialTheme.colorScheme.onErrorContainer,+            modifier = Modifier.align(Alignment.Center).offset(y = 4.dp),+        )+        Text(+            label,+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.75f),+            modifier = Modifier.align(Alignment.BottomCenter).offset(y = (-20).dp),+        )+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/PrecipChart.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/PrecipChart.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/PrecipChart.ktnew file mode 100644index 0000000000..59cc488812--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/PrecipChart.kt@@ -0,0 +1,88 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.network.Hourly+import kotlin.time.Instant++/**+ * 24-hour precipitation-probability bars inside a [WeatherSection]. Bars get+ * more opaque as the chance climbs so a quick glance shows the rainy+ * stretch.+ */+@Composable+fun PrecipChart(hourly: Hourly) {+    if (hourly.precipitationProbability.isEmpty()) return+    val nowSec = System.currentTimeMillis() / 1000+    val pairs: List<Int> = hourly.time+        .withIndex()+        .mapNotNull { (i, t) ->+            val ts = runCatching { Instant.parse("$t:00Z").epochSeconds }.getOrNull()+                ?: runCatching { Instant.parse(t).epochSeconds }.getOrNull()+                ?: return@mapNotNull null+            if (ts < nowSec - 3600) null else hourly.precipitationProbability.getOrNull(i)+        }+        .filterNotNull()+        .take(24)+    if (pairs.isEmpty() || pairs.max() == 0) return++    val barColor = MaterialTheme.colorScheme.onSurface+    val trackColor = MaterialTheme.colorScheme.surfaceContainerHighest++    WeatherSection(title = "Precipitation", surfacePadding = PaddingValues(16.dp)) {+        Text(+            "Max ${pairs.max()}% in the next 24 hours",+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurface,+        )+        Canvas(+            modifier = Modifier+                .fillMaxWidth()+                .height(72.dp)+                .padding(top = 12.dp),+        ) {+            val w = size.width+            val h = size.height+            val n = pairs.size+            val barW = w / n+            drawRoundRect(+                color = trackColor,+                topLeft = Offset(0f, h - 2.dp.toPx()),+                size = Size(w, 2.dp.toPx()),+                cornerRadius = CornerRadius(1.dp.toPx()),+            )+            pairs.forEachIndexed { i, p ->+                val frac = p / 100f+                val barH = h * frac+                val alpha = (0.30f + 0.65f * frac).coerceAtMost(1f)+                drawRoundRect(+                    color = barColor.copy(alpha = alpha),+                    topLeft = Offset(i * barW + barW * 0.20f, h - barH),+                    size = Size(barW * 0.6f, barH),+                    cornerRadius = CornerRadius(2.dp.toPx()),+                )+            }+        }+        Row(+            modifier = Modifier.fillMaxWidth().padding(top = 6.dp),+            horizontalArrangement = Arrangement.SpaceBetween,+        ) {+            Text("NOW", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+            Text("12H", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+            Text("24H", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+        }+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/PressureTile.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/PressureTile.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/PressureTile.ktnew file mode 100644index 0000000000..79622e811b--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/PressureTile.kt@@ -0,0 +1,39 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.R++@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun PressureBlock(pressureHpa: Double, modifier: Modifier = Modifier) {+    val inHg = pressureHpa * 0.02953+    WeatherBlock(+        title = "Pressure",+        iconRes = R.drawable.outline_pressure_24,+        modifier = modifier,+        shape = CircleShape,+        containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,+        contentColor = MaterialTheme.colorScheme.onSurface,+    ) {+        Text(+            String.format("%.2f", inHg),+            style = MaterialTheme.typography.displaySmall,+            color = MaterialTheme.colorScheme.onSurface,+            modifier = Modifier.align(Alignment.Center).offset(y = 4.dp),+        )+        Text(+            "inHg",+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            modifier = Modifier.align(Alignment.BottomCenter).offset(y = (-20).dp),+        )+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/SunTile.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/SunTile.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/SunTile.ktnew file mode 100644index 0000000000..97142018e8--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/SunTile.kt@@ -0,0 +1,55 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.offset+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.MaterialShapes+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.material3.toShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.R+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant++@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun SunBlock(sunriseEpochSec: Long?, sunsetEpochSec: Long?, modifier: Modifier = Modifier) {+    val sunrise = sunriseEpochSec?.let { formatTime(it) } ?: "—"+    val sunset = sunsetEpochSec?.let { formatTime(it) } ?: "—"+    WeatherBlock(+        title = "Sun",+        iconRes = R.drawable.outline_clear_day_24,+        modifier = modifier,+        shape = MaterialShapes.Cookie12Sided.toShape(),+        containerColor = MaterialTheme.colorScheme.primaryContainer,+        contentColor = MaterialTheme.colorScheme.onPrimaryContainer,+    ) {+        Text(+            sunrise,+            style = MaterialTheme.typography.titleLarge,+            color = MaterialTheme.colorScheme.onPrimaryContainer,+            modifier = Modifier.align(Alignment.Center).offset(y = (-12).dp),+        )+        Text(+            "Sets $sunset",+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.75f),+            modifier = Modifier.align(Alignment.BottomCenter).offset(y = (-20).dp),+        )+    }+}++private fun formatTime(epochSec: Long): String {+    val ldt = Instant.fromEpochSeconds(epochSec)+        .toLocalDateTime(TimeZone.currentSystemDefault())+    val h = ldt.hour+    val m = ldt.minute+    val display = if (h % 12 == 0) 12 else h % 12+    val ampm = if (h < 12) "AM" else "PM"+    val mm = m.toString().padStart(2, '0')+    return "$display:$mm $ampm"+}
weather/src/main/java/com/vayunmathur/weather/ui/components/SunriseSunsetCard.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/SunriseSunsetCard.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/SunriseSunsetCard.ktnew file mode 100644index 0000000000..9957bab92e--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/SunriseSunsetCard.kt@@ -0,0 +1,139 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.PathEffect+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toLocalDateTime+import kotlin.math.cos+import kotlin.math.sin+import kotlin.time.Instant++/**+ * Sun arc card — dashed full arc track, solid arc + dot up to the current+ * moment, sunrise/sunset labels underneath. Sits inside a [WeatherSection].+ */+@Composable+fun SunriseSunsetCard(sunriseEpochSec: Long?, sunsetEpochSec: Long?) {+    if (sunriseEpochSec == null || sunsetEpochSec == null || sunsetEpochSec <= sunriseEpochSec) return+    val nowSec = System.currentTimeMillis() / 1000+    val frac = ((nowSec - sunriseEpochSec).toDouble() / (sunsetEpochSec - sunriseEpochSec))+        .coerceIn(0.0, 1.0)+    val isDay = nowSec in sunriseEpochSec..sunsetEpochSec++    val arcColor = MaterialTheme.colorScheme.onSurface+    val trackColor = MaterialTheme.colorScheme.outlineVariant+    val sunColor = MaterialTheme.colorScheme.onSurface++    WeatherSection(title = "Sun", surfacePadding = PaddingValues(16.dp)) {+        Box(modifier = Modifier.fillMaxWidth().height(110.dp)) {+            Canvas(modifier = Modifier.fillMaxWidth().height(110.dp)) {+                val w = size.width+                val h = size.height+                val trackPath = Path().apply {+                    moveTo(0f, h)+                    for (deg in 180..360) {+                        val theta = Math.toRadians(deg.toDouble())+                        val x = (w / 2 + (w / 2) * cos(theta)).toFloat()+                        val y = (h + h * sin(theta)).toFloat()+                        lineTo(x, y)+                    }+                }+                drawPath(+                    trackPath,+                    color = trackColor,+                    style = Stroke(+                        width = 1.5.dp.toPx(),+                        pathEffect = PathEffect.dashPathEffect(floatArrayOf(8f, 8f)),+                    ),+                )+                val activePath = Path().apply {+                    moveTo(0f, h)+                    val endDeg = 180 + 180 * frac+                    var d = 180.0+                    while (d <= endDeg) {+                        val theta = Math.toRadians(d)+                        val x = (w / 2 + (w / 2) * cos(theta)).toFloat()+                        val y = (h + h * sin(theta)).toFloat()+                        lineTo(x, y)+                        d += 1.0+                    }+                }+                drawPath(+                    activePath,+                    color = if (isDay) arcColor else trackColor,+                    style = Stroke(width = 2.5.dp.toPx()),+                )+                val theta = Math.toRadians(180 + 180 * frac)+                val sunX = (w / 2 + (w / 2) * cos(theta)).toFloat()+                val sunY = (h + h * sin(theta)).toFloat()+                drawCircle(+                    color = if (isDay) sunColor else trackColor,+                    radius = 7.dp.toPx(),+                    center = Offset(sunX, sunY),+                )+            }+        }+        Row(+            modifier = Modifier.fillMaxWidth().padding(top = 12.dp),+            horizontalArrangement = Arrangement.SpaceBetween,+        ) {+            Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+                Text(+                    "SUNRISE",+                    style = MaterialTheme.typography.labelSmall.copy(letterSpacing = 1.sp),+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+                Text(+                    formatTime(sunriseEpochSec),+                    style = MaterialTheme.typography.titleMedium,+                    fontWeight = FontWeight.Medium,+                )+            }+            Column(+                verticalArrangement = Arrangement.spacedBy(2.dp),+                horizontalAlignment = Alignment.End,+            ) {+                Text(+                    "SUNSET",+                    style = MaterialTheme.typography.labelSmall.copy(letterSpacing = 1.sp),+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+                Text(+                    formatTime(sunsetEpochSec),+                    style = MaterialTheme.typography.titleMedium,+                    fontWeight = FontWeight.Medium,+                )+            }+        }+    }+}++private fun formatTime(epochSec: Long): String {+    val ldt = Instant.fromEpochSeconds(epochSec)+        .toLocalDateTime(TimeZone.currentSystemDefault())+    val h = ldt.hour+    val m = ldt.minute+    val display = if (h % 12 == 0) 12 else h % 12+    val ampm = if (h < 12) "AM" else "PM"+    val mm = m.toString().padStart(2, '0')+    return "$display:$mm $ampm"+}
weather/src/main/java/com/vayunmathur/weather/ui/components/UVTile.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/UVTile.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/UVTile.ktnew file mode 100644index 0000000000..7d9f4203ba--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/UVTile.kt@@ -0,0 +1,48 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.offset+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.MaterialShapes+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.material3.toShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.R++@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun UVBlock(uvIndex: Double?, modifier: Modifier = Modifier) {+    val v = uvIndex?.let { it.toInt() }+    val label = when {+        v == null -> "—"+        v < 3 -> "Low"+        v < 6 -> "Moderate"+        v < 8 -> "High"+        v < 11 -> "Very high"+        else -> "Extreme"+    }+    WeatherBlock(+        title = "UV index",+        iconRes = R.drawable.outline_clear_day_24,+        modifier = modifier,+        shape = MaterialShapes.Sunny.toShape(),+        containerColor = MaterialTheme.colorScheme.tertiaryContainer,+        contentColor = MaterialTheme.colorScheme.onTertiaryContainer,+    ) {+        Text(+            v?.toString() ?: "—",+            style = MaterialTheme.typography.displayMedium,+            color = MaterialTheme.colorScheme.onTertiaryContainer,+            modifier = Modifier.align(Alignment.Center).offset(y = 4.dp),+        )+        Text(+            label,+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onTertiaryContainer.copy(alpha = 0.75f),+            modifier = Modifier.align(Alignment.BottomCenter).offset(y = (-20).dp),+        )+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/VisibilityTile.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/VisibilityTile.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/VisibilityTile.ktnew file mode 100644index 0000000000..4b69c6ddd8--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/VisibilityTile.kt@@ -0,0 +1,56 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.offset+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.MaterialShapes+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.material3.toShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.R+import kotlin.math.roundToInt++@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun VisibilityBlock(visibilityMeters: Double, useMiles: Boolean = false, modifier: Modifier = Modifier) {+    val value: String+    val unit: String+    if (useMiles) {+        value = (visibilityMeters / 1609.34).roundToInt().toString()+        unit = "mi"+    } else {+        value = (visibilityMeters / 1000).roundToInt().toString()+        unit = "km"+    }+    val label = when {+        visibilityMeters >= 16_000 -> "Crystal clear"+        visibilityMeters >= 8_000 -> "Clear"+        visibilityMeters >= 4_000 -> "Slight haze"+        visibilityMeters >= 1_000 -> "Hazy"+        else -> "Poor"+    }+    WeatherBlock(+        title = "Visibility",+        iconRes = R.drawable.outline_visibility_24,+        modifier = modifier,+        shape = MaterialShapes.Cookie12Sided.toShape(),+        containerColor = MaterialTheme.colorScheme.tertiaryContainer,+        contentColor = MaterialTheme.colorScheme.onTertiaryContainer,+    ) {+        Text(+            "$value $unit",+            style = MaterialTheme.typography.displaySmall,+            color = MaterialTheme.colorScheme.onTertiaryContainer,+            modifier = Modifier.align(Alignment.Center).offset(y = 4.dp),+        )+        Text(+            label,+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onTertiaryContainer.copy(alpha = 0.75f),+            modifier = Modifier.align(Alignment.BottomCenter).offset(y = (-20).dp),+        )+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlock.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlock.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlock.ktnew file mode 100644index 0000000000..7c0c1a6b91--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlock.kt@@ -0,0 +1,86 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialShapes+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.toShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp++/**+ * Square weather-detail block, modelled on WeatherMaster's `WeatherBlocks`+ * cookie-shaped tiles. Each block picks its own [shape] from+ * [MaterialShapes] and its own [containerColor] from [MaterialTheme.colorScheme]+ * so the grid feels varied while staying inside the seed-derived Material+ * You palette. Header sits at top-center, content fills the rest as a+ * [BoxScope].+ */+@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun WeatherBlock(+    title: String,+    iconRes: Int,+    modifier: Modifier = Modifier,+    shape: Shape = MaterialShapes.Cookie12Sided.toShape(),+    containerColor: Color = MaterialTheme.colorScheme.surfaceContainer,+    contentColor: Color = MaterialTheme.colorScheme.onSurface,+    content: @Composable androidx.compose.foundation.layout.BoxScope.() -> Unit,+) {+    Surface(+        modifier = modifier+            .fillMaxSize()+            .aspectRatio(1f),+        shape = shape,+        color = containerColor,+        contentColor = contentColor,+    ) {+        Box(modifier = Modifier.fillMaxSize()) {+            content()+            Box(modifier = Modifier.align(Alignment.TopCenter)) {+                BlockHeader(title = title, iconRes = iconRes, contentColor = contentColor)+            }+        }+    }+}++@Composable+private fun BlockHeader(title: String, iconRes: Int, contentColor: Color) {+    Row(+        horizontalArrangement = Arrangement.spacedBy(5.dp, alignment = Alignment.CenterHorizontally),+        verticalAlignment = Alignment.CenterVertically,+        modifier = Modifier.padding(top = 16.dp, start = 12.dp, end = 12.dp),+    ) {+        Icon(+            painter = painterResource(iconRes),+            contentDescription = null,+            modifier = Modifier.size(18.dp),+            tint = contentColor.copy(alpha = 0.9f),+        )+        Text(+            text = title,+            style = MaterialTheme.typography.titleMedium,+            fontWeight = FontWeight.Bold,+            color = contentColor.copy(alpha = 0.9f),+            maxLines = 1,+            overflow = TextOverflow.Ellipsis,+        )+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherCard.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherCard.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherCard.ktnew file mode 100644index 0000000000..9042c52448--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherCard.kt@@ -0,0 +1,101 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp++/**+ * Header rendered ABOVE each section's surface — `titleMedium` `Medium`,+ * with a small leading glyph in the same color. Mirrors the Pixel Weather+ * card-title look ("Hourly forecast" with a clock icon, "10-day forecast"+ * with a calendar icon, etc.).+ */+@Composable+fun SectionHeader(+    title: String,+    modifier: Modifier = Modifier,+    leadingIconRes: Int? = null,+) {+    Row(+        modifier = modifier+            .fillMaxWidth()+            .padding(horizontal = 32.dp, vertical = 6.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        if (leadingIconRes != null) {+            Icon(+                painter = painterResource(id = leadingIconRes),+                contentDescription = null,+                tint = MaterialTheme.colorScheme.onSurface,+                modifier = Modifier.size(18.dp),+            )+            Spacer(Modifier.width(10.dp))+        }+        Text(+            text = title,+            style = MaterialTheme.typography.titleMedium,+            fontWeight = FontWeight.Medium,+            color = MaterialTheme.colorScheme.onSurface,+        )+    }+}++/**+ * Section shell — header inside the card at the top, then content+ * underneath. Matches Pixel Weather's card-with-header-inside pattern.+ * Background is `surfaceContainer` for a subtle elevation against the page+ * surface.+ */+@Composable+fun WeatherSection(+    title: String,+    modifier: Modifier = Modifier,+    leadingIconRes: Int? = null,+    surfacePadding: PaddingValues = PaddingValues(0.dp),+    content: @Composable ColumnScope.() -> Unit,+) {+    Surface(+        modifier = modifier+            .fillMaxWidth()+            .padding(horizontal = 16.dp),+        shape = RoundedCornerShape(24.dp),+        color = MaterialTheme.colorScheme.surfaceContainer,+    ) {+        Column(modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp)) {+            SectionHeader(title = title, leadingIconRes = leadingIconRes)+            Column(+                modifier = Modifier.fillMaxWidth().padding(surfacePadding),+                content = content,+            )+        }+    }+}++/** Thin inset hairline between rows inside a [WeatherSection]. */+@Composable+fun WeatherSectionDivider(insetStart: Dp = 16.dp) {+    HorizontalDivider(+        modifier = Modifier.padding(start = insetStart, end = 16.dp),+        thickness = 0.5.dp,+        color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),+    )+}
weather/src/main/java/com/vayunmathur/weather/ui/components/WindTile.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/WindTile.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/WindTile.ktnew file mode 100644index 0000000000..cfca110bd7--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/WindTile.kt@@ -0,0 +1,42 @@+package com.vayunmathur.weather.ui.components++import androidx.compose.foundation.layout.offset+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.MaterialShapes+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.material3.toShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.weather.R+import com.vayunmathur.weather.util.WindUnit+import com.vayunmathur.weather.util.compassDirection+import com.vayunmathur.weather.util.formatWind++@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun WindBlock(speedKph: Double, directionDeg: Int, unit: WindUnit, modifier: Modifier = Modifier) {+    WeatherBlock(+        title = "Wind",+        iconRes = R.drawable.outline_wind_24,+        modifier = modifier,+        shape = MaterialShapes.Pill.toShape(),+        containerColor = MaterialTheme.colorScheme.primaryContainer,+        contentColor = MaterialTheme.colorScheme.onPrimaryContainer,+    ) {+        Text(+            formatWind(speedKph, unit),+            style = MaterialTheme.typography.displaySmall,+            color = MaterialTheme.colorScheme.onPrimaryContainer,+            modifier = Modifier.align(Alignment.Center).offset(y = 4.dp),+        )+        Text(+            "From ${compassDirection(directionDeg)}",+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.75f),+            modifier = Modifier.align(Alignment.BottomCenter).offset(y = (-20).dp),+        )+    }+}
weather/src/main/java/com/vayunmathur/weather/util/LocationProvider.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/util/LocationProvider.kt b/weather/src/main/java/com/vayunmathur/weather/util/LocationProvider.ktnew file mode 100644index 0000000000..b82107e514--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/util/LocationProvider.kt@@ -0,0 +1,85 @@+package com.vayunmathur.weather.util++import android.Manifest+import android.annotation.SuppressLint+import android.content.Context+import android.content.pm.PackageManager+import android.location.Location+import android.location.LocationManager+import androidx.core.content.ContextCompat+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlin.coroutines.resume++/**+ * Wraps Android's framework [LocationManager] to provide a single-shot+ * "what's the device's current rough location?" suspending call. Mirrors the+ * pattern used by [com.vayunmathur.maps.util.FrameworkLocationManager] —+ * intentionally avoids the play-services-location dependency since no other+ * module in this repo brings it in.+ *+ * Strategy:+ *   1. Try the freshest of `getLastKnownLocation` from each provider.+ *   2. If nothing recent is available, ask GPS/Network for ONE update each+ *      and return whichever arrives first.+ *+ * Returns `null` if location permission isn't granted or if both providers+ * fail to deliver within the caller's timeout. Callers should wrap in+ * `withTimeoutOrNull(...)` to bound the wait.+ */+object LocationProvider {++    fun hasPermission(context: Context): Boolean {+        val fine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)+        val coarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)+        return fine == PackageManager.PERMISSION_GRANTED || coarse == PackageManager.PERMISSION_GRANTED+    }++    /**+     * Best-effort current location. Returns the last known fix immediately if+     * one is available; otherwise requests a single update.+     */+    @SuppressLint("MissingPermission")+    suspend fun currentLocation(context: Context): Location? {+        if (!hasPermission(context)) return null+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return null++        val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)+            .filter { lm.isProviderEnabled(it) }+        if (providers.isEmpty()) return null++        // 1. Quick path: cached last known location.+        providers+            .mapNotNull { runCatching { lm.getLastKnownLocation(it) }.getOrNull() }+            .maxByOrNull { it.time }+            ?.let { return it }++        // 2. Slow path: register one-shot listeners on every enabled provider+        //    and resume with the first fix.+        return suspendCancellableCoroutine { cont ->+            val listeners = mutableListOf<android.location.LocationListener>()+            var resumed = false+            providers.forEach { provider ->+                val listener = object : android.location.LocationListener {+                    override fun onLocationChanged(location: Location) {+                        if (!resumed) {+                            resumed = true+                            listeners.forEach { runCatching { lm.removeUpdates(it) } }+                            cont.resume(location)+                        }+                    }+                    override fun onProviderDisabled(provider: String) {}+                    override fun onProviderEnabled(provider: String) {}+                    @Deprecated("Removed in API 29 but kept for older devices")+                    override fun onStatusChanged(provider: String?, status: Int, extras: android.os.Bundle?) {}+                }+                listeners += listener+                runCatching {+                    lm.requestLocationUpdates(provider, 0L, 0f, listener, android.os.Looper.getMainLooper())+                }+            }+            cont.invokeOnCancellation {+                listeners.forEach { runCatching { lm.removeUpdates(it) } }+            }+        }+    }+}
weather/src/main/java/com/vayunmathur/weather/util/TileOrderPrefs.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/util/TileOrderPrefs.kt b/weather/src/main/java/com/vayunmathur/weather/util/TileOrderPrefs.ktnew file mode 100644index 0000000000..8aaedfbca2--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/util/TileOrderPrefs.kt@@ -0,0 +1,39 @@+package com.vayunmathur.weather.util++import android.content.Context+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++private val Context.tileOrderDataStore by preferencesDataStore(name = "weather_tile_order")+private val KEY_ORDER = stringPreferencesKey("tile_order")++/** Stable identifiers for the customizable metric tiles. */+enum class WeatherTile { AirQuality, Sun, Visibility, Pressure, Humidity, Pollen, UV, Wind }++/**+ * User-customizable order of metric tiles in the home grid. Persisted as a+ * comma-separated string of enum names so future tiles can be added without+ * a migration — unknown / new tiles are appended at end on each read.+ */+class TileOrderPrefs(private val context: Context) {++    val order: Flow<List<WeatherTile>> = context.tileOrderDataStore.data.map { prefs ->+        val saved = prefs[KEY_ORDER]+            ?.split(',')+            ?.mapNotNull { name -> runCatching { WeatherTile.valueOf(name) }.getOrNull() }+            ?: emptyList()+        // Append any tile not yet in the saved list (new tiles introduced+        // after the user customized).+        val remaining = WeatherTile.entries.filter { it !in saved }+        saved + remaining+    }++    suspend fun setOrder(order: List<WeatherTile>) {+        context.tileOrderDataStore.edit { prefs ->+            prefs[KEY_ORDER] = order.joinToString(",") { it.name }+        }+    }+}
weather/src/main/java/com/vayunmathur/weather/util/UnitFormat.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/util/UnitFormat.kt b/weather/src/main/java/com/vayunmathur/weather/util/UnitFormat.ktnew file mode 100644index 0000000000..cd5d460924--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/util/UnitFormat.kt@@ -0,0 +1,45 @@+package com.vayunmathur.weather.util++import kotlin.math.roundToInt++/** Temperature display unit. Storage / API is always Celsius. */+enum class TemperatureUnit { Celsius, Fahrenheit }++/** Wind-speed display unit. Storage / API is always km/h. */+enum class WindUnit { KmH, Mph }++fun Double.celsiusTo(unit: TemperatureUnit): Double = when (unit)

Diff truncated.