Modern Apps git

← Modern-Apps.git

watch: harden exercise sessions with live tile timer, real laps, speed series, end reason, availability, and wear picker

Commit
9025d593d0ab004a879ea54c61eeb25230fb3d4a
Author
Vayun Mathur <[email protected]>
When
2026-07-06 17:36 UTC (5 months ago)
Parents
de52918

Diff

watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.ktindex 353c217a2a..291630b7fe 100644--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt@@ -7,6 +7,7 @@ import androidx.health.connect.client.permission.HealthPermission import androidx.health.connect.client.records.DistanceRecord import androidx.health.connect.client.records.ElevationGainedRecord import androidx.health.connect.client.records.ExerciseRoute+import androidx.health.connect.client.records.ExerciseLap import androidx.health.connect.client.records.ExerciseSegment import androidx.health.connect.client.records.ExerciseSessionRecord import androidx.health.connect.client.records.FloorsClimbedRecord@@ -226,6 +227,14 @@ class HealthConnectManager(private val context: Context) {             )         } +        val laps = summary.laps.orEmpty().map { lap ->+            val lapStart = Instant.ofEpochMilli(lap.start)+            val lapEnd = Instant.ofEpochMilli(lap.end).let {+                if (it.isAfter(lapStart)) it else lapStart.plusSeconds(1)+            }+            ExerciseLap(startTime = lapStart, endTime = lapEnd)+        }+         toInsert += ExerciseSessionRecord(             startTime = start,             startZoneOffset = startOffset,@@ -234,28 +243,42 @@ class HealthConnectManager(private val context: Context) {             exerciseType = healthConnectExerciseType(summary.exerciseType),             title = null,             segments = segments,-            laps = emptyList(),+            laps = laps,             exerciseRoute = route,             metadata = Metadata.manualEntry(clientRecordId = "exercise-$key"),         ) -        // Speed: only avg/max were reported (no time series), so emit avg at the-        // start and max at the end of the window.-        summary.avgSpeedMps?.let { avg ->-            val samples = buildList {-                add(SpeedRecord.Sample(time = start, speed = Velocity.metersPerSecond(avg)))-                summary.maxSpeedMps?.let {-                    add(SpeedRecord.Sample(time = end, speed = Velocity.metersPerSecond(it)))-                }-            }+        // Speed: prefer the real captured time-series; fall back to the avg@start /+        // max@end approximation only when no series was reported.+        val speedSamples = summary.speedSamples.orEmpty()+            .map { SpeedRecord.Sample(time = Instant.ofEpochMilli(it.timeMs), speed = Velocity.metersPerSecond(it.mps)) }+            .filter { !it.time.isBefore(start) && !it.time.isAfter(end) }+        if (speedSamples.isNotEmpty()) {             toInsert += SpeedRecord(                 startTime = start,                 startZoneOffset = startOffset,                 endTime = end,                 endZoneOffset = endOffset,-                samples = samples,+                samples = speedSamples,                 metadata = Metadata.manualEntry(clientRecordId = "exercise-speed-$key"),             )+        } else {+            summary.avgSpeedMps?.let { avg ->+                val samples = buildList {+                    add(SpeedRecord.Sample(time = start, speed = Velocity.metersPerSecond(avg)))+                    summary.maxSpeedMps?.let {+                        add(SpeedRecord.Sample(time = end, speed = Velocity.metersPerSecond(it)))+                    }+                }+                toInsert += SpeedRecord(+                    startTime = start,+                    startZoneOffset = startOffset,+                    endTime = end,+                    endZoneOffset = endOffset,+                    samples = samples,+                    metadata = Metadata.manualEntry(clientRecordId = "exercise-speed-$key"),+                )+            }         }          summary.avgCadenceSpm?.let { cadence ->
watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.ktindex 3d4757d4a5..fc3bbb80d3 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt@@ -27,7 +27,11 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items import androidx.wear.compose.material.Button+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.watch.watch.data.SensorDatabase@@ -184,22 +188,32 @@ class MainActivity : ComponentActivity() {      @Composable     private fun PickerScreen(onPick: (WorkoutType) -> Unit, onBack: () -> Unit) {-        Column(-            modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),+        ScalingLazyColumn(+            modifier = Modifier.fillMaxSize(),             horizontalAlignment = Alignment.CenterHorizontally,             verticalArrangement = Arrangement.spacedBy(6.dp),         ) {-            Text(stringResource(R.string.exercise_pick_type))-            WorkoutType.entries.forEach { workout ->-                Button(+            item {+                Text(+                    stringResource(R.string.exercise_pick_type),+                    modifier = Modifier.padding(vertical = 4.dp),+                )+            }+            items(WorkoutType.entries) { workout ->+                Chip(+                    label = { Text(workout.label) },                     onClick = { onPick(workout) },-                    modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp),-                ) {-                    Text(workout.label)-                }+                    colors = ChipDefaults.primaryChipColors(),+                    modifier = Modifier.fillMaxWidth(),+                )             }-            Button(onClick = onBack, modifier = Modifier.padding(top = 4.dp)) {-                Text(stringResource(R.string.exercise_back))+            item {+                Chip(+                    label = { Text(stringResource(R.string.exercise_back)) },+                    onClick = onBack,+                    colors = ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth(),+                )             }         }     }@@ -216,6 +230,8 @@ class MainActivity : ComponentActivity() {         val calories by ExerciseService.caloriesFlow.collectAsState()         val distance by ExerciseService.distanceFlow.collectAsState()         val label by ExerciseService.activeWorkoutLabelFlow.collectAsState()+        val availability by ExerciseService.availabilityFlow.collectAsState()+        val message by ExerciseService.messageFlow.collectAsState()         val dash = stringResource(R.string.exercise_dash)          Column(@@ -229,6 +245,8 @@ class MainActivity : ComponentActivity() {             Text(stringResource(R.string.exercise_hr, hr?.toInt()?.toString() ?: dash))             Text(stringResource(R.string.exercise_calories, calories?.toInt()?.toString() ?: dash))             Text(stringResource(R.string.exercise_distance, distance?.toInt()?.toString() ?: dash))+            availability?.let { Text(it) }+            message?.let { Text(it) }              Row(                 modifier = Modifier.padding(top = 8.dp),
watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseController.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseController.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseController.ktindex f7695700c9..abb21a15d8 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseController.kt+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseController.kt@@ -8,11 +8,14 @@ import androidx.health.services.client.HealthServices import androidx.health.services.client.data.Availability import androidx.health.services.client.data.DataPointContainer import androidx.health.services.client.data.DataType+import androidx.health.services.client.data.DataTypeAvailability import androidx.health.services.client.data.ExerciseConfig+import androidx.health.services.client.data.ExerciseEndReason import androidx.health.services.client.data.ExerciseLapSummary import androidx.health.services.client.data.ExerciseState import androidx.health.services.client.data.ExerciseTrackedStatus import androidx.health.services.client.data.ExerciseUpdate+import androidx.health.services.client.data.LocationAvailability import androidx.health.services.client.data.LocationData import androidx.health.services.client.data.WarmUpConfig import com.vayunmathur.watch.shared.data.ExerciseSessionSummary@@ -48,6 +51,8 @@ class ExerciseController(     private val onState: (ExerciseState) -> Unit,     private val onMetrics: (LiveMetrics) -> Unit,     private val onMessage: (String) -> Unit,+    // Data-availability hint (e.g. "Acquiring GPS…"); empty string clears it.+    private val onAvailability: (String) -> Unit, ) {     data class LiveMetrics(         val activeDurationMs: Long = 0,@@ -69,6 +74,9 @@ class ExerciseController(     // Accumulated across updates for the final summary.     private val routePoints = mutableListOf<RoutePoint>()     @Volatile private var lastRouteAtMs = 0L+    private val laps = mutableListOf<LapMarker>()+    private val speedSamples = mutableListOf<SpeedSample>()+    @Volatile private var lastSpeedAtMs = 0L     @Volatile private var latestActiveDurationMs = 0L     @Volatile private var latestHr: Double? = null     @Volatile private var latestCalories: Double? = null@@ -200,6 +208,11 @@ class ExerciseController(         }          override fun onExerciseUpdateReceived(update: ExerciseUpdate) {+            // Orphan recovery: a re-attached (or restarted) session has no locally+            // set start anchor, so adopt the first reported start time.+            if (startedAtMs == 0L) {+                startedAtMs = update.startTime?.toEpochMilli() ?: System.currentTimeMillis()+            }             val metrics = update.latestMetrics             captureLive(update, metrics)             val state = update.exerciseStateInfo.state@@ -209,9 +222,27 @@ class ExerciseController(             }         } -        override fun onLapSummaryReceived(lapSummary: ExerciseLapSummary) {}+        override fun onLapSummaryReceived(lapSummary: ExerciseLapSummary) {+            laps += LapMarker(+                start = lapSummary.startTime.toEpochMilli(),+                end = lapSummary.endTime.toEpochMilli(),+            )+        } -        override fun onAvailabilityChanged(dataType: DataType<*, *>, availability: Availability) {}+        override fun onAvailabilityChanged(dataType: DataType<*, *>, availability: Availability) {+            val label = when (dataType) {+                DataType.LOCATION -> "GPS"+                DataType.HEART_RATE_BPM -> "HR"+                else -> return+            }+            val acquiring = when (availability) {+                is LocationAvailability -> availability != LocationAvailability.ACQUIRED_TETHERED &&+                    availability != LocationAvailability.ACQUIRED_UNTETHERED+                is DataTypeAvailability -> availability != DataTypeAvailability.AVAILABLE+                else -> false+            }+            onAvailability(if (acquiring) "Acquiring $label…" else "")+        }     }      private fun captureLive(update: ExerciseUpdate, metrics: DataPointContainer) {@@ -225,6 +256,14 @@ class ExerciseController(             latestAvgSpeed = it.average             latestMaxSpeed = it.max         }+        // Accumulate a throttled speed time-series (same cadence as route points).+        metrics.getData(DataType.SPEED).forEach { sample ->+            val now = System.currentTimeMillis()+            if (now - lastSpeedAtMs >= SPEED_MIN_INTERVAL_MS) {+                lastSpeedAtMs = now+                speedSamples += SpeedSample(timeMs = now, mps = sample.value)+            }+        }         metrics.getData(DataType.STEPS_PER_MINUTE_STATS)?.let {             latestAvgCadence = it.average.toDouble()         }@@ -267,6 +306,7 @@ class ExerciseController(         activeWorkout = null         val endTime = System.currentTimeMillis()         val startTime = update.startTime?.toEpochMilli() ?: startedAtMs+        val endReason = endReasonText(update.exerciseStateInfo.endReason)          val summary = ExerciseSessionSummary(             exerciseType = workout.healthServicesType.name,@@ -279,15 +319,28 @@ class ExerciseController(             vo2Max = latestVo2Max,             route = routePoints.toList().takeIf { it.isNotEmpty() },             lapCount = latestLapCount,+            laps = laps.toList().takeIf { it.isNotEmpty() },+            speedSamples = speedSamples.toList().takeIf { it.isNotEmpty() },             segments = buildSegments(workout, startTime, endTime),+            endReason = endReason,             distanceMeters = latestDistance,             totalCalories = latestCalories,             avgHr = latestHr,         )+        onMessage(endReason)         persist(summary)         clearCallback()     } +    // Health Services ExerciseEndReason -> a short human string surfaced on the UI.+    private fun endReasonText(reason: Int): String = when (reason) {+        ExerciseEndReason.USER_END -> "Ended by user"+        ExerciseEndReason.AUTO_END_PERMISSION_LOST -> "Ended: sensor permission lost"+        ExerciseEndReason.AUTO_END_PAUSE_EXPIRED -> "Ended: paused too long"+        ExerciseEndReason.AUTO_END_MISSING_LISTENER -> "Ended: tracking interrupted"+        else -> "Workout ended"+    }+     // Rep-based workouts report a running REP_COUNT_TOTAL; we emit it as a single     // whole-session segment. Fine-grained per-set segmentation is not available     // from a plain rep counter, so the segment type is UNKNOWN (0).@@ -324,6 +377,9 @@ class ExerciseController(     private fun resetAccumulators() {         routePoints.clear()         lastRouteAtMs = 0L+        laps.clear()+        speedSamples.clear()+        lastSpeedAtMs = 0L         latestActiveDurationMs = 0L         latestHr = null         latestCalories = null@@ -355,6 +411,7 @@ class ExerciseController(     companion object {         private const val TAG = "ExerciseController"         private const val ROUTE_MIN_INTERVAL_MS = 3_000L+        private const val SPEED_MIN_INTERVAL_MS = 3_000L         // Health Connect ExerciseSegment.EXERCISE_SEGMENT_TYPE_UNKNOWN.         private const val SEGMENT_TYPE_UNKNOWN = 0     }
watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseService.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseService.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseService.ktnew file mode 100644index 0000000000..2f86c2b274--- /dev/null+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseService.kt@@ -0,0 +1,208 @@+package com.vayunmathur.watch.watch.service++import android.Manifest+import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.content.pm.ServiceInfo+import android.os.IBinder+import androidx.core.content.ContextCompat+import androidx.health.services.client.data.ExerciseState+import androidx.wear.tiles.TileService+import com.vayunmathur.watch.watch.R+import com.vayunmathur.watch.watch.data.SensorDatabase+import com.vayunmathur.watch.watch.data.WorkoutType+import com.vayunmathur.watch.watch.tile.ExerciseTileService+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow++/**+ * Foreground service (type health, plus location for GPS workouts) that owns an+ * [ExerciseController] for one active workout. It exposes companion [StateFlow]s+ * consumed by the in-app screen and the Tile, and reacts to START/PAUSE/RESUME/+ * STOP actions delivered via [onStartCommand]. It also ensures+ * [SensorBackgroundService] (the BLE GATT server) is running so the ended-session+ * row can actually ship to the phone.+ */+class ExerciseService : Service() {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+    private var controller: ExerciseController? = null++    override fun onCreate() {+        super.onCreate()+        val dao = SensorDatabase.get(this).sensorDao()+        controller = ExerciseController(+            context = this,+            dao = dao,+            scope = scope,+            onState = { onExerciseState(it) },+            onMetrics = { m ->+                activeDurationMs.value = m.activeDurationMs+                heartRate.value = m.heartRateBpm+                calories.value = m.calories+                distance.value = m.distanceMeters+            },+            onMessage = { message.value = it },+            onAvailability = { availability.value = it.ifEmpty { null } },+        )+    }++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        val action = intent?.getStringExtra(EXTRA_ACTION) ?: ACTION_START+        val workout = intent?.getStringExtra(EXTRA_WORKOUT)+            ?.let { runCatching { WorkoutType.valueOf(it) }.getOrNull() }++        when (action) {+            ACTION_START -> {+                val type = workout ?: WorkoutType.Workout+                startForegroundFor(type)+                activeWorkoutLabel.value = type.label+                message.value = null+                // Ensure the BLE pipeline is up so the session row ships.+                SensorBackgroundService.start(this)+                controller?.start(type)+                requestTileUpdate()+            }+            ACTION_PAUSE -> controller?.pause()+            ACTION_RESUME -> controller?.resume()+            ACTION_STOP -> controller?.stop()+        }+        return START_STICKY+    }++    private fun onExerciseState(state: ExerciseState) {+        uiState.value = when {+            state.isEnded -> UiState.Ended+            state.isPaused -> UiState.Paused+            state == ExerciseState.PREPARING || state == ExerciseState.USER_STARTING -> UiState.Preparing+            else -> UiState.Active+        }+        // Anchor the live Tile timer once the session is genuinely active.+        if (uiState.value == UiState.Active && activeStartEpochMs.value == 0L) {+            activeStartEpochMs.value = System.currentTimeMillis() - activeDurationMs.value+        }+        requestTileUpdate()+        if (state.isEnded) {+            resetLiveState()+            stopForeground(STOP_FOREGROUND_REMOVE)+            stopSelf()+        }+    }++    private fun startForegroundFor(workout: WorkoutType) {+        val hasLocation = ContextCompat.checkSelfPermission(+            this,+            Manifest.permission.ACCESS_FINE_LOCATION,+        ) == PackageManager.PERMISSION_GRANTED+        val type = if (workout.isGpsBased && hasLocation) {+            ServiceInfo.FOREGROUND_SERVICE_TYPE_HEALTH or+                ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION+        } else {+            ServiceInfo.FOREGROUND_SERVICE_TYPE_HEALTH+        }+        startForeground(NOTIFICATION_ID, buildNotification(), type)+    }++    private fun requestTileUpdate() {+        try {+            TileService.getUpdater(this).requestUpdate(ExerciseTileService::class.java)+        } catch (_: Exception) {+        }+    }++    private fun buildNotification(): Notification {+        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+        val channel = NotificationChannel(+            CHANNEL_ID,+            getString(R.string.exercise_notification_channel),+            NotificationManager.IMPORTANCE_LOW,+        )+        manager.createNotificationChannel(channel)+        return Notification.Builder(this, CHANNEL_ID)+            .setContentTitle(getString(R.string.exercise_notification_title))+            .setContentText(getString(R.string.exercise_notification_text))+            .setSmallIcon(R.drawable.ic_launcher_foreground)+            .setOngoing(true)+            .build()+    }++    private fun resetLiveState() {+        activeDurationMs.value = 0L+        heartRate.value = null+        calories.value = null+        distance.value = null+        activeWorkoutLabel.value = null+        activeStartEpochMs.value = 0L+        availability.value = null+    }++    override fun onDestroy() {+        scope.cancel()+        controller = null+        if (uiState.value != UiState.Ended) uiState.value = UiState.Idle+        super.onDestroy()+    }++    override fun onBind(intent: Intent?): IBinder? = null++    enum class UiState { Idle, Preparing, Active, Paused, Ended }++    companion object {+        private const val CHANNEL_ID = "exercise_session"+        private const val NOTIFICATION_ID = 2++        const val EXTRA_ACTION = "action"+        const val EXTRA_WORKOUT = "workout"+        const val ACTION_START = "START"+        const val ACTION_PAUSE = "PAUSE"+        const val ACTION_RESUME = "RESUME"+        const val ACTION_STOP = "STOP"++        val uiState = MutableStateFlow(UiState.Idle)+        val activeDurationMs = MutableStateFlow(0L)+        val heartRate = MutableStateFlow<Double?>(null)+        val calories = MutableStateFlow<Double?>(null)+        val distance = MutableStateFlow<Double?>(null)+        val activeWorkoutLabel = MutableStateFlow<String?>(null)+        val message = MutableStateFlow<String?>(null)+        // Epoch ms the active session started; drives the live Tile timer. 0 = idle.+        val activeStartEpochMs = MutableStateFlow(0L)+        // Non-null "Acquiring GPS/HR…" hint while a sensor is not yet available.+        val availability = MutableStateFlow<String?>(null)++        val uiStateFlow: StateFlow<UiState> = uiState+        val activeDurationFlow: StateFlow<Long> = activeDurationMs+        val heartRateFlow: StateFlow<Double?> = heartRate+        val caloriesFlow: StateFlow<Double?> = calories+        val distanceFlow: StateFlow<Double?> = distance+        val activeWorkoutLabelFlow: StateFlow<String?> = activeWorkoutLabel+        val messageFlow: StateFlow<String?> = message+        val activeStartEpochFlow: StateFlow<Long> = activeStartEpochMs+        val availabilityFlow: StateFlow<String?> = availability++        fun start(context: Context, workout: WorkoutType) {+            send(context, ACTION_START, workout)+        }++        fun pause(context: Context) = send(context, ACTION_PAUSE, null)+        fun resume(context: Context) = send(context, ACTION_RESUME, null)+        fun stop(context: Context) = send(context, ACTION_STOP, null)++        private fun send(context: Context, action: String, workout: WorkoutType?) {+            val intent = Intent(context, ExerciseService::class.java).apply {+                putExtra(EXTRA_ACTION, action)+                workout?.let { putExtra(EXTRA_WORKOUT, it.name) }+            }+            context.startForegroundService(intent)+        }+    }+}
watch/watch/src/main/java/com/vayunmathur/watch/watch/tile/ExerciseTileService.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/tile/ExerciseTileService.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/tile/ExerciseTileService.ktnew file mode 100644index 0000000000..5114046a33--- /dev/null+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/tile/ExerciseTileService.kt@@ -0,0 +1,219 @@+package com.vayunmathur.watch.watch.tile++import android.content.Context+import androidx.concurrent.futures.ResolvableFuture+import androidx.wear.protolayout.ActionBuilders+import androidx.wear.protolayout.DeviceParametersBuilders.DeviceParameters+import androidx.wear.protolayout.LayoutElementBuilders+import androidx.wear.protolayout.LayoutElementBuilders.LayoutElement+import androidx.wear.protolayout.ModifiersBuilders.Clickable+import androidx.wear.protolayout.ResourceBuilders+import androidx.wear.protolayout.TimelineBuilders+import androidx.wear.protolayout.TypeBuilders.StringLayoutConstraint+import androidx.wear.protolayout.TypeBuilders.StringProp+import androidx.wear.protolayout.expression.DynamicBuilders.DynamicInstant+import androidx.wear.protolayout.expression.DynamicBuilders.DynamicInt32+import androidx.wear.protolayout.expression.DynamicBuilders.DynamicString+import androidx.wear.protolayout.material.Button+import androidx.wear.protolayout.material.CompactChip+import androidx.wear.protolayout.material.Text+import androidx.wear.protolayout.material.Typography+import androidx.wear.protolayout.material.layouts.PrimaryLayout+import androidx.wear.tiles.RequestBuilders+import androidx.wear.tiles.TileBuilders+import androidx.wear.tiles.TileService+import com.google.common.util.concurrent.ListenableFuture+import com.vayunmathur.watch.watch.MainActivity+import com.vayunmathur.watch.watch.service.ExerciseService+import com.vayunmathur.watch.watch.ui.ExerciseControlActivity+import java.time.Instant++/**+ * Quick-glance workout controls Tile. When no workout is active it shows a+ * "Start workout" chip that launches [MainActivity]'s picker; while a workout is+ * running it shows the elapsed time + live HR and Pause/Resume + Stop buttons.+ *+ * Tiles cannot call a Service directly, so the control buttons launch the+ * transparent [ExerciseControlActivity] trampoline, which forwards the action to+ * [ExerciseService]. The service calls TileService.getUpdater().requestUpdate()+ * on every state change; a modest freshness interval is a fallback.+ */+class ExerciseTileService : TileService() {++    override fun onTileRequest(+        requestParams: RequestBuilders.TileRequest,+    ): ListenableFuture<TileBuilders.Tile> {+        val device = requestParams.deviceConfiguration+        val layout = buildLayout(this, device)+        val tile = TileBuilders.Tile.Builder()+            .setResourcesVersion(RESOURCES_VERSION)+            .setFreshnessIntervalMillis(FRESHNESS_MS)+            .setTileTimeline(TimelineBuilders.Timeline.fromLayoutElement(layout))+            .build()+        return immediate(tile)+    }++    override fun onTileResourcesRequest(+        requestParams: RequestBuilders.ResourcesRequest,+    ): ListenableFuture<ResourceBuilders.Resources> {+        return immediate(+            ResourceBuilders.Resources.Builder().setVersion(RESOURCES_VERSION).build(),+        )+    }++    private fun buildLayout(context: Context, device: DeviceParameters): LayoutElement {+        val state = ExerciseService.uiState.value+        return if (state == ExerciseService.UiState.Idle || state == ExerciseService.UiState.Ended) {+            idleLayout(context, device)+        } else {+            activeLayout(context, device, state)+        }+    }++    private fun idleLayout(context: Context, device: DeviceParameters): LayoutElement {+        val launch = Clickable.Builder()+            .setId("start")+            .setOnClick(+                ActionBuilders.LaunchAction.Builder()+                    .setAndroidActivity(+                        ActionBuilders.AndroidActivity.Builder()+                            .setPackageName(context.packageName)+                            .setClassName(MainActivity::class.java.name)+                            .addKeyToExtraMapping(+                                MainActivity.EXTRA_OPEN_PICKER,+                                ActionBuilders.stringExtra("1"),+                            )+                            .build(),+                    )+                    .build(),+            )+            .build()+        return PrimaryLayout.Builder(device)+            .setResponsiveContentInsetEnabled(true)+            .setContent(+                Text.Builder(context, "Start a workout")+                    .setTypography(Typography.TYPOGRAPHY_BODY1)+                    .setMaxLines(2)+                    .build(),+            )+            .setPrimaryChipContent(+                CompactChip.Builder(context, "Start", launch, device).build(),+            )+            .build()+    }++    private fun activeLayout(+        context: Context,+        device: DeviceParameters,+        state: ExerciseService.UiState,+    ): LayoutElement {+        val label = ExerciseService.activeWorkoutLabel.value ?: "Workout"+        val hr = ExerciseService.heartRate.value?.let { "HR ${it.toInt()}" } ?: "HR --"++        val paused = state == ExerciseService.UiState.Paused+        val pauseResumeAction = if (paused) ExerciseControlActivity.ACTION_RESUME+        else ExerciseControlActivity.ACTION_PAUSE+        val pauseResumeLabel = if (paused) "Resume" else "Pause"++        val controls = LayoutElementBuilders.Row.Builder()+            .addContent(+                Button.Builder(context, controlClickable("pauseResume", pauseResumeAction))+                    .setTextContent(if (paused) "R" else "P")+                    .build(),+            )+            .addContent(+                Button.Builder(context, controlClickable("stop", ExerciseControlActivity.ACTION_STOP))+                    .setTextContent("S")+                    .build(),+            )+            .build()++        val content = LayoutElementBuilders.Column.Builder()+            .addContent(+                Text.Builder(context, durationProp(), durationConstraint())+                    .setTypography(Typography.TYPOGRAPHY_DISPLAY2)+                    .build(),+            )+            .addContent(+                Text.Builder(context, hr)+                    .setTypography(Typography.TYPOGRAPHY_CAPTION1)+                    .build(),+            )+            .addContent(controls)+            .build()++        return PrimaryLayout.Builder(device)+            .setResponsiveContentInsetEnabled(true)+            .setPrimaryLabelTextContent(+                Text.Builder(context, label)+                    .setTypography(Typography.TYPOGRAPHY_CAPTION1)+                    .build(),+            )+            .setContent(content)+            .setSecondaryLabelTextContent(+                Text.Builder(context, pauseResumeLabel)+                    .setTypography(Typography.TYPOGRAPHY_CAPTION2)+                    .build(),+            )+            .build()+    }++    private fun controlClickable(id: String, action: String): Clickable =+        Clickable.Builder()+            .setId(id)+            .setOnClick(+                ActionBuilders.LaunchAction.Builder()+                    .setAndroidActivity(+                        ActionBuilders.AndroidActivity.Builder()+                            .setPackageName(packageName)+                            .setClassName(ExerciseControlActivity::class.java.name)+                            .addKeyToExtraMapping(+                                ExerciseControlActivity.EXTRA_ACTION,+                                ActionBuilders.stringExtra(action),+                            )+                            .build(),+                    )+                    .build(),+            )+            .build()++    // A live-ticking m:ss timer bound to the session start via a ProtoLayout+    // dynamic expression, so the platform re-evaluates it every second without a+    // tile refresh. Falls back to a static 0:00 before the start anchor is set.+    private fun durationProp(): StringProp {+        val startMs = ExerciseService.activeStartEpochMs.value+        val fallback = formatDuration(ExerciseService.activeDurationMs.value)+        val builder = StringProp.Builder(fallback)+        if (startMs > 0L) {+            val elapsed = DynamicInstant.withSecondsPrecision(Instant.ofEpochMilli(startMs))+                .durationUntil(DynamicInstant.platformTimeWithSecondsPrecision())+            val secondsFormat = DynamicInt32.IntFormatter.Builder()+                .setMinIntegerDigits(2)+                .build()+            val dynamic: DynamicString = elapsed.minutesPart.format()+                .concat(DynamicString.constant(":"))+                .concat(elapsed.secondsPart.format(secondsFormat))+            builder.setDynamicValue(dynamic)+        }+        return builder.build()+    }++    private fun durationConstraint(): StringLayoutConstraint =+        StringLayoutConstraint.Builder("88:88").build()++    private fun formatDuration(ms: Long): String {+        val totalSeconds = ms / 1000+        val minutes = totalSeconds / 60+        val seconds = totalSeconds % 60+        return "%d:%02d".format(minutes, seconds)+    }++    private fun <T> immediate(value: T): ListenableFuture<T> =+        ResolvableFuture.create<T>().apply { set(value) }++    companion object {+        private const val RESOURCES_VERSION = "1"+        // Fallback refresh; live updates are driven by ExerciseService.requestUpdate().+        private const val FRESHNESS_MS = 10_000L+    }+}