wear: maps companion renders a real watch map
- Commit
18b4f732976dcf0bff38f08c98368506ec75febd- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-25 01:56 UTC (11 days ago)
- Parents
42bf04a
New :maps:wear: the watch renders a Canvas map from a phone-supplied vector snapshot (600 m radius, quantized 2 m units, 48 KB region cap with a Douglas-Peucker degradation ladder; route overlay 24 KB). Position is the phone's location; a fresh region extracts at 65% of radius (hysteresis) or on watch request; offline keeps the last region with a stale label. Active navigation overlays the decimated route + maneuvers; Idle/Arrived/ Failed clears it. HONEST LIMIT: library/map exposes no Kotlin basemap geometry API (Vulkan decodes the planet natively), so production snapshots carry POIs, saved places, and the route today and declare degraded=[roads,water,buildings]; extractor and renderer already support those kinds when a source lands - no geometry faked. Verified: WearMapRegionTest 9/9, wear 10/10 + assemble. Parent verification: full :maps tests + wear lint green; :maps:lint has a pre-existing ScaffoldSearch error in SearchSheet.kt, untouched by this change.
Diff
maps-wear/AGENTS.md
diff --git a/maps-wear/AGENTS.md b/maps-wear/AGENTS.mdnew file mode 100644index 0000000000..2bcac5a866--- /dev/null+++ b/maps-wear/AGENTS.md@@ -0,0 +1,49 @@+# AGENTS.md — maps-wear/ (':maps:wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `maps-wear/` + `maps/` (the phone side of the same feature).++- Gradle: :maps:wear / dir: maps-wear/ (convention: `common-conventions-wear`)+- Package roots present: ui, data, domain, sync+- Entry file: ui/WearMainActivity.kt++## Why this module exists (read before changing identity)+Wear OS companion of the phone Maps (`:maps`). This module deliberately+uses `applicationId = "com.vayunmathur.maps"` (the phone app's) with the+shared dev/release signing from the convention plugins: WearLink's+handshake token requires the same signing certificate on both sides, so+changing either breaks phone<->watch sync. Bootstrap is a one-time ADB+sideload of this APK onto the watch.++## Protocol+`domain/WearMapsProtocol.kt` is a copy of the phone's file (Gradle cannot+depend on another app module). Change both copies together; each side's+`WearMapsProtocolTest` pins the same golden JSON.++- Region snapshot: WearLink data item (`/maps/region`, phone -> watch) —+ bounded, simplified, quantized vector geometry for a Canvas renderer;+ the watch carries no tile stack and no planet data+- Route overlay: WearLink data item (`/maps/route`, phone -> watch);+ `active=false` is the explicit clear when navigation ends+- Position: WearLink data item (`/maps/position`, phone -> watch)+- Watch state: WearLink data item (`/maps/watch-state`, watch -> phone)+- Fresh region: WearLink message (`/maps/request-region`), watch -> phone+- Transport: :library:wearlink (RFCOMM, no Play services); app-lifecycle-bound++## Execution model (stated, not implied)+The PHONE supplies the region and is the position source (its location+manager / navigation session); the watch runs no GPS of its own. The+phone republishes the region when the user nears the snapshot edge+(hysteresis, 65% of radius); between republishes the watch moves the+user dot and follows it within the last region. With the link down the+last region renders with a stale/offline label — never as live data.+North-up in v1; the renderer is a plain Canvas projection, so bearing+rotation is a cheap future step, not claimed here. The phone has no+Home/Work saved-place concept, so the saved glance shows saved places+with distance — no ETA is invented.++## Verify (this module only)+```+./gradlew :maps:wear:assembleDev+./gradlew :maps:wear:testDebugUnitTest+```
maps-wear/build.gradle.kts
diff --git a/maps-wear/build.gradle.kts b/maps-wear/build.gradle.ktsnew file mode 100644index 0000000000..43f3f97115--- /dev/null+++ b/maps-wear/build.gradle.kts@@ -0,0 +1,30 @@+plugins {+ id("common-conventions-wear")+}++launcherIcon {+ symbol = "location_on"+}++// Version shared with the phone app (root version.txt).+val wearVersionLines = file("../version.txt").readLines()+val wearVersionCode = wearVersionLines[0].trim().toInt()+val wearVersionName = wearVersionLines[1].trim()++android {+ // WearLink handshake requires same package + signing as the phone app.+ namespace = "com.vayunmathur.maps.wear"+ defaultConfig {+ applicationId = "com.vayunmathur.maps"+ minSdk = 31+ versionCode = wearVersionCode+ versionName = wearVersionName+ }+}++dependencies {+ implementation(libs.kotlinx.coroutines.android)+ implementation(project(":library:wearlink"))+ testImplementation(libs.kotlin.test)+ testImplementation(libs.kotlin.test.junit)+}
maps-wear/src/main/AndroidManifest.xml
diff --git a/maps-wear/src/main/AndroidManifest.xml b/maps-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..a7b9f447b3--- /dev/null+++ b/maps-wear/src/main/AndroidManifest.xml@@ -0,0 +1,38 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <uses-feature+ android:name="android.hardware.type.watch"+ android:required="true" />+ <uses-feature+ android:name="android.hardware.touchscreen"+ android:required="false" />++ <uses-permission android:name="android.permission.WAKE_LOCK" />++ <application+ android:allowBackup="false"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@android:style/Theme.Material.NoActionBar">++ <!-- Paired with the phone app, not a standalone watch app. -->+ <meta-data+ android:name="com.google.android.wearable.standalone"+ android:value="false" />++ <activity+ android:name=".ui.WearMainActivity"+ android:exported="true"+ android:taskAffinity="">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>++ <!-- WearLink delivery is app-lifecycle-bound; no system listener service. -->+ </application>+</manifest>
maps-wear/src/main/java/com/vayunmathur/maps/wear/data/WearMapsStore.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/data/WearMapsStore.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/data/WearMapsStore.ktnew file mode 100644index 0000000000..27e9c39789--- /dev/null+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/data/WearMapsStore.kt@@ -0,0 +1,109 @@+package com.vayunmathur.maps.wear.data++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.maps.wear.domain.WearMapSnapshot+import com.vayunmathur.maps.wear.domain.WearMapsProtocol+import com.vayunmathur.maps.wear.domain.WearPosition+import com.vayunmathur.maps.wear.domain.WearRouteState+import com.vayunmathur.maps.wear.domain.WearWatchState+import java.io.File+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.encodeToString++/**+ * The watch's local truth: the last region snapshot, route overlay and+ * position, persisted as JSON in app-private storage so the map renders+ * fully offline (phone absent, process cold-started) — labelled stale,+ * never as live data. An inactive [WearRouteState] clears the overlay+ * and is not kept.+ */+class WearMapsStore private constructor(private val context: Context) {++ companion object {+ private const val TAG = "WearMapsStore"++ @Volatile+ private var instance: WearMapsStore? = null++ /** The process-wide store (bridge and UI must agree on one). */+ fun get(context: Context): WearMapsStore = instance ?: synchronized(this) {+ instance ?: WearMapsStore(context.applicationContext).also { instance = it }+ }+ }++ private val regionFile = File(context.filesDir, "wear-maps-region.json")+ private val routeFile = File(context.filesDir, "wear-maps-route.json")+ private val positionFile = File(context.filesDir, "wear-maps-position.json")++ private val _snapshot = MutableStateFlow(loadSnapshot())+ val snapshot: StateFlow<WearMapSnapshot?> = _snapshot.asStateFlow()++ private val _route = MutableStateFlow(loadRoute())+ /** Active route overlay, or null when no navigation (cleared routes stay cleared). */+ val route: StateFlow<WearRouteState?> = _route.asStateFlow()++ private val _position = MutableStateFlow(loadPosition())+ val position: StateFlow<WearPosition?> = _position.asStateFlow()++ private val _connected = MutableStateFlow(false)+ /** Last known WearLink session state, for offline honesty in the UI. */+ val connected: StateFlow<Boolean> = _connected.asStateFlow()++ fun setConnected(connected: Boolean) {+ _connected.value = connected+ }++ fun setSnapshot(snapshot: WearMapSnapshot) {+ _snapshot.value = snapshot+ persist(regionFile, WearMapsProtocol.json.encodeToString(snapshot))+ publishWatchState()+ }++ /** Applies a route state; `active=false` clears the overlay (route ended). */+ fun setRoute(state: WearRouteState) {+ val applied = com.vayunmathur.maps.wear.domain.wearApplyRouteState(_route.value, state)+ _route.value = applied+ if (applied == null) {+ runCatching { routeFile.delete() }+ } else {+ persist(routeFile, WearMapsProtocol.json.encodeToString(applied))+ }+ publishWatchState()+ }++ fun setPosition(position: WearPosition) {+ _position.value = position+ persist(positionFile, WearMapsProtocol.json.encodeToString(position))+ }++ private fun publishWatchState() {+ com.vayunmathur.maps.wear.sync.WearLinkBridge.publishWatchState(context)+ }++ /** The watch-state document the bridge republishes on connect. */+ fun watchState(): WearWatchState = WearWatchState(+ appliedGeneratedAtMillis = _snapshot.value?.generatedAtMillis ?: 0L,+ hasRegion = _snapshot.value != null,+ routeActive = _route.value?.active == true,+ )++ private fun loadSnapshot(): WearMapSnapshot? = runCatching {+ WearMapsProtocol.json.decodeFromString<WearMapSnapshot>(regionFile.readText())+ }.getOrNull()++ private fun loadRoute(): WearRouteState? = runCatching {+ WearMapsProtocol.json.decodeFromString<WearRouteState>(routeFile.readText())+ }.getOrNull()?.takeIf { it.active }++ private fun loadPosition(): WearPosition? = runCatching {+ WearMapsProtocol.json.decodeFromString<WearPosition>(positionFile.readText())+ }.getOrNull()++ private fun persist(file: File, text: String) {+ runCatching { file.writeText(text) }+ .onFailure { Log.status(TAG, "persist ${file.name} failed: ${it.message}") }+ }+}
maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapProjection.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapProjection.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapProjection.ktnew file mode 100644index 0000000000..d302c864c3--- /dev/null+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapProjection.kt@@ -0,0 +1,86 @@+package com.vayunmathur.maps.wear.domain++import kotlin.math.sqrt++/**+ * Pure north-up projection for the watch Canvas renderer.+ *+ * Coordinates are metres east/north of the snapshot centre. The view is+ * centred on [centerEastM]/[centerNorthM] (the snapshot centre, or the+ * user when following), scaled so the snapshot radius fits the smaller+ * viewport dimension, plus a pan offset in metres. North is up:+ * positive north metres map to smaller screen y. Rotation is not done+ * in v1 (a single Canvas rotate would make it cheap; labels/legibility+ * keep v1 north-up — see module AGENTS.md).+ */+data class WearMapProjection(+ val viewportWidthPx: Float,+ val viewportHeightPx: Float,+ val radiusM: Int,+ val centerEastM: Double = 0.0,+ val centerNorthM: Double = 0.0,+ val panEastM: Double = 0.0,+ val panNorthM: Double = 0.0,+ val zoom: Double = 1.0,+) {+ /** Pixels per metre: radius fits half the smaller viewport side, times [zoom]. */+ val pixelsPerMeter: Double+ get() = (minOf(viewportWidthPx, viewportHeightPx) / 2.0 / radiusM.coerceAtLeast(1)) * zoom++ /** Screen (x, y) in pixels for metres east/north of the snapshot centre. */+ fun project(eastM: Double, northM: Double): Pair<Float, Float> {+ val x = viewportWidthPx / 2.0 + (eastM - centerEastM + panEastM) * pixelsPerMeter+ val y = viewportHeightPx / 2.0 - (northM - centerNorthM + panNorthM) * pixelsPerMeter+ return x.toFloat() to y.toFloat()+ }++ /** Inverse of [project]: metres east/north under a screen point. */+ fun unproject(xPx: Float, yPx: Float): Pair<Double, Double> {+ val east = (xPx - viewportWidthPx / 2.0) / pixelsPerMeter + centerEastM - panEastM+ val north = (viewportHeightPx / 2.0 - yPx) / pixelsPerMeter + centerNorthM - panNorthM+ return east to north+ }++ /** True when metres (e/n) fall inside the snapshot square. */+ fun insideRegion(eastM: Double, northM: Double): Boolean =+ kotlin.math.abs(eastM) <= radiusM && kotlin.math.abs(northM) <= radiusM+}++/** Metres east/north of a snapshot's centre for an absolute E7 position. */+fun wearOffsetInSnapshot(snapshot: WearMapSnapshot, latE7: Int, lonE7: Int): Pair<Double, Double> {+ val originLat = snapshot.centerLatE7 / 1e7+ val originLon = snapshot.centerLonE7 / 1e7+ return wearMetersEast(originLat, originLon, lonE7 / 1e7) to+ wearMetersNorth(originLat, latE7 / 1e7)+}++/** Metres east/north of a snapshot's centre for a route-overlay point (route origin + quantized). */+fun wearRoutePointInSnapshot(+ snapshot: WearMapSnapshot,+ route: WearRouteState,+ dxUnits: Int,+ dyUnits: Int,+): Pair<Double, Double> {+ val snapshotLat = snapshot.centerLatE7 / 1e7+ val snapshotLon = snapshot.centerLonE7 / 1e7+ val routeLat = route.routeOriginLatE7 / 1e7+ val routeLon = route.routeOriginLonE7 / 1e7+ val originEast = wearMetersEast(snapshotLat, snapshotLon, routeLon)+ val originNorth = wearMetersNorth(snapshotLat, routeLat)+ return (originEast + wearDequantize(dxUnits)) to (originNorth + wearDequantize(dyUnits))+}++/** Distance (m) between an E7 position and a saved place, for the glance list. */+fun wearDistanceM(fromLatE7: Int, fromLonE7: Int, to: WearSavedPlace): Double {+ val dx = wearMetersEast(fromLatE7 / 1e7, fromLonE7 / 1e7, to.lonE7 / 1e7)+ val dy = wearMetersNorth(fromLatE7 / 1e7, to.latE7 / 1e7)+ return sqrt(dx * dx + dy * dy)+}++/** Route overlay lifecycle: an inactive state clears the overlay; an active one replaces it. */+fun wearApplyRouteState(current: WearRouteState?, incoming: WearRouteState): WearRouteState? =+ if (incoming.active) incoming else null++/** Stale when the snapshot is older than the protocol window; no snapshot is always stale. */+fun wearIsStale(snapshot: WearMapSnapshot?, nowMillis: Long): Boolean =+ snapshot == null || nowMillis - snapshot.generatedAtMillis > WearMapsProtocol.STALE_AFTER_MS
maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapsProtocol.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapsProtocol.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapsProtocol.ktnew file mode 100644index 0000000000..e971d947c3--- /dev/null+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapsProtocol.kt@@ -0,0 +1,196 @@+package com.vayunmathur.maps.wear.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import kotlin.math.cos++/**+ * Phone <-> watch protocol for the Wear OS Maps companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module (`:maps:wear`,+ * applicationId `com.vayunmathur.maps`) carries a copy of this file under+ * `com.vayunmathur.maps.wear.domain`. Change both copies together; each+ * side's unit tests pin the same golden JSON so a one-sided edit fails.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items: [REGION_PATH] phone -> watch (bounded vector snapshot of+ * the area around the user), [ROUTE_PATH] phone -> watch (navigation+ * overlay, or `active=false` to clear it), [POSITION_PATH] phone ->+ * watch (small frequent user position inside the current region) and+ * [WATCH_STATE_PATH] watch -> phone (what the watch last applied).+ * - Messages: [REQUEST_REGION_PATH] watch -> phone (ask for a fresh+ * region; delivery needs a live session, nothing wakes a dead process).+ *+ * What a snapshot contains — and what it honestly does not:+ * Coordinates are quantized metres east/north of the snapshot centre+ * ([QUANT_STEP_M] per unit, so round-trip error is at most half a step).+ * Lines carry roads/paths/water/buildings/route geometry *when the phone+ * has a cheap source for them*; points carry POIs from the offline index+ * and saved places. `:library:map` exposes no Kotlin geometry API for the+ * basemap's road/water/building linework (the Vulkan renderer decodes the+ * `.mamaps` tiles natively), so a phone build without such a source sets+ * [WearMapSnapshot.degraded] to name the missing kinds instead of faking+ * geometry. The watch renders whatever lines it is given.+ *+ * Position source is the PHONE. The watch does not run its own GPS in+ * this design (a watch fix would cost watch battery for a worse antenna+ * and would disagree with the phone map the user navigates by); the+ * phone's location manager / navigation session is the single source.+ */+object WearMapsProtocol {+ /** WearLink appId the phone requires in the peer handshake. */+ const val CAPABILITY = "maps_wear_companion"++ /** Data-item path (phone -> watch): the [WearMapSnapshot] JSON. */+ const val REGION_PATH = "/maps/region"++ /** Data-item path (phone -> watch): the [WearRouteState] JSON. */+ const val ROUTE_PATH = "/maps/route"++ /** Data-item path (phone -> watch): the [WearPosition] JSON. */+ const val POSITION_PATH = "/maps/position"++ /** Data-item path (watch -> phone): the [WearWatchState] JSON. */+ const val WATCH_STATE_PATH = "/maps/watch-state"++ /** Message path (watch -> phone): ask the phone to republish the region. */+ const val REQUEST_REGION_PATH = "/maps/request-region"++ /** Radius (m) of the square region a snapshot covers around its centre. */+ const val REGION_RADIUS_M = 600++ /** Metres per quantized coordinate unit (round-trip error <= half). */+ const val QUANT_STEP_M = 2.0++ /** Largest region JSON in UTF-8 bytes; extraction degrades to fit. */+ const val MAX_JSON_BYTES = 48_000++ /** Largest route JSON in UTF-8 bytes; route extraction decimates to fit. */+ const val MAX_ROUTE_JSON_BYTES = 24_000++ /** A snapshot older than this (watch clock vs [WearMapSnapshot.generatedAtMillis]) reads stale. */+ const val STALE_AFTER_MS = 90_000L++ /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+ val json: Json = Json { ignoreUnknownKeys = true }+}++/** Geometry kind of a [WearMapLine]; the watch strokes/fills by kind. */+@Serializable+enum class WearLineKind { ROAD, PATH, WATER, BUILDING, ROUTE }++/**+ * One simplified polyline/polygon, quantized metres east/north of the+ * snapshot (or route) origin as a flat `[dx, dy, dx, dy, ...]` list in+ * [WearMapsProtocol.QUANT_STEP_M] units. [closed] polygons fill.+ */+@Serializable+data class WearMapLine(+ val kind: WearLineKind,+ val pts: List<Int> = emptyList(),+ val closed: Boolean = false,+ val name: String = "",+)++/** One POI point, quantized metres east/north of the snapshot centre. */+@Serializable+data class WearMapPoint(+ /** Offline POI type id (phone `PoiCategories` numbering); -1 for saved. */+ val type: Int = 0,+ val name: String = "",+ val dx: Int = 0,+ val dy: Int = 0,+)++/** One saved place (absolute coords: the glance list needs distance, not just on-map position). */+@Serializable+data class WearSavedPlace(+ val name: String = "",+ val latE7: Int = 0,+ val lonE7: Int = 0,+)++/**+ * The phone's bounded vector snapshot for the watch ([WearMapsProtocol.REGION_PATH]).+ * Centre is E7 degrees; all geometry is quantized metres relative to it.+ */+@Serializable+data class WearMapSnapshot(+ val generatedAtMillis: Long = 0L,+ val centerLatE7: Int = 0,+ val centerLonE7: Int = 0,+ val radiusM: Int = WearMapsProtocol.REGION_RADIUS_M,+ val lines: List<WearMapLine> = emptyList(),+ val points: List<WearMapPoint> = emptyList(),+ val saved: List<WearSavedPlace> = emptyList(),+ /** True when the byte cap dropped or coarsened geometry. */+ val truncated: Boolean = false,+ /** Human-honest names of what is missing/coarser, e.g. "roads", "detail". Empty = full. */+ val degraded: List<String> = emptyList(),+ /** User bearing (degrees clockwise from north) at publish, -1 = unknown. */+ val userBearingDeg: Int = -1,+)++/** The phone's current user position ([WearMapsProtocol.POSITION_PATH]); -1 bearing = unknown. */+@Serializable+data class WearPosition(+ val latE7: Int = 0,+ val lonE7: Int = 0,+ val bearingDeg: Int = -1,+ val atMillis: Long = 0L,+)++/** One maneuver in the route-detail list. */+@Serializable+data class WearManeuver(+ val text: String = "",+ /** Maneuver kind name from the phone router (e.g. TURN_LEFT); may be empty. */+ val kind: String = "",+ /** Cumulative distance from route start (m) at which this maneuver occurs. */+ val distanceFromStartM: Int = 0,+)++/**+ * Navigation overlay for the watch ([WearMapsProtocol.ROUTE_PATH]).+ * `active=false` is the explicit clear: route ended/arrived/stopped.+ * [routePts] are quantized metres relative to ([routeOriginLatE7],+ * [routeOriginLonE7]), independent of any region snapshot's centre, so a+ * region republish can never misalign the overlay.+ */+@Serializable+data class WearRouteState(+ val active: Boolean = false,+ val destinationName: String = "",+ val routeOriginLatE7: Int = 0,+ val routeOriginLonE7: Int = 0,+ val routePts: List<Int> = emptyList(),+ val maneuvers: List<WearManeuver> = emptyList(),+ val nextText: String = "",+ val distanceToNextM: Int = 0,+ val distanceRemainingM: Int = 0,+ val etaEpochMs: Long = 0L,+ val generatedAtMillis: Long = 0L,+)++/** What the watch last applied, published at [WearMapsProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearWatchState(+ val appliedGeneratedAtMillis: Long = 0L,+ val hasRegion: Boolean = false,+ val routeActive: Boolean = false,+)++/** Metres east of [originLon] for [lon] at [originLat] (equirectangular; fine at region scale). */+fun wearMetersEast(originLat: Double, originLon: Double, lon: Double): Double =+ (lon - originLon) * 111_320.0 * cos(Math.toRadians(originLat))++/** Metres north of [originLat] for [lat]. */+fun wearMetersNorth(originLat: Double, lat: Double): Double = (lat - originLat) * 110_540.0++/** Quantize metres to [WearMapsProtocol.QUANT_STEP_M] units. */+fun wearQuantize(meters: Double): Int = Math.round(meters / WearMapsProtocol.QUANT_STEP_M).toInt()++/** Inverse of [wearQuantize]. */+fun wearDequantize(units: Int): Double = units * WearMapsProtocol.QUANT_STEP_M
maps-wear/src/main/java/com/vayunmathur/maps/wear/sync/WearLinkBridge.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/sync/WearLinkBridge.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..4d07b41b39--- /dev/null+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/sync/WearLinkBridge.kt@@ -0,0 +1,81 @@+package com.vayunmathur.maps.wear.sync++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import com.vayunmathur.maps.wear.data.WearMapsStore+import com.vayunmathur.maps.wear.domain.WearMapSnapshot+import com.vayunmathur.maps.wear.domain.WearMapsProtocol+import com.vayunmathur.maps.wear.domain.WearPosition+import com.vayunmathur.maps.wear.domain.WearRouteState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Watch side of WearLink for Maps: region/route/position data items land+ * in [WearMapsStore], watch state goes back as a data item, and a fresh+ * region is requested by message. Delivery is bound to this process+ * being alive; the persisted store covers cold starts and link loss.+ */+object WearLinkBridge {+ private const val TAG = "WearLinkBridge"+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ @Volatile+ private var node: WearLinkNode? = null++ fun get(context: Context): WearLinkNode {+ val appContext = context.applicationContext+ return node ?: synchronized(this) {+ node ?: create(appContext).also { node = it }+ }+ }++ private fun create(context: Context): WearLinkNode {+ val store = WearMapsStore.get(context)+ val listener = object : WearLinkListener {+ override fun onData(path: String, body: ByteArray) {+ val text = body.decodeToString()+ when (path) {+ WearMapsProtocol.REGION_PATH -> decode<WearMapSnapshot>(text)?.let(store::setSnapshot)+ WearMapsProtocol.ROUTE_PATH -> decode<WearRouteState>(text)?.let(store::setRoute)+ WearMapsProtocol.POSITION_PATH -> decode<WearPosition>(text)?.let(store::setPosition)+ }+ }+ }+ val created = WearLinkNode(context, WearMapsProtocol.CAPABILITY, listener)+ scope.launch {+ created.state.collect { linkState ->+ store.setConnected(linkState is WearLinkState.Connected)+ }+ }+ created.start()+ return created+ }++ private inline fun <reified T> decode(text: String): T? = runCatching {+ WearMapsProtocol.json.decodeFromString<T>(text)+ }.getOrElse {+ Log.status(TAG, "ignoring malformed data item")+ null+ }++ fun publishWatchState(context: Context) {+ val state = WearMapsStore.get(context).watchState()+ scope.launch {+ get(context).putData(+ WearMapsProtocol.WATCH_STATE_PATH,+ WearMapsProtocol.json.encodeToString(state).encodeToByteArray(),+ )+ }+ }++ /** Ask the phone for a fresh region; false when no session is live. */+ suspend fun requestRegion(context: Context): Boolean =+ get(context).sendMessage(WearMapsProtocol.REQUEST_REGION_PATH, ByteArray(0))+}
maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMainActivity.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMainActivity.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..fd65be5883--- /dev/null+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMainActivity.kt@@ -0,0 +1,48 @@+package com.vayunmathur.maps.wear.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.wear.compose.material.MaterialTheme+import com.vayunmathur.maps.wear.data.WearMapsStore+import com.vayunmathur.maps.wear.sync.WearLinkBridge++/**+ * Watch maps entry: the rendered map home, route detail and saved glance,+ * all from the locally stored snapshot so they work standalone (phone+ * absent, cold start) with stale/offline honesty.+ */+class WearMainActivity : ComponentActivity() {++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+ val store = WearMapsStore.get(this)+ WearLinkBridge.get(this)+ WearLinkBridge.publishWatchState(this)+ setContent {+ MaterialTheme {+ var route by remember { mutableStateOf<WearRoute>(WearRoute.Map) }+ when (route) {+ WearRoute.Map -> WearMapScreen(+ store = store,+ onOpenRoute = { route = WearRoute.RouteDetail },+ onOpenSaved = { route = WearRoute.Saved },+ )+ WearRoute.RouteDetail -> WearRouteDetailScreen(+ store = store,+ onBack = { route = WearRoute.Map },+ )+ WearRoute.Saved -> WearSavedScreen(+ store = store,+ onBack = { route = WearRoute.Map },+ )+ }+ }+ }+ }+}
maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMapCanvas.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMapCanvas.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMapCanvas.ktnew file mode 100644index 0000000000..c4f09e0968--- /dev/null+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMapCanvas.kt@@ -0,0 +1,142 @@+package com.vayunmathur.maps.wear.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.PathEffect+import androidx.compose.ui.graphics.drawscope.Stroke+import com.vayunmathur.maps.wear.domain.WearLineKind+import com.vayunmathur.maps.wear.domain.WearMapProjection+import com.vayunmathur.maps.wear.domain.WearMapSnapshot+import com.vayunmathur.maps.wear.domain.WearPosition+import com.vayunmathur.maps.wear.domain.WearRouteState+import com.vayunmathur.maps.wear.domain.wearDequantize+import com.vayunmathur.maps.wear.domain.wearOffsetInSnapshot+import com.vayunmathur.maps.wear.domain.wearRoutePointInSnapshot+import kotlin.math.cos+import kotlin.math.sin++private val LandColor = Color(0xFF101613)+private val WaterColor = Color(0xFF1D4E6B)+private val BuildingColor = Color(0xFF394149)+private val RoadColor = Color(0xFF9AA3AD)+private val PathColor = Color(0xFF6E7B6E)+private val RouteColor = Color(0xFF4DA3FF)+private val PoiColor = Color(0xFFFFC46B)+private val SavedColor = Color(0xFF7EE081)+private val UserColor = Color(0xFF4DA3FF)++/**+ * Lightweight Canvas renderer for one phone-supplied vector snapshot:+ * no tile stack, no map library — just projected polylines/polygons,+ * POI dots, the route overlay and the user puck. North-up in v1.+ * Draw order: water/buildings (fills), roads/paths, route, points, user.+ * Follows the user when a position is known, else centres the snapshot.+ */+@Composable+fun WearMapCanvas(+ snapshot: WearMapSnapshot,+ route: WearRouteState?,+ position: WearPosition?,+) {+ Canvas(Modifier.fillMaxSize()) {+ val userOffset = position?.let { wearOffsetInSnapshot(snapshot, it.latE7, it.lonE7) }+ val projection = WearMapProjection(+ viewportWidthPx = size.width,+ viewportHeightPx = size.height,+ radiusM = snapshot.radiusM,+ centerEastM = userOffset?.first ?: 0.0,+ centerNorthM = userOffset?.second ?: 0.0,+ )+ drawRect(LandColor)+ fun pathOf(flat: List<Int>, toMetres: (Int, Int) -> Pair<Double, Double>): Path {+ val path = Path()+ for (i in flat.indices step 2) {+ if (i + 1 >= flat.size) break+ val (east, north) = toMetres(flat[i], flat[i + 1])+ val (x, y) = projection.project(east, north)+ if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)+ }+ return path+ }+ val snapshotPts = { dx: Int, dy: Int -> wearDequantize(dx) to wearDequantize(dy) }+ // Fills first, then strokes in kind-priority order.+ for (line in snapshot.lines.filter { it.closed }) {+ val color = if (line.kind == WearLineKind.WATER) WaterColor else BuildingColor+ drawPath(pathOf(line.pts, snapshotPts), color)+ }+ for (kind in listOf(WearLineKind.WATER, WearLineKind.ROAD, WearLineKind.PATH)) {+ for (line in snapshot.lines.filter { !it.closed && it.kind == kind }) {+ drawPath(+ pathOf(line.pts, snapshotPts),+ color = when (kind) {+ WearLineKind.WATER -> WaterColor+ WearLineKind.ROAD -> RoadColor+ else -> PathColor+ },+ style = Stroke(+ width = if (kind == WearLineKind.ROAD) 3f else 2f,+ pathEffect = if (kind == WearLineKind.PATH) {+ PathEffect.dashPathEffect(floatArrayOf(6f, 6f))+ } else {+ null+ },+ ),+ )+ }+ }+ // Snapshot-embedded route lines, then the live route overlay (fresher).+ for (line in snapshot.lines.filter { !it.closed && it.kind == WearLineKind.ROUTE }) {+ drawPath(pathOf(line.pts, snapshotPts), RouteColor, style = Stroke(width = 5f))+ }+ if (route?.active == true && route.routePts.size >= 4) {+ val routePath = pathOf(route.routePts) { dx, dy ->+ wearRoutePointInSnapshot(snapshot, route, dx, dy)+ }+ drawPath(routePath, Color.White, style = Stroke(width = 7f))+ drawPath(routePath, RouteColor, style = Stroke(width = 5f))+ }+ for (point in snapshot.points) {+ val (x, y) = projection.project(wearDequantize(point.dx), wearDequantize(point.dy))+ drawCircle(PoiColor, radius = 3.5f, center = Offset(x, y))+ }+ for (place in snapshot.saved) {+ val (east, north) = wearOffsetInSnapshot(snapshot, place.latE7, place.lonE7)+ val (x, y) = projection.project(east, north)+ drawCircle(SavedColor, radius = 4.5f, center = Offset(x, y))+ }+ // User puck last, with a bearing cone when the phone reported one.+ val (ux, uy) = if (userOffset != null) {+ projection.project(userOffset.first, userOffset.second)+ } else {+ projection.project(0.0, 0.0)+ }+ val bearing = position?.bearingDeg ?: snapshot.userBearingDeg+ if (bearing >= 0) {+ val rad = Math.toRadians(bearing.toDouble())+ val cone = Path().apply {+ moveTo(ux, uy)+ lineTo(+ ux + 26f * sin(rad - 0.35).toFloat(),+ uy - 26f * cos(rad - 0.35).toFloat(),+ )+ lineTo(+ ux + 26f * sin(rad + 0.35).toFloat(),+ uy - 26f * cos(rad + 0.35).toFloat(),+ )+ close()+ }+ drawPath(cone, UserColor.copy(alpha = 0.35f))+ }+ drawCircle(Color.White, radius = 8f, center = Offset(ux, uy))+ drawCircle(UserColor, radius = 6f, center = Offset(ux, uy))+ // Scale bar: 100 m in the bottom-left, north marker top-right.+ val scalePx = (100.0 * projection.pixelsPerMeter).toFloat()+ drawLine(Color.White, Offset(12f, size.height - 12f), Offset(12f + scalePx, size.height - 12f), 3f)+ drawCircle(Color.DarkGray, radius = 13f, center = Offset(size.width - 18f, 18f))+ }+}
maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMapScreen.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMapScreen.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMapScreen.ktnew file mode 100644index 0000000000..c9ebf9dc3f--- /dev/null+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearMapScreen.kt@@ -0,0 +1,131 @@+package com.vayunmathur.maps.wear.ui++import androidx.compose.foundation.layout.Box+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.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.material.Button+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.maps.wear.R+import com.vayunmathur.maps.wear.data.WearMapsStore+import com.vayunmathur.maps.wear.domain.wearIsStale+import com.vayunmathur.maps.wear.sync.WearLinkBridge+import kotlinx.coroutines.launch++/**+ * Map home page: the rendered region with the user (and route, when the+ * phone is navigating) on it. Honesty labels sit under the map: offline+ * when the link is down, stale when the snapshot aged out, and a limited-+ * detail note when the phone flagged missing linework.+ */+@Composable+fun WearMapScreen(+ store: WearMapsStore,+ onOpenRoute: () -> Unit,+ onOpenSaved: () -> Unit,+) {+ val snapshot by store.snapshot.collectAsState()+ val route by store.route.collectAsState()+ val position by store.position.collectAsState()+ val connected by store.connected.collectAsState()+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ var note by remember { mutableStateOf<String?>(null) }+ val requestedText = stringResource(R.string.wear_requested)+ val noPhoneText = stringResource(R.string.wear_no_phone)++ Box(Modifier.fillMaxSize()) {+ val current = snapshot+ if (current == null) {+ Text(+ stringResource(R.string.wear_no_region),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(16.dp).align(Alignment.Center),+ )+ } else {+ WearMapCanvas(snapshot = current, route = route, position = position)+ Column(Modifier.align(Alignment.TopCenter).padding(top = 18.dp)) {+ if (route?.active == true) {+ Text(+ route!!.nextText.ifBlank { route!!.destinationName },+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp),+ maxLines = 2,+ )+ Text(+ "${route!!.distanceToNextM} m · ${(route!!.distanceRemainingM / 1000.0)} km left",+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth(),+ )+ }+ }+ Column(Modifier.align(Alignment.BottomCenter).padding(bottom = 26.dp)) {+ val stale = wearIsStale(current, System.currentTimeMillis())+ when {+ !connected -> Text(+ stringResource(R.string.wear_offline),+ style = MaterialTheme.typography.caption2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth(),+ )+ stale -> Text(+ stringResource(R.string.wear_stale),+ style = MaterialTheme.typography.caption2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth(),+ )+ }+ if (current.degraded.isNotEmpty()) {+ Text(+ stringResource(R.string.wear_limited_detail),+ style = MaterialTheme.typography.caption2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth(),+ )+ }+ note?.let {+ Text(+ it,+ style = MaterialTheme.typography.caption2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth(),+ )+ }+ }+ }+ Row(Modifier.align(Alignment.BottomCenter).padding(bottom = 2.dp)) {+ Button(onClick = onOpenRoute, modifier = Modifier.padding(end = 4.dp)) {+ Text(stringResource(R.string.wear_route), maxLines = 1)+ }+ Button(onClick = onOpenSaved, modifier = Modifier.padding(end = 4.dp)) {+ Text(stringResource(R.string.wear_saved), maxLines = 1)+ }+ Button(onClick = {+ scope.launch {+ note = if (WearLinkBridge.requestRegion(context)) requestedText else noPhoneText+ }+ }) {+ Text(stringResource(R.string.wear_request_region), maxLines = 1)+ }+ }+ }+}
maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearRoute.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearRoute.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearRoute.ktnew file mode 100644index 0000000000..c3fc4fbd92--- /dev/null+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearRoute.kt@@ -0,0 +1,13 @@+package com.vayunmathur.maps.wear.ui++/** Watch navigation destinations mirroring the phone IA: map home, route detail, saved glance. */+sealed interface WearRoute {+ /** The rendered map (home). */+ data object Map : WearRoute++ /** Maneuver list for the phone's active route. */+ data object RouteDetail : WearRoute++ /** Saved places glance (name + distance; the phone has no Home/Work). */+ data object Saved : WearRoute+}
maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearRouteDetailScreen.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearRouteDetailScreen.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearRouteDetailScreen.ktnew file mode 100644index 0000000000..e245b15537--- /dev/null+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearRouteDetailScreen.kt@@ -0,0 +1,79 @@+package com.vayunmathur.maps.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.maps.wear.R+import com.vayunmathur.maps.wear.data.WearMapsStore++/** Route detail page: next maneuver plus the phone's maneuver list, or the no-route honesty. */+@Composable+fun WearRouteDetailScreen(+ store: WearMapsStore,+ onBack: () -> Unit,+) {+ val route by store.route.collectAsState()+ val listState = rememberScalingLazyListState()+ ScalingLazyColumn(state = listState) {+ item {+ Text(+ stringResource(R.string.wear_maneuvers),+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ val current = route+ if (current?.active != true) {+ item {+ Text(+ stringResource(R.string.wear_no_route),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else {+ if (current.destinationName.isNotBlank()) {+ item {+ Text(+ current.destinationName,+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ }+ items(current.maneuvers) { maneuver ->+ Chip(+ onClick = {},+ label = { Text(maneuver.text.ifBlank { maneuver.kind }, maxLines = 2) },+ secondaryLabel = { Text("${maneuver.distanceFromStartM} m", maxLines = 1) },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+ item {+ Chip(+ onClick = onBack,+ label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+ colors = ChipDefaults.primaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+}
maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearSavedScreen.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearSavedScreen.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearSavedScreen.ktnew file mode 100644index 0000000000..b3e87b2216--- /dev/null+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/ui/WearSavedScreen.kt@@ -0,0 +1,83 @@+package com.vayunmathur.maps.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.maps.wear.R+import com.vayunmathur.maps.wear.data.WearMapsStore+import com.vayunmathur.maps.wear.domain.wearDistanceM++/**+ * Saved places glance: name + distance from the user (phone position, or+ * the region centre when no fix yet). The phone has no Home/Work concept+ * and no watch ETA is invented — distance only.+ */+@Composable+fun WearSavedScreen(+ store: WearMapsStore,+ onBack: () -> Unit,+) {+ val snapshot by store.snapshot.collectAsState()+ val position by store.position.collectAsState()+ val listState = rememberScalingLazyListState()+ ScalingLazyColumn(state = listState) {+ item {+ Text(+ stringResource(R.string.wear_saved),+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ val places = snapshot?.saved.orEmpty()+ if (places.isEmpty()) {+ item {+ Text(+ stringResource(R.string.wear_no_saved),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else {+ val fromLat = position?.latE7 ?: snapshot!!.centerLatE7+ val fromLon = position?.lonE7 ?: snapshot!!.centerLonE7+ items(places) { place ->+ val meters = wearDistanceM(fromLat, fromLon, place)+ Chip(+ onClick = {},+ label = { Text(place.name, maxLines = 1) },+ secondaryLabel = {+ Text(+ if (meters >= 1000) "%.1f km".format(meters / 1000.0) else "${meters.toInt()} m",+ maxLines = 1,+ )+ },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+ item {+ Chip(+ onClick = onBack,+ label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+ colors = ChipDefaults.primaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+}
maps-wear/src/main/res/values/colors.xml
diff --git a/maps-wear/src/main/res/values/colors.xml b/maps-wear/src/main/res/values/colors.xmlnew file mode 100644index 0000000000..bfc7025d71--- /dev/null+++ b/maps-wear/src/main/res/values/colors.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Background for the generated adaptive launcher icon (see LauncherIconGen). -->+<resources>+ <color name="ic_launcher_background">#FFFFFF</color>+</resources>
maps-wear/src/main/res/values/strings.xml
diff --git a/maps-wear/src/main/res/values/strings.xml b/maps-wear/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..4c476d7c80--- /dev/null+++ b/maps-wear/src/main/res/values/strings.xml@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">Maps</string>+ <string name="wear_no_region">No map synced yet. Open Maps on your phone to sync this watch.</string>+ <string name="wear_stale">Stale · last map from your phone</string>+ <string name="wear_offline">Offline · showing the last map</string>+ <string name="wear_limited_detail">Road detail stays on your phone</string>+ <string name="wear_request_region">Update map</string>+ <string name="wear_requested">Asked your phone for a fresh map</string>+ <string name="wear_no_phone">Phone not reachable — showing the last map</string>+ <string name="wear_route">Route</string>+ <string name="wear_saved">Saved</string>+ <string name="wear_back">Back</string>+ <string name="wear_no_route">No route on your phone. Start navigation there and it appears here.</string>+ <string name="wear_no_saved">No saved places synced yet.</string>+ <string name="wear_maneuvers">Maneuvers</string>+</resources>
maps-wear/src/test/java/com/vayunmathur/maps/wear/domain/WearMapsProtocolTest.kt
diff --git a/maps-wear/src/test/java/com/vayunmathur/maps/wear/domain/WearMapsProtocolTest.kt b/maps-wear/src/test/java/com/vayunmathur/maps/wear/domain/WearMapsProtocolTest.ktnew file mode 100644index 0000000000..d5fe16360c--- /dev/null+++ b/maps-wear/src/test/java/com/vayunmathur/maps/wear/domain/WearMapsProtocolTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.maps.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearMapsProtocolTest {++ @Test+ fun goldenSnapshotJson() {+ // Must match the phone copy's golden string byte-for-byte.+ val snapshot = WearMapSnapshot(+ generatedAtMillis = 1_000L,+ centerLatE7 = 340_522_350,+ centerLonE7 = -1_182_436_830,+ lines = listOf(WearMapLine(WearLineKind.ROAD, listOf(0, 0, 10, 0))),+ points = listOf(WearMapPoint(0, "Cafe", 5, -3)),+ )+ assertEquals(+ """{"generatedAtMillis":1000,"centerLatE7":340522350,"centerLonE7":-1182436830,""" ++ """"lines":[{"kind":"ROAD","pts":[0,0,10,0]}],""" ++ """"points":[{"name":"Cafe","dx":5,"dy":-3}]}""",+ WearMapsProtocol.json.encodeToString(snapshot),+ )+ }++ @Test+ fun snapshotAndRouteRoundTrip() {+ val snapshot = WearMapSnapshot(9L, 10, 20, saved = listOf(WearSavedPlace("Home", 1, 2)))+ assertEquals(+ snapshot,+ WearMapsProtocol.json.decodeFromString<WearMapSnapshot>(+ WearMapsProtocol.json.encodeToString(snapshot),+ ),+ )+ val route = WearRouteState(active = true, destinationName = "Work", routePts = listOf(0, 0, 5, 5))+ assertEquals(+ route,+ WearMapsProtocol.json.decodeFromString<WearRouteState>(+ WearMapsProtocol.json.encodeToString(route),+ ),+ )+ }++ @Test+ fun quantizationRoundTripWithinHalfStep() {+ for (meters in listOf(0.0, 1.0, 3.0, 57.0, -123.0, 599.0)) {+ val back = wearDequantize(wearQuantize(meters))+ assertTrue(kotlin.math.abs(back - meters) <= WearMapsProtocol.QUANT_STEP_M / 2 + 1e-9)+ }+ }++ @Test+ fun projectionCentersNorthUpAndFitsRadius() {+ val projection = WearMapProjection(viewportWidthPx = 400f, viewportHeightPx = 400f, radiusM = 600)+ assertEquals(200f to 200f, projection.project(0.0, 0.0))+ // North is up: +north metres -> smaller y, same x.+ val (nx, ny) = projection.project(0.0, 300.0)+ assertEquals(200f, nx)+ assertTrue(ny < 200f)+ // East edge of the region lands on the viewport edge.+ val (ex, _) = projection.project(600.0, 0.0)+ assertEquals(400f, ex)+ assertTrue(projection.insideRegion(600.0, -600.0))+ assertFalse(projection.insideRegion(601.0, 0.0))+ }++ @Test+ fun projectionRoundTripAndPanAndFollow() {+ val base = WearMapProjection(viewportWidthPx = 300f, viewportHeightPx = 400f, radiusM = 600)+ val (x, y) = base.project(120.0, -80.0)+ val (east, north) = base.unproject(x, y)+ assertTrue(kotlin.math.abs(east - 120.0) < 1e-6 && kotlin.math.abs(north + 80.0) < 1e-6)+ // Following the user recentres: user offset projects to viewport centre.+ val follow = base.copy(centerEastM = 120.0, centerNorthM = -80.0)+ assertEquals(150f to 200f, follow.project(120.0, -80.0))+ // Pan shifts everything by the pan amount.+ val panned = base.copy(panEastM = 50.0)+ val (px, _) = panned.project(0.0, 0.0)+ assertTrue(px > 150f)+ }++ @Test+ fun routePointConversionAlignsOrigins() {+ val snapshot = WearMapSnapshot(centerLatE7 = 0, centerLonE7 = 0, radiusM = 600)+ val route = WearRouteState(+ active = true,+ routeOriginLatE7 = 0,+ routeOriginLonE7 = (0.001 * 1e7).toInt(), // ~111 m east+ )+ val (east, north) = wearRoutePointInSnapshot(snapshot, route, dxUnits = 0, dyUnits = 0)+ assertTrue(east in 100.0..125.0 && north == 0.0, "east=$east")+ // A route with the same origin as the snapshot maps 1:1 after dequantize.+ val same = wearRoutePointInSnapshot(snapshot, route.copy(routeOriginLonE7 = 0), 10, -5)+ assertEquals(20.0 to -10.0, same)+ }++ @Test+ fun staleAfterWindowAndWhenMissing() {+ val snapshot = WearMapSnapshot(generatedAtMillis = 1_000L)+ assertFalse(wearIsStale(snapshot, 1_000L + WearMapsProtocol.STALE_AFTER_MS))+ assertTrue(wearIsStale(snapshot, 1_001L + WearMapsProtocol.STALE_AFTER_MS))+ assertTrue(wearIsStale(null, 0L))+ }++ @Test+ fun routeOverlayLifecycle() {+ val active = WearRouteState(active = true, destinationName = "Work", nextText = "Turn left")+ val applied = wearApplyRouteState(null, active)+ assertEquals(active, applied)+ // A newer active state replaces; an inactive state clears and stays cleared.+ val newer = active.copy(nextText = "Turn right")+ assertEquals(newer, wearApplyRouteState(applied, newer))+ assertEquals(null, wearApplyRouteState(newer, WearRouteState(active = false)))+ assertEquals(null, wearApplyRouteState(null, WearRouteState(active = false)))+ }++ @Test+ fun savedDistanceUsesUserPosition() {+ val home = WearSavedPlace("Home", latE7 = 0, lonE7 = (0.01 * 1e7).toInt()) // ~1.1 km east+ val distance = wearDistanceM(0, 0, home)+ assertTrue(distance in 1_000.0..1_200.0, "distance=$distance")+ }+}
maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex e10eca33e4..0cd0b7ec52 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -131,6 +131,11 @@ dependencies { // WorkManager: the map-overlay check worker outlives the settings screen. implementation(project(":library:work")) + // Phone side of the Wear OS companion (platform/WearMapsSync): region+ // snapshot + route overlay to :maps:wear, which shares this app's+ // applicationId and signing certificate.+ implementation(project(":library:wearlink"))+ // Manifest JSON parsing (pure JVM: unit-testable, unlike org.json). implementation(libs.kotlinx.serialization.json)
maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex c891e01602..569af7f163 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -86,6 +86,10 @@ class MainActivity : MaActivity() { override fun onCreateBeforeContent() { // FIRST_PARTY: data.maproj.org tiles + amenities + api.maproj.org -> ISRG+GTS NetworkClient.init(this, TrustBundle.FIRST_PARTY)+ // Wear watch companion (region snapshot + route overlay over+ // WearLink; app-lifecycle-bound, see platform/WearMapsSync).+ com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+ com.vayunmathur.maps.platform.WearMapsSync.start(this) intentLauncher = IntentLauncher(this) // Deferred off the startup path: neither the legacy-file delete nor // the overlay-schedule check gates the first frame (the theme reads
maps/src/main/java/com/vayunmathur/maps/domain/WearMapRegion.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/domain/WearMapRegion.kt b/maps/src/main/java/com/vayunmathur/maps/domain/WearMapRegion.ktnew file mode 100644index 0000000000..229962c341--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/domain/WearMapRegion.kt@@ -0,0 +1,337 @@+package com.vayunmathur.maps.domain++import com.vayunmathur.library.map.GeoPoint+import kotlinx.serialization.encodeToString+import kotlin.math.abs+import kotlin.math.hypot+import kotlin.math.sqrt++/**+ * Pure region extraction for the watch snapshot (see [WearMapsProtocol]).+ *+ * Input is whatever vector geometry the phone has cheaply: raw lines+ * (roads/paths/water/buildings, in that priority) and raw POI points.+ * Extraction, in order: project to metres around the centre, clip to the+ * region square, Douglas-Peucker simplify, quantize, then enforce+ * [WearMapsProtocol.MAX_JSON_BYTES] by an honest degradation ladder+ * (coarser simplification, then dropping low-priority kinds, then fewer+ * points) — [WearMapSnapshot.truncated]/[WearMapSnapshot.degraded] say+ * exactly what was lost. Geometry is never invented: kinds the caller+ * supplied none of are named in `degraded` by the caller, not here.+ */++/** One unsimplified line in geographic coords, as a caller supplies it. */+data class WearRawLine(+ val kind: WearLineKind,+ val points: List<GeoPoint>,+ val closed: Boolean = false,+ val name: String = "",+)++/** One POI in geographic coords, as a caller supplies it. */+data class WearRawPoint(+ val type: Int,+ val name: String,+ val point: GeoPoint,+)++/** Keep priority when the byte cap bites: route/road survive longest. */+private val LINE_PRIORITY = listOf(+ WearLineKind.ROUTE, WearLineKind.ROAD, WearLineKind.PATH,+ WearLineKind.WATER, WearLineKind.BUILDING,+)++private data class MeterPt(val x: Double, val y: Double)++/** Douglas-Peucker simplification in metre space; endpoints always kept. */+fun simplifyWearLine(points: List<GeoPoint>, origin: GeoPoint, toleranceM: Double): List<GeoPoint> {+ if (points.size <= 2) return points+ val meter = points.map {+ MeterPt(+ wearMetersEast(origin.latitude, origin.longitude, it.longitude),+ wearMetersNorth(origin.latitude, it.latitude),+ )+ }+ val keep = BooleanArray(points.size)+ keep[0] = true+ keep[points.lastIndex] = true+ simplifyRange(meter, 0, points.lastIndex, toleranceM, keep)+ return points.filterIndexed { i, _ -> keep[i] }+}++private fun simplifyRange(pts: List<MeterPt>, first: Int, last: Int, tol: Double, keep: BooleanArray) {+ if (last <= first + 1) return+ var worst = -1+ var worstDist = tol+ for (i in first + 1 until last) {+ val d = pointSegmentDistance(pts[i], pts[first], pts[last])+ if (d > worstDist) {+ worstDist = d+ worst = i+ }+ }+ if (worst < 0) return+ keep[worst] = true+ simplifyRange(pts, first, worst, tol, keep)+ simplifyRange(pts, worst, last, tol, keep)+}++private fun pointSegmentDistance(p: MeterPt, a: MeterPt, b: MeterPt): Double {+ val dx = b.x - a.x+ val dy = b.y - a.y+ val lenSq = dx * dx + dy * dy+ if (lenSq == 0.0) return hypot(p.x - a.x, p.y - a.y)+ val t = (((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq).coerceIn(0.0, 1.0)+ return hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))+}++/** Clip one open polyline (metre space) to the square `[-radius, radius]^2`, splitting runs. */+private fun clipOpenLine(pts: List<MeterPt>, radius: Double): List<List<MeterPt>> {+ val runs = mutableListOf<List<MeterPt>>()+ var current = mutableListOf<MeterPt>()+ fun flush() {+ if (current.size >= 2) runs += current+ current = mutableListOf()+ }+ for (i in 0 until pts.size - 1) {+ val clipped = clipSegment(pts[i], pts[i + 1], radius)+ if (clipped == null) {+ flush()+ continue+ }+ val (a, b) = clipped+ if (current.isEmpty() || current.last() != a) {+ flush()+ current += a+ }+ current += b+ }+ flush()+ return runs+}++/** Liang-Barsky segment/square clip; null when fully outside. */+private fun clipSegment(a: MeterPt, b: MeterPt, r: Double): Pair<MeterPt, MeterPt>? {+ var t0 = 0.0+ var t1 = 1.0+ val dx = b.x - a.x+ val dy = b.y - a.y+ // p/q for the four square edges.+ val edges = arrayOf(+ doubleArrayOf(-dx, a.x + r), doubleArrayOf(dx, r - a.x),+ doubleArrayOf(-dy, a.y + r), doubleArrayOf(dy, r - a.y),+ )+ for ((p, q) in edges) {+ if (p == 0.0) {+ if (q < 0) return null+ continue+ }+ val t = q / p+ if (p < 0) {+ if (t > t1) return null+ if (t > t0) t0 = t+ } else {+ if (t < t0) return null+ if (t < t1) t1 = t+ }+ }+ if (t0 > t1) return null+ return MeterPt(a.x + t0 * dx, a.y + t0 * dy) to MeterPt(a.x + t1 * dx, a.y + t1 * dy)+}++/** Quantized flat `[dx, dy, ...]` for metre points. */+private fun quantizeFlat(pts: List<MeterPt>): List<Int> =+ pts.flatMap { listOf(wearQuantize(it.x), wearQuantize(it.y)) }++private fun toMeterPts(points: List<GeoPoint>, originLat: Double, originLon: Double): List<MeterPt> =+ points.map {+ MeterPt(+ wearMetersEast(originLat, originLon, it.longitude),+ wearMetersNorth(originLat, it.latitude),+ )+ }++/**+ * Builds a byte-capped snapshot. [missingKinds] names geometry kinds the+ * caller could not supply at all (honesty, e.g. basemap linework); they+ * are merged into [WearMapSnapshot.degraded] verbatim.+ */+fun buildWearMapSnapshot(+ center: GeoPoint,+ generatedAtMillis: Long,+ rawLines: List<WearRawLine>,+ rawPoints: List<WearRawPoint>,+ saved: List<WearSavedPlace> = emptyList(),+ userBearingDeg: Int = -1,+ missingKinds: List<String> = emptyList(),+ radiusM: Int = WearMapsProtocol.REGION_RADIUS_M,+): WearMapSnapshot {+ val tolerances = listOf(4.0, 8.0, 16.0, 32.0)+ val pointCaps = listOf(80, 60, 40, 20)+ var droppedKinds = emptyList<WearLineKind>()+ for (step in tolerances.indices) {+ val snapshot = buildAt(+ center, generatedAtMillis, rawLines, rawPoints, saved,+ userBearingDeg, missingKinds, radiusM,+ toleranceM = tolerances[step], pointCap = pointCaps[step],+ droppedKinds = droppedKinds,+ coarsened = step > 0,+ )+ if (encodedSize(snapshot) <= WearMapsProtocol.MAX_JSON_BYTES) return snapshot+ // Next rung: also drop the lowest-priority remaining line kind.+ val remaining = LINE_PRIORITY.filter { k -> rawLines.any { it.kind == k } && k !in droppedKinds }+ if (remaining.isNotEmpty()) droppedKinds = droppedKinds + remaining.last()+ }+ // Final rung: coarsest build with whatever kinds remain; flagged truncated.+ return buildAt(+ center, generatedAtMillis, rawLines, rawPoints, saved,+ userBearingDeg, missingKinds, radiusM,+ toleranceM = tolerances.last(), pointCap = pointCaps.last(),+ droppedKinds = droppedKinds, coarsened = true,+ )+}++private fun encodedSize(snapshot: WearMapSnapshot): Int =+ WearMapsProtocol.json.encodeToString(snapshot).encodeToByteArray().size++private fun buildAt(+ center: GeoPoint,+ generatedAtMillis: Long,+ rawLines: List<WearRawLine>,+ rawPoints: List<WearRawPoint>,+ saved: List<WearSavedPlace>,+ userBearingDeg: Int,+ missingKinds: List<String>,+ radiusM: Int,+ toleranceM: Double,+ pointCap: Int,+ droppedKinds: List<WearLineKind>,+ coarsened: Boolean,+): WearMapSnapshot {+ val r = radiusM.toDouble()+ val lines = mutableListOf<WearMapLine>()+ for (raw in rawLines) {+ if (raw.kind in droppedKinds || raw.points.size < 2) continue+ val simplified = simplifyWearLine(raw.points, center, toleranceM)+ val meter = toMeterPts(simplified, center.latitude, center.longitude)+ if (raw.closed) {+ val inside = meter.filter { abs(it.x) <= r && abs(it.y) <= r }+ if (inside.size >= 3) {+ lines += WearMapLine(raw.kind, quantizeFlat(inside), closed = true, name = raw.name)+ }+ } else {+ for (run in clipOpenLine(meter, r)) {+ lines += WearMapLine(raw.kind, quantizeFlat(run), name = raw.name)+ }+ }+ }+ // Nearest points survive the cap (the watch is a glance, centre-first).+ val points = rawPoints+ .map { p ->+ val x = wearMetersEast(center.latitude, center.longitude, p.point.longitude)+ val y = wearMetersNorth(center.latitude, p.point.latitude)+ Triple(p, x, y)+ }+ .filter { abs(it.second) <= r && abs(it.third) <= r }+ .sortedBy { it.second * it.second + it.third * it.third }+ .take(pointCap)+ .map { (p, x, y) -> WearMapPoint(p.type, p.name, wearQuantize(x), wearQuantize(y)) }+ val degraded = buildList {+ addAll(missingKinds)+ if (coarsened) add("detail")+ droppedKinds.forEach { add(it.name.lowercase()) }+ }+ return WearMapSnapshot(+ generatedAtMillis = generatedAtMillis,+ centerLatE7 = (center.latitude * 1e7).toInt(),+ centerLonE7 = (center.longitude * 1e7).toInt(),+ radiusM = radiusM,+ lines = lines,+ points = points,+ saved = saved,+ truncated = coarsened || droppedKinds.isNotEmpty() || points.size < rawPoints.size,+ degraded = degraded.distinct(),+ userBearingDeg = userBearingDeg,+ )+}++/**+ * Movement hysteresis: republish only when the user is in the outer band+ * of the current snapshot, so walking around the centre does not thrash+ * the link, and leaving the region always republishes.+ */+object WearRegionHysteresis {+ /** Fraction of the radius beyond which a fix triggers a republish. */+ const val EDGE_FRACTION = 0.65++ fun shouldRepublish(distanceFromCenterM: Double, radiusM: Int): Boolean =+ distanceFromCenterM > radiusM * EDGE_FRACTION++ /** Equirectangular distance (m) between two geographic points. */+ fun distanceM(a: GeoPoint, b: GeoPoint): Double {+ val dx = wearMetersEast(a.latitude, a.longitude, b.longitude)+ val dy = wearMetersNorth(a.latitude, b.latitude)+ return sqrt(dx * dx + dy * dy)+ }+}++/**+ * Builds the watch route overlay from a phone route: decimated polyline+ * ahead of [distanceAlongM], maneuvers with cumulative distances, and the+ * next-maneuver/ETA summary. Decimation coarsens until the byte cap fits.+ */+fun buildWearRouteState(+ destinationName: String,+ polyline: List<GeoPoint>,+ maneuvers: List<WearManeuver>,+ nextText: String,+ distanceToNextM: Int,+ distanceRemainingM: Int,+ etaEpochMs: Long,+ generatedAtMillis: Long,+): WearRouteState {+ if (polyline.isEmpty()) {+ return WearRouteState(+ active = true, destinationName = destinationName,+ maneuvers = maneuvers, nextText = nextText,+ distanceToNextM = distanceToNextM,+ distanceRemainingM = distanceRemainingM,+ etaEpochMs = etaEpochMs, generatedAtMillis = generatedAtMillis,+ )+ }+ val origin = polyline.first()+ for (tolerance in listOf(6.0, 12.0, 24.0, 48.0)) {+ val simplified = simplifyWearLine(polyline, origin, tolerance)+ val capped = if (simplified.size > 400) {+ simplified.filterIndexed { i, _ -> i % 2 == 0 || i == simplified.lastIndex }+ } else {+ simplified+ }+ val state = WearRouteState(+ active = true, destinationName = destinationName,+ routeOriginLatE7 = (origin.latitude * 1e7).toInt(),+ routeOriginLonE7 = (origin.longitude * 1e7).toInt(),+ routePts = quantizeFlat(toMeterPts(capped, origin.latitude, origin.longitude)),+ maneuvers = maneuvers.take(12),+ nextText = nextText,+ distanceToNextM = distanceToNextM,+ distanceRemainingM = distanceRemainingM,+ etaEpochMs = etaEpochMs, generatedAtMillis = generatedAtMillis,+ )+ if (WearMapsProtocol.json.encodeToString(state).encodeToByteArray().size <=+ WearMapsProtocol.MAX_ROUTE_JSON_BYTES+ ) return state+ }+ // Degenerate fallback: endpoints only, still an honest active route.+ return WearRouteState(+ active = true, destinationName = destinationName,+ routeOriginLatE7 = (origin.latitude * 1e7).toInt(),+ routeOriginLonE7 = (origin.longitude * 1e7).toInt(),+ routePts = quantizeFlat(toMeterPts(listOf(origin, polyline.last()), origin.latitude, origin.longitude)),+ maneuvers = maneuvers.take(12),+ nextText = nextText,+ distanceToNextM = distanceToNextM,+ distanceRemainingM = distanceRemainingM,+ etaEpochMs = etaEpochMs, generatedAtMillis = generatedAtMillis,+ )+}
maps/src/main/java/com/vayunmathur/maps/domain/WearMapsProtocol.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/domain/WearMapsProtocol.kt b/maps/src/main/java/com/vayunmathur/maps/domain/WearMapsProtocol.ktnew file mode 100644index 0000000000..3cf31a6c72--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/domain/WearMapsProtocol.kt@@ -0,0 +1,196 @@+package com.vayunmathur.maps.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import kotlin.math.cos++/**+ * Phone <-> watch protocol for the Wear OS Maps companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module (`:maps:wear`,+ * applicationId `com.vayunmathur.maps`) carries a copy of this file under+ * `com.vayunmathur.maps.wear.domain`. Change both copies together; each+ * side's unit tests pin the same golden JSON so a one-sided edit fails.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items: [REGION_PATH] phone -> watch (bounded vector snapshot of+ * the area around the user), [ROUTE_PATH] phone -> watch (navigation+ * overlay, or `active=false` to clear it), [POSITION_PATH] phone ->+ * watch (small frequent user position inside the current region) and+ * [WATCH_STATE_PATH] watch -> phone (what the watch last applied).+ * - Messages: [REQUEST_REGION_PATH] watch -> phone (ask for a fresh+ * region; delivery needs a live session, nothing wakes a dead process).+ *+ * What a snapshot contains — and what it honestly does not:+ * Coordinates are quantized metres east/north of the snapshot centre+ * ([QUANT_STEP_M] per unit, so round-trip error is at most half a step).+ * Lines carry roads/paths/water/buildings/route geometry *when the phone+ * has a cheap source for them*; points carry POIs from the offline index+ * and saved places. `:library:map` exposes no Kotlin geometry API for the+ * basemap's road/water/building linework (the Vulkan renderer decodes the+ * `.mamaps` tiles natively), so a phone build without such a source sets+ * [WearMapSnapshot.degraded] to name the missing kinds instead of faking+ * geometry. The watch renders whatever lines it is given.+ *+ * Position source is the PHONE. The watch does not run its own GPS in+ * this design (a watch fix would cost watch battery for a worse antenna+ * and would disagree with the phone map the user navigates by); the+ * phone's location manager / navigation session is the single source.+ */+object WearMapsProtocol {+ /** WearLink appId the phone requires in the peer handshake. */+ const val CAPABILITY = "maps_wear_companion"++ /** Data-item path (phone -> watch): the [WearMapSnapshot] JSON. */+ const val REGION_PATH = "/maps/region"++ /** Data-item path (phone -> watch): the [WearRouteState] JSON. */+ const val ROUTE_PATH = "/maps/route"++ /** Data-item path (phone -> watch): the [WearPosition] JSON. */+ const val POSITION_PATH = "/maps/position"++ /** Data-item path (watch -> phone): the [WearWatchState] JSON. */+ const val WATCH_STATE_PATH = "/maps/watch-state"++ /** Message path (watch -> phone): ask the phone to republish the region. */+ const val REQUEST_REGION_PATH = "/maps/request-region"++ /** Radius (m) of the square region a snapshot covers around its centre. */+ const val REGION_RADIUS_M = 600++ /** Metres per quantized coordinate unit (round-trip error <= half). */+ const val QUANT_STEP_M = 2.0++ /** Largest region JSON in UTF-8 bytes; extraction degrades to fit. */+ const val MAX_JSON_BYTES = 48_000++ /** Largest route JSON in UTF-8 bytes; route extraction decimates to fit. */+ const val MAX_ROUTE_JSON_BYTES = 24_000++ /** A snapshot older than this (watch clock vs [WearMapSnapshot.generatedAtMillis]) reads stale. */+ const val STALE_AFTER_MS = 90_000L++ /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+ val json: Json = Json { ignoreUnknownKeys = true }+}++/** Geometry kind of a [WearMapLine]; the watch strokes/fills by kind. */+@Serializable+enum class WearLineKind { ROAD, PATH, WATER, BUILDING, ROUTE }++/**+ * One simplified polyline/polygon, quantized metres east/north of the+ * snapshot (or route) origin as a flat `[dx, dy, dx, dy, ...]` list in+ * [WearMapsProtocol.QUANT_STEP_M] units. [closed] polygons fill.+ */+@Serializable+data class WearMapLine(+ val kind: WearLineKind,+ val pts: List<Int> = emptyList(),+ val closed: Boolean = false,+ val name: String = "",+)++/** One POI point, quantized metres east/north of the snapshot centre. */+@Serializable+data class WearMapPoint(+ /** Offline POI type id (phone `PoiCategories` numbering); -1 for saved. */+ val type: Int = 0,+ val name: String = "",+ val dx: Int = 0,+ val dy: Int = 0,+)++/** One saved place (absolute coords: the glance list needs distance, not just on-map position). */+@Serializable+data class WearSavedPlace(+ val name: String = "",+ val latE7: Int = 0,+ val lonE7: Int = 0,+)++/**+ * The phone's bounded vector snapshot for the watch ([WearMapsProtocol.REGION_PATH]).+ * Centre is E7 degrees; all geometry is quantized metres relative to it.+ */+@Serializable+data class WearMapSnapshot(+ val generatedAtMillis: Long = 0L,+ val centerLatE7: Int = 0,+ val centerLonE7: Int = 0,+ val radiusM: Int = WearMapsProtocol.REGION_RADIUS_M,+ val lines: List<WearMapLine> = emptyList(),+ val points: List<WearMapPoint> = emptyList(),+ val saved: List<WearSavedPlace> = emptyList(),+ /** True when the byte cap dropped or coarsened geometry. */+ val truncated: Boolean = false,+ /** Human-honest names of what is missing/coarser, e.g. "roads", "detail". Empty = full. */+ val degraded: List<String> = emptyList(),+ /** User bearing (degrees clockwise from north) at publish, -1 = unknown. */+ val userBearingDeg: Int = -1,+)++/** The phone's current user position ([WearMapsProtocol.POSITION_PATH]); -1 bearing = unknown. */+@Serializable+data class WearPosition(+ val latE7: Int = 0,+ val lonE7: Int = 0,+ val bearingDeg: Int = -1,+ val atMillis: Long = 0L,+)++/** One maneuver in the route-detail list. */+@Serializable+data class WearManeuver(+ val text: String = "",+ /** Maneuver kind name from the phone router (e.g. TURN_LEFT); may be empty. */+ val kind: String = "",+ /** Cumulative distance from route start (m) at which this maneuver occurs. */+ val distanceFromStartM: Int = 0,+)++/**+ * Navigation overlay for the watch ([WearMapsProtocol.ROUTE_PATH]).+ * `active=false` is the explicit clear: route ended/arrived/stopped.+ * [routePts] are quantized metres relative to ([routeOriginLatE7],+ * [routeOriginLonE7]), independent of any region snapshot's centre, so a+ * region republish can never misalign the overlay.+ */+@Serializable+data class WearRouteState(+ val active: Boolean = false,+ val destinationName: String = "",+ val routeOriginLatE7: Int = 0,+ val routeOriginLonE7: Int = 0,+ val routePts: List<Int> = emptyList(),+ val maneuvers: List<WearManeuver> = emptyList(),+ val nextText: String = "",+ val distanceToNextM: Int = 0,+ val distanceRemainingM: Int = 0,+ val etaEpochMs: Long = 0L,+ val generatedAtMillis: Long = 0L,+)++/** What the watch last applied, published at [WearMapsProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearWatchState(+ val appliedGeneratedAtMillis: Long = 0L,+ val hasRegion: Boolean = false,+ val routeActive: Boolean = false,+)++/** Metres east of [originLon] for [lon] at [originLat] (equirectangular; fine at region scale). */+fun wearMetersEast(originLat: Double, originLon: Double, lon: Double): Double =+ (lon - originLon) * 111_320.0 * cos(Math.toRadians(originLat))++/** Metres north of [originLat] for [lat]. */+fun wearMetersNorth(originLat: Double, lat: Double): Double = (lat - originLat) * 110_540.0++/** Quantize metres to [WearMapsProtocol.QUANT_STEP_M] units. */+fun wearQuantize(meters: Double): Int = Math.round(meters / WearMapsProtocol.QUANT_STEP_M).toInt()++/** Inverse of [wearQuantize]. */+fun wearDequantize(units: Int): Double = units * WearMapsProtocol.QUANT_STEP_M
maps/src/main/java/com/vayunmathur/maps/platform/WearMapsSync.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/platform/WearMapsSync.kt b/maps/src/main/java/com/vayunmathur/maps/platform/WearMapsSync.ktnew file mode 100644index 0000000000..1d0188d247--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/platform/WearMapsSync.kt@@ -0,0 +1,248 @@+package com.vayunmathur.maps.platform++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import com.vayunmathur.maps.data.PoiIndex+import com.vayunmathur.maps.data.SavedPlaceStore+import com.vayunmathur.maps.data.inViewport+import com.vayunmathur.maps.domain.WearLineKind+import com.vayunmathur.maps.domain.WearMapSnapshot+import com.vayunmathur.maps.domain.WearMapsProtocol+import com.vayunmathur.maps.domain.WearManeuver+import com.vayunmathur.maps.domain.WearPosition+import com.vayunmathur.maps.domain.WearRawLine+import com.vayunmathur.maps.domain.WearRawPoint+import com.vayunmathur.maps.domain.WearRegionHysteresis+import com.vayunmathur.maps.domain.WearRouteState+import com.vayunmathur.maps.domain.WearSavedPlace+import com.vayunmathur.maps.domain.buildWearMapSnapshot+import com.vayunmathur.maps.domain.buildWearRouteState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString+import kotlin.math.cos++/**+ * Phone side of the Maps WearLink companion: the phone supplies the+ * region, the watch renders it (see [WearMapsProtocol]).+ *+ * - Location comes from this phone ([FrameworkLocationManager]); the+ * watch runs no GPS of its own. Every fix publishes a small+ * [WearPosition]; a fresh region is extracted only when+ * [WearRegionHysteresis] says the user nears the snapshot edge.+ * - Region geometry is what this app has cheaply in Kotlin: POIs from+ * the offline index ([PoiIndex.inViewport]), saved places, and — while+ * navigating — the route. Basemap road/water/building linework is NOT+ * available in Kotlin (`:library:map` decodes tiles natively), so the+ * snapshot names those kinds in `degraded` rather than faking them;+ * the extractor/renderer carry them the moment a source exists.+ * - Navigation mirrors [NavigationSessionManager]: Navigating publishes+ * an active [WearRouteState]; Idle/Arrived/Failed publish the explicit+ * `active=false` clear exactly once per transition.+ */+object WearMapsSync {+ private const val TAG = "WearMapsSync"+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ @Volatile+ private var node: WearLinkNode? = null+ @Volatile+ private var lastLocation: GeoPoint? = null+ @Volatile+ private var lastBearingDeg: Int = -1+ @Volatile+ private var lastCenter: GeoPoint? = null+ @Volatile+ private var lastRoutePublishMs = 0L+ @Volatile+ private var routeWasActive = false++ fun start(context: Context) {+ val appContext = context.applicationContext+ if (node != null) return+ synchronized(this) {+ if (node != null) return+ val listener = object : WearLinkListener {+ override fun onMessage(path: String, body: ByteArray) {+ if (path == WearMapsProtocol.REQUEST_REGION_PATH) {+ scope.launch { publishRegion(appContext, force = true) }+ }+ }+ }+ val created = WearLinkNode(appContext, WearMapsProtocol.CAPABILITY, listener)+ node = created+ scope.launch {+ var wasConnected = false+ created.state.collect { linkState ->+ val connected = linkState is WearLinkState.Connected+ if (connected && !wasConnected) {+ publishRegion(appContext, force = true)+ publishRoute(appContext, force = true)+ }+ wasConnected = connected+ }+ }+ created.start()+ startLocation(appContext)+ startNavigationMirror(appContext)+ }+ }++ private fun startLocation(appContext: Context) {+ val manager = FrameworkLocationManager(appContext)+ // Process-lifetime companion feed: deliberately never stopped while+ // this process lives (the sync itself is app-lifecycle-bound).+ manager.startUpdates(onUpdateReceived = { point, heading, _ ->+ lastLocation = point+ if (heading != null) lastBearingDeg = heading.toInt()+ scope.launch {+ publishPosition(appContext, point)+ publishRegion(appContext, force = false)+ }+ })+ }++ private suspend fun publishPosition(appContext: Context, point: GeoPoint) {+ val position = WearPosition(+ latE7 = (point.latitude * 1e7).toInt(),+ lonE7 = (point.longitude * 1e7).toInt(),+ bearingDeg = lastBearingDeg,+ atMillis = System.currentTimeMillis(),+ )+ node?.putData(+ WearMapsProtocol.POSITION_PATH,+ WearMapsProtocol.json.encodeToString(position).encodeToByteArray(),+ )+ }++ /** Extract + publish the region around the last fix; [force] bypasses hysteresis. */+ suspend fun publishRegion(appContext: Context, force: Boolean) {+ val user = lastLocation ?: return+ val center = lastCenter+ if (!force && center != null &&+ !WearRegionHysteresis.shouldRepublish(+ WearRegionHysteresis.distanceM(center, user),+ WearMapsProtocol.REGION_RADIUS_M,+ )+ ) return+ val snapshot = extractRegion(appContext, user)+ val sent = node?.putData(+ WearMapsProtocol.REGION_PATH,+ WearMapsProtocol.json.encodeToString(snapshot).encodeToByteArray(),+ ) ?: false+ if (sent) {+ lastCenter = user+ } else {+ Log.status(TAG, "region not delivered (no live WearLink session)")+ }+ }++ /** The cheap-Kotlin extraction: offline POIs + saved places (+ route line while navigating). */+ private fun extractRegion(appContext: Context, center: GeoPoint): WearMapSnapshot {+ val radius = WearMapsProtocol.REGION_RADIUS_M.toDouble()+ val dLat = radius / 110_540.0+ val dLon = radius / (111_320.0 * cos(Math.toRadians(center.latitude)).coerceAtLeast(0.05))+ val points = runCatching {+ PoiIndex.initialize(appContext)+ PoiIndex.inViewport(+ west = center.longitude - dLon, south = center.latitude - dLat,+ east = center.longitude + dLon, north = center.latitude + dLat,+ cap = 300,+ ).map { WearRawPoint(it.type, it.name, GeoPoint(it.lon, it.lat)) }+ }.getOrDefault(emptyList())+ val savedStore = SavedPlaceStore(DataStoreUtils.getInstance(appContext))+ val saved = (savedStore.savedInitial() + savedStore.listsInitial().values.flatten())+ .distinctBy { it.name to it.lat to it.lon }+ .map {+ WearSavedPlace(it.name, (it.lat * 1e7).toInt(), (it.lon * 1e7).toInt())+ }+ val route = NavigationSessionManager.session.value.route+ val lines = if (route != null && route.polyline.size >= 2) {+ listOf(WearRawLine(WearLineKind.ROUTE, route.polyline))+ } else {+ emptyList()+ }+ return buildWearMapSnapshot(+ center = center,+ generatedAtMillis = System.currentTimeMillis(),+ rawLines = lines,+ rawPoints = points,+ saved = saved.take(20),+ userBearingDeg = lastBearingDeg,+ // Honest absence: no Kotlin source for basemap linework today.+ missingKinds = listOf("roads", "water", "buildings"),+ )+ }++ private fun startNavigationMirror(appContext: Context) {+ scope.launch {+ NavigationSessionManager.state.collectLatest {+ publishRoute(appContext, force = false)+ }+ }+ scope.launch {+ NavigationSessionManager.session.collectLatest {+ publishRoute(appContext, force = true)+ }+ }+ }++ /** Publish the route overlay, or its explicit clear when not navigating. */+ suspend fun publishRoute(appContext: Context, force: Boolean) {+ val navState = NavigationSessionManager.state.value+ val session = NavigationSessionManager.session.value+ val navigating = navState as? NavigationSessionManager.NavState.Navigating+ val route = session.route+ val now = System.currentTimeMillis()+ if (navigating == null || route == null) {+ if (routeWasActive || force && navState is NavigationSessionManager.NavState.Idle) {+ routeWasActive = false+ node?.putData(+ WearMapsProtocol.ROUTE_PATH,+ WearMapsProtocol.json.encodeToString(+ WearRouteState(active = false, generatedAtMillis = now),+ ).encodeToByteArray(),+ )+ }+ return+ }+ if (!force && now - lastRoutePublishMs < 5_000L) return+ lastRoutePublishMs = now+ routeWasActive = true+ val progress = navigating.progress+ var cumulative = 0.0+ val maneuvers = route.step.map { step ->+ WearManeuver(+ text = step.navInstruction.instructions,+ kind = step.navInstruction.maneuver.name,+ distanceFromStartM = cumulative.toInt(),+ ).also { cumulative += step.distanceMeters }+ }+ val nextText = route.step.getOrNull(progress.currentStepIndex)+ ?.navInstruction?.instructions.orEmpty()+ val state = buildWearRouteState(+ destinationName = session.destinationName.orEmpty(),+ polyline = route.polyline,+ maneuvers = maneuvers,+ nextText = nextText,+ distanceToNextM = progress.distanceToNextManeuver.toInt(),+ distanceRemainingM = progress.distanceRemaining.toInt(),+ etaEpochMs = progress.etaEpochMs,+ generatedAtMillis = now,+ )+ node?.putData(+ WearMapsProtocol.ROUTE_PATH,+ WearMapsProtocol.json.encodeToString(state).encodeToByteArray(),+ )+ // Route geometry belongs in the region too; refresh it alongside.+ publishRegion(appContext, force = true)+ }+}
maps/src/test/java/com/vayunmathur/maps/domain/WearMapRegionTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/domain/WearMapRegionTest.kt b/maps/src/test/java/com/vayunmathur/maps/domain/WearMapRegionTest.ktnew file mode 100644index 0000000000..362a534e67--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/domain/WearMapRegionTest.kt@@ -0,0 +1,159 @@+package com.vayunmathur.maps.domain++import com.vayunmathur.library.map.GeoPoint+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearMapRegionTest {++ private val center = GeoPoint(0.0, 0.0) // lon, lat — equator, metre math is exact-ish++ private fun east(meters: Double) = GeoPoint(meters / 111_320.0, 0.0)+ private fun north(meters: Double) = GeoPoint(0.0, meters / 110_540.0)++ @Test+ fun goldenSnapshotJson() {+ val snapshot = WearMapSnapshot(+ generatedAtMillis = 1_000L,+ centerLatE7 = 340_522_350,+ centerLonE7 = -1_182_436_830,+ lines = listOf(WearMapLine(WearLineKind.ROAD, listOf(0, 0, 10, 0))),+ points = listOf(WearMapPoint(0, "Cafe", 5, -3)),+ )+ assertEquals(+ """{"generatedAtMillis":1000,"centerLatE7":340522350,"centerLonE7":-1182436830,""" ++ """"lines":[{"kind":"ROAD","pts":[0,0,10,0]}],""" ++ """"points":[{"name":"Cafe","dx":5,"dy":-3}]}""",+ WearMapsProtocol.json.encodeToString(snapshot),+ )+ }++ @Test+ fun quantizationRoundTripWithinHalfStep() {+ for (meters in listOf(0.0, 1.0, 2.0, 3.0, 57.0, -123.0, 599.0)) {+ val back = wearDequantize(wearQuantize(meters))+ assertTrue(kotlin.math.abs(back - meters) <= WearMapsProtocol.QUANT_STEP_M / 2 + 1e-9, "$meters -> $back")+ }+ }++ @Test+ fun simplifyDropsCollinearKeepsCorner() {+ val line = listOf(east(0.0), east(50.0), east(100.0), north(0.0).let { GeoPoint(it.longitude, 100.0 / 110_540.0) })+ val simplified = simplifyWearLine(line, center, toleranceM = 4.0)+ assertEquals(3, simplified.size)+ assertEquals(line.first(), simplified.first())+ assertEquals(line.last(), simplified.last())+ }++ @Test+ fun extractionClipsToRegionAndCapsBytes() {+ // A road far outside must be clipped away; a long road inside is kept quantized.+ val outside = WearRawLine(WearLineKind.ROAD, listOf(east(5_000.0), east(6_000.0)))+ val inside = WearRawLine(+ WearLineKind.ROAD,+ (0..20).map { east(it * 50.0 - 500.0) },+ )+ val points = (1..200).map { WearRawPoint(0, "Poi $it with a reasonably long name", east(it * 3.0)) }+ val snapshot = buildWearMapSnapshot(center, 7L, listOf(outside, inside), points)+ val bytes = WearMapsProtocol.json.encodeToString(snapshot).encodeToByteArray().size+ assertTrue(bytes <= WearMapsProtocol.MAX_JSON_BYTES, "snapshot $bytes over cap")+ assertTrue(snapshot.lines.isNotEmpty())+ assertTrue(snapshot.lines.all { line ->+ line.pts.indices.step(2).all { i ->+ kotlin.math.abs(wearDequantize(line.pts[i])) <= snapshot.radiusM + WearMapsProtocol.QUANT_STEP_M+ }+ })+ // Nearest points survive.+ assertTrue(snapshot.points.size <= 80)+ assertTrue(snapshot.truncated)+ }++ @Test+ fun degradationDropsBuildingsBeforeRoads() {+ val fatName = "x".repeat(1_000)+ // All inside the 600 m region: horizontal roads + small building squares.+ val roads = (1..120).map { row ->+ WearRawLine(+ WearLineKind.ROAD,+ (0..30).map { i -> GeoPoint((i * 33.0 - 500.0) / 111_320.0, (row * 16.0 - 480.0) / 110_540.0) },+ name = fatName,+ )+ }+ val buildings = (1..120).map { b ->+ val bx = (b % 10) * 90.0 - 450.0+ val by = (b / 10) * 90.0 - 270.0+ WearRawLine(+ WearLineKind.BUILDING,+ listOf(+ GeoPoint(bx / 111_320.0, by / 110_540.0),+ GeoPoint((bx + 40.0) / 111_320.0, by / 110_540.0),+ GeoPoint((bx + 40.0) / 111_320.0, (by + 40.0) / 110_540.0),+ GeoPoint(bx / 111_320.0, (by + 40.0) / 110_540.0),+ ),+ closed = true, name = fatName,+ )+ }+ val snapshot = buildWearMapSnapshot(center, 0L, roads + buildings, emptyList())+ val bytes = WearMapsProtocol.json.encodeToString(snapshot).encodeToByteArray().size+ // Either it fits by dropping buildings, or it is honestly truncated at the final rung.+ assertTrue(snapshot.truncated)+ if (bytes <= WearMapsProtocol.MAX_JSON_BYTES) {+ assertTrue(snapshot.degraded.contains("buildings") || snapshot.degraded.contains("detail"))+ }+ }++ @Test+ fun missingKindsAreNamedHonestly() {+ val snapshot = buildWearMapSnapshot(+ center, 0L, emptyList(), emptyList(),+ missingKinds = listOf("roads", "water", "buildings"),+ )+ assertEquals(listOf("roads", "water", "buildings"), snapshot.degraded)+ assertTrue(snapshot.lines.isEmpty())+ }++ @Test+ fun hysteresisHoldsInsideAndFiresAtEdge() {+ assertFalse(WearRegionHysteresis.shouldRepublish(300.0, 600))+ assertFalse(WearRegionHysteresis.shouldRepublish(390.0, 600)) // exactly 65%+ assertTrue(WearRegionHysteresis.shouldRepublish(391.0, 600))+ assertTrue(WearRegionHysteresis.shouldRepublish(700.0, 600)) // outside+ }++ @Test+ fun routeStateCapsBytesAndKeepsManeuvers() {+ val polyline = (0..500).map { east(it * 10.0) }+ val maneuvers = listOf(WearManeuver("Turn left", "TURN_LEFT", 100))+ val state = buildWearRouteState(+ destinationName = "Home",+ polyline = polyline,+ maneuvers = maneuvers,+ nextText = "Turn left",+ distanceToNextM = 100,+ distanceRemainingM = 5_000,+ etaEpochMs = 123L,+ generatedAtMillis = 9L,+ )+ assertTrue(state.active)+ assertEquals(maneuvers, state.maneuvers)+ val bytes = WearMapsProtocol.json.encodeToString(state).encodeToByteArray().size+ assertTrue(bytes <= WearMapsProtocol.MAX_ROUTE_JSON_BYTES, "route $bytes over cap")+ // First route point is the quantized origin.+ assertEquals(listOf(0, 0), state.routePts.take(2))+ }++ @Test+ fun routeRoundTrip() {+ val state = WearRouteState(active = true, destinationName = "Work", nextText = "Straight")+ assertEquals(+ state,+ WearMapsProtocol.json.decodeFromString<WearRouteState>(+ WearMapsProtocol.json.encodeToString(state),+ ),+ )+ assertFalse(WearRouteState(active = false).active) // explicit clear shape+ }+}