diff --git a/app/src/main/kotlin/org/openstrap/app/data/Route.kt b/app/src/main/kotlin/org/openstrap/app/data/Route.kt index b1c7f15c..7fa3352e 100644 --- a/app/src/main/kotlin/org/openstrap/app/data/Route.kt +++ b/app/src/main/kotlin/org/openstrap/app/data/Route.kt @@ -321,24 +321,33 @@ object Route { } /** Per-kilometre splits along [points]; the last one may be partial. Paused time doesn't count. */ - fun splits(points: List, pauses: List = emptyList(), km: Double = 1000.0): List { + fun splits(points: List, pauses: List = emptyList(), km: Double = 1000.0): List = + legs(points, pauses, km).map { it.split } + + /** One kilometre's [split] with the smoothed track [points] it covers, from the previous leg's last point. */ + data class Leg(val split: Split, val points: List) + + /** The kilometres of [splits], each with its stretch of the smoothed track; paused stretches are left out. */ + fun legs(points: List, pauses: List = emptyList(), km: Double = 1000.0): List { val clean = track(points) - val out = mutableListOf() - var startT = clean.firstOrNull()?.t ?: return out + val out = mutableListOf() + val current = mutableListOf(clean.firstOrNull() ?: return out) var meters = 0.0 var seconds = 0L clean.zipWithNext().forEach { (a, b) -> if (paused(a, b, pauses)) return@forEach meters += meters(a, b) seconds += b.t - a.t + current += b if (meters >= km) { - out += Split(out.size, b.t, seconds, meters) + out += Leg(Split(out.size, b.t, seconds, meters), current.toList()) + current.clear() + current += b meters = 0.0 seconds = 0 - startT = b.t } } - if (meters > 0) out += Split(out.size, clean.last().t, seconds, meters) + if (meters > 0) out += Leg(Split(out.size, clean.last().t, seconds, meters), current) return out } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMap.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMap.kt new file mode 100644 index 00000000..bb4c629c --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMap.kt @@ -0,0 +1,112 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawing +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.compose.ui.window.DialogWindowProvider +import org.openstrap.app.R +import org.openstrap.app.data.Route +import org.openstrap.app.ui.dashboard.LocalHeartZones +import org.openstrap.app.ui.workout.PhoneSummary + +/** The route cut into stretches in the colour of the heart zone each was run in, for the card's map and the full one. */ +@Composable +internal fun rememberZoneStretches(summary: PhoneSummary): List, Int>> { + val heartZones = LocalHeartZones.current + return remember(summary, heartZones) { + Route.byZone(summary.route, summary.history, summary.analysis.maxHeartRate, heartZones) + } +} + +/** The route map over the whole screen, in its own window so it covers the rail, the panes and the bars; Back or [onClose] closes it. */ +@Composable +internal fun FullScreenRouteMap(summary: PhoneSummary, model: RouteMapModel, onClose: () -> Unit) { + Dialog( + onDismissRequest = onClose, + properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false), + ) { + NoWindowAnimation() + FullScreenRouteMapContent(summary, model, onClose) + } +} + +/** A rotation builds the dialog again, so its window's entrance animation would show the map popping open once more. */ +@Composable +private fun NoWindowAnimation() { + val window = (LocalView.current.parent as? DialogWindowProvider)?.window + SideEffect { window?.setWindowAnimations(-1) } +} + +/** + * The map and its pills: Close top-end, Route only (or Show map) top-start, and Fit route top-centre + * once a drag has stopped the map following the route. Km markers sit along the line, and the split picker along the + * bottom draws the chosen kilometre with a white casing and fits it. + */ +@Composable +internal fun FullScreenRouteMapContent(summary: PhoneSummary, model: RouteMapModel, onClose: () -> Unit) { + val stretches = rememberZoneStretches(summary) + val routeOnly = model.routeOnly + var follow by remember { mutableStateOf(true) } + val legs = remember(summary) { Route.legs(summary.route, summary.pauses) } + val kmMarkers = remember(legs) { legs.filter { it.split.meters >= 1000.0 }.map { it.split.index + 1 to it.points.last() } } + val rows = remember(summary) { splitRowsFor(summary, summary.route) } + val selected = model.selected + var pickerHeight by remember { mutableStateOf(0.dp) } + val density = LocalDensity.current + // From the screen's bottom edge to the picker's top, so the fitted route and the map's credit stay above it. + val underPicker = WindowInsets.safeDrawing.asPaddingValues().calculateBottomPadding() + 12.dp + pickerHeight + Box(Modifier.fillMaxSize().background(Color.Black)) { + WorkoutMap( + stretches, + routeOnly, + Modifier.fillMaxSize(), + follow = follow, + fitPadding = PaddingValues(start = 24.dp, top = 96.dp, end = 24.dp, bottom = maxOf(96.dp, underPicker + 24.dp)), + creditBottom = underPicker + 8.dp, + onPanned = { follow = false }, + kmMarkers = kmMarkers, + highlight = selected?.let { legs.getOrNull(it)?.points }.orEmpty(), + ) + Box(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.safeDrawing).padding(12.dp)) { + val routeOnlyLabel = if (routeOnly) R.string.glow_summary_map_show_map else R.string.glow_summary_map_route_only + IconPill(stringResource(routeOnlyLabel), { model.routeOnly = !routeOnly }, Modifier.align(Alignment.TopStart)) + if (!follow) { + IconPill(stringResource(R.string.glow_summary_map_fit), { follow = true }, Modifier.align(Alignment.TopCenter)) + } + IconPill(stringResource(R.string.glow_summary_map_close), onClose, Modifier.align(Alignment.TopEnd)) + if (rows.isNotEmpty()) { + SplitPicker( + rows, + selected, + onSelect = { + model.selected = it + follow = true + }, + Modifier.align(Alignment.BottomStart).onSizeChanged { pickerHeight = with(density) { it.height.toDp() } }, + ) + } + } + } +} diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutScreen.kt index f0c17801..6ae2b068 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutScreen.kt @@ -6,6 +6,7 @@ import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import org.openstrap.app.presentation.Ranges import androidx.activity.compose.BackHandler +import androidx.lifecycle.viewmodel.compose.viewModel import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -175,12 +176,14 @@ private fun PastSummary( dayActiveKcal: Float?, onOpenDay: (() -> Unit)?, foundTag: Boolean, + routeMap: RouteMapModel = viewModel(), ) { val heartZones = LocalHeartZones.current val a = summary.analysis val w = a.workout val list = rememberLazyListState() var info by rememberSaveable { mutableStateOf(false) } + if (routeMap.isOpen(w.start)) FullScreenRouteMap(summary, routeMap) { routeMap.close() } val others = remember(workouts, w.start) { workouts.filter { it.workout.start != w.start }.sortedByDescending { it.workout.start } } val usual = remember(others) { Workouts.usualLoad(others.map { it.workout.trainingLoad }) } val family = org.openstrap.app.ui.workout.FamilySummary.familyOf(w.sportType, summary.structure) @@ -210,7 +213,7 @@ private fun PastSummary( else SummaryHero(h.value, h.unit, h.figures, WorkoutDetailCopy.sentence(w.sportType, a.activeSeconds, w.trainingLoad, usual, zones.toList()), h.line) } SummaryHeroCard(hero, mainZoneColor(zones, familyColor(family)), Workouts.effort(w.trainingLoad, usual)) - FamilySection(family, summary, emptyList(), others, weekStarts, heartLine = false) + FamilySection(family, summary, emptyList(), others, weekStarts, heartLine = false, onOpenMap = { routeMap.open(w.start) }) // Always there, even before any heart rate, since it holds Trim. HeartRateCard(a, trim) val facts = WorkoutDetailCopy.facts( diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutSummary.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutSummary.kt index 2a366c3f..b1efb47e 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutSummary.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutSummary.kt @@ -5,10 +5,12 @@ import org.openstrap.app.presentation.Units import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.activity.compose.BackHandler +import androidx.lifecycle.viewmodel.compose.viewModel import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.background +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues @@ -32,6 +34,8 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset @@ -115,6 +119,7 @@ fun GlowWorkoutSummaryScreen( /** What it earned ([RewardsCopy.summary]), null while it's worked out. */ rewards: SummaryRewards? = null, celebrations: Celebrations? = null, + routeMap: RouteMapModel = viewModel(), ) { val a = summary?.analysis // Done goes through the celebrations it earned (workouts spec 3.4): a personal best's card, then the goal moment @@ -144,6 +149,10 @@ fun GlowWorkoutSummaryScreen( } BackHandler(onBack = done) var info by rememberSaveable { mutableStateOf(false) } + // The full-screen route map is a dialog hosted here, with its state in a ViewModel (see RouteMapModel). + if (summary != null && routeMap.isOpen(summary.analysis.workout.start)) { + FullScreenRouteMap(summary, routeMap) { routeMap.close() } + } val hero = remember(summary, workouts) { if (summary == null || a == null) null else summaryHero(FamilySummary.familyOf(a.workout.sportType, summary.structure), summary, Workouts.usualLoad(workouts.filter { it.workout.start != a.workout.start }.map { it.workout.trainingLoad })) @@ -213,7 +222,7 @@ fun GlowWorkoutSummaryScreen( // What was done to the times, under the hero that says them. TrimNote(summary, trim.undo, Modifier.padding(horizontal = 4.dp), onCard = false) val weekStarts = remember(workouts) { goalWeekStarts(workouts) } - FamilySection(family, summary, liveRoute, others, weekStarts, week = rewards?.week) + FamilySection(family, summary, liveRoute, others, weekStarts, week = rewards?.week, onOpenMap = { routeMap.open(w.start) }) EarnedChips(earned) // The drop only with heart rate to show: recorded in the workout, or arriving live after it. val live = calmDown?.takeIf { it.start == w.start } @@ -328,16 +337,23 @@ private fun DropLine(readings: List>, end: Long, modifier: Modif } } -/** The kept route in its zones' colours; nothing without a route that goes somewhere. */ +/** + * The kept route in its zones' colours; nothing without a route that goes somewhere. Tapping the map calls [onOpen] + * when it is given. + */ @Composable -internal fun RouteMap(summary: PhoneSummary, modifier: Modifier = Modifier) { - val heartZones = LocalHeartZones.current +internal fun RouteMap(summary: PhoneSummary, modifier: Modifier = Modifier, onOpen: (() -> Unit)? = null) { if (!Route.mappable(summary.route)) return - val stretches = remember(summary, heartZones) { - Route.byZone(summary.route, summary.history, summary.analysis.maxHeartRate, heartZones) - } + val stretches = rememberZoneStretches(summary) + val open = stringResource(R.string.glow_summary_map_open) Box(modifier.fillMaxWidth().height(170.dp).clip(GlowLayout.TileShape).background(Raised)) { WorkoutMap(stretches, routeOnly = false, Modifier.fillMaxSize()) + // The live map takes touches itself, so a layer above it catches the tap: the card's map is a preview. + if (onOpen != null) { + Box( + Modifier.matchParentSize().clickable(onClickLabel = open, onClick = onOpen).semantics { contentDescription = open }, + ) + } } } @@ -406,9 +422,7 @@ internal fun SplitsList(summary: PhoneSummary, liveRoute: List, mar val a = summary.analysis val maxHr = a.maxHeartRate val route = summary.route.ifEmpty { liveRoute.filter { it.t in a.shownStart..a.end } } - val rows = remember(route, summary) { SummaryCopy.splitRows( - Route.splits(route, summary.pauses), summary.history, route.firstOrNull()?.t, summary.distanceMeters?.takeIf { !summary.distanceFromSteps }, - ) } + val rows = remember(route, summary) { splitRowsFor(summary, route) } val laps = summary.laps.takeIf { it.size > 1 }.orEmpty() val sets = summary.sets.filter { it.end != null } // Each row's heart takes the zone its average heart rate sat in. diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/KmMarkers.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/KmMarkers.kt new file mode 100644 index 00000000..519c2a5c --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/KmMarkers.kt @@ -0,0 +1,43 @@ +package org.openstrap.app.ui.glow + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Typeface +import org.openstrap.app.data.Route + +/** The marker number's size, and a smaller one so three digits still sit inside the ring. */ +private const val KM_TEXT_DP = 11f +private const val KM_TEXT_3_DIGITS_DP = 8f + +/** Each marker a Point feature whose `icon` names its image, `km-`, added to the style by [WorkoutMap]. */ +internal fun kmMarkerFeatures(markers: List>): String = + markers.joinToString(",", """{"type":"FeatureCollection","features":[""", "]}") { (km, p) -> + """{"type":"Feature","geometry":{"type":"Point","coordinates":[${coord(p)}]},"properties":{"icon":"km-$km"}}""" + } + +/** + * Kilometre [km]'s marker: a 22 dp dark circle, as the start dot, ringed in white, its number in bold white. A bitmap, + * not a map text label, since a label needs a font from the tile host and Route only makes no requests. + */ +internal fun kmMarkerBitmap(km: Int, density: Float): Bitmap { + val size = (22 * density).toInt() + val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) + val canvas = Canvas(bitmap) + val c = size / 2f + val ring = 2 * density + val paint = Paint(Paint.ANTI_ALIAS_FLAG) + paint.color = 0xFF121316.toInt() + canvas.drawCircle(c, c, c - ring / 2, paint) + paint.style = Paint.Style.STROKE + paint.strokeWidth = ring + paint.color = android.graphics.Color.WHITE + canvas.drawCircle(c, c, c - ring / 2, paint) + paint.style = Paint.Style.FILL + paint.typeface = Typeface.DEFAULT_BOLD + paint.textAlign = Paint.Align.CENTER + val label = km.toString() + paint.textSize = (if (label.length > 2) KM_TEXT_3_DIGITS_DP else KM_TEXT_DP) * density + canvas.drawText(label, c, c - (paint.descent() + paint.ascent()) / 2, paint) + return bitmap +} diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/RouteMapModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/RouteMapModel.kt new file mode 100644 index 00000000..c27ecdfc --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/RouteMapModel.kt @@ -0,0 +1,30 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel + +/** + * What the full-screen route map keeps: which workout's map is open ([openFor], its start), Route only and the selected + * split. A ViewModel, not `rememberSaveable`: a page's saved state is keyed by where it sits in the layout tree, and the + * phone's stack and the wide screen's pane put it in different places, so each orientation kept its own stale copy. + */ +class RouteMapModel : ViewModel() { + var openFor by mutableStateOf(null) + private set + var routeOnly by mutableStateOf(false) + var selected by mutableStateOf(null) + + fun isOpen(start: Long) = openFor == start + + fun open(start: Long) { + openFor = start + routeOnly = false + selected = null + } + + fun close() { + openFor = null + } +} diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/SplitPicker.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/SplitPicker.kt new file mode 100644 index 00000000..88a53250 --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/SplitPicker.kt @@ -0,0 +1,58 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import org.openstrap.app.data.Route +import org.openstrap.app.ui.components.pressClickable +import org.openstrap.app.ui.theme.ControlSurface +import org.openstrap.app.ui.workout.PhoneSummary +import org.openstrap.app.ui.workout.SplitRow +import org.openstrap.app.ui.workout.SummaryCopy + +/** + * The Splits list's rows as chips along the full-screen map, name over time; the [selected] one lit white. Tapping a + * chip selects it, tapping the selected one clears it ([onSelect] null). + */ +// The rows are remembered once per summary, so a stable list type wouldn't let this skip any more often. +@Suppress("UnstableCollections", "ComposeUnstableCollections") +@Composable +internal fun SplitPicker(rows: List, selected: Int?, onSelect: (Int?) -> Unit, modifier: Modifier = Modifier) { + LazyRow(modifier, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + itemsIndexed(rows) { i, row -> + val on = i == selected + val ink = if (on) ControlSurface else Color.White + Column( + Modifier.clip(CircleShape).background(if (on) Color.White else ControlSurface) + .pressClickable({ onSelect(if (on) null else i) }, CircleShape) + .semantics { this.selected = on } + .padding(horizontal = 16.dp, vertical = 6.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text(row.name, color = ink, style = GlowType.body, maxLines = 1) + Text(row.time, color = ink.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.caption, maxLines = 1) + } + } + } +} + +/** The Splits list's rows along [route], one per [Route.legs] kilometre shown: the list and the map's picker share them. */ +internal fun splitRowsFor(summary: PhoneSummary, route: List): List = SummaryCopy.splitRows( + Route.splits(route, summary.pauses), + summary.history, + route.firstOrNull()?.t, + summary.distanceMeters?.takeIf { !summary.distanceFromSteps }, +) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/SummarySections.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/SummarySections.kt index 3884226f..60c0649a 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/SummarySections.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/SummarySections.kt @@ -192,6 +192,7 @@ internal fun FamilySection( /** False on a past workout's page, whose heart rate card has the line already: the lines under it stay. */ heartLine: Boolean = true, week: Rewards.WeekLine? = null, + onOpenMap: () -> Unit = {}, ) { val heartZones = LocalHeartZones.current val a = summary.analysis @@ -200,7 +201,7 @@ internal fun FamilySection( val zones = remember(a) { ZoneSeconds(a.zoneSeconds) } when (family) { Workouts.Family.Distance -> { - RouteCard(summary) + RouteCard(summary, onOpenMap) SplitsList(summary, liveRoute, markFastest = true) } Workouts.Family.IndoorCardio -> { @@ -255,12 +256,12 @@ internal fun FamilySection( /** The kept route in its zones' colours with the climb; nothing without a route that goes somewhere. */ @Composable -private fun RouteCard(summary: PhoneSummary) { +private fun RouteCard(summary: PhoneSummary, onOpenMap: () -> Unit) { if (!Route.mappable(summary.route)) return PictureCard(MetricColors.steps, Modifier.fillMaxWidth()) { val climb = Route.climb(summary.route)?.let { stringResource(R.string.glow_summary_climb, Math.round(it)) } EdgeTitle(stringResource(R.string.glow_summary_route), climb) - RouteMap(summary, Modifier.padding(top = 12.dp)) + RouteMap(summary, Modifier.padding(top = 12.dp), onOpen = onOpenMap) } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/WorkoutMap.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/WorkoutMap.kt index 5dcaca2b..495dd9ea 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/WorkoutMap.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/WorkoutMap.kt @@ -36,6 +36,7 @@ import org.maplibre.android.style.layers.CircleLayer import org.maplibre.android.style.layers.LineLayer import org.maplibre.android.style.layers.Property import org.maplibre.android.style.layers.PropertyFactory +import org.maplibre.android.style.layers.SymbolLayer import org.maplibre.android.style.sources.GeoJsonSource import org.openstrap.app.data.Route import org.openstrap.app.ui.workout.ZONE_COLORS @@ -56,8 +57,11 @@ private const val BLANK_STYLE = """{"version":8,"sources":{},"layers":[{"id":"bg * line's end, ringed in [hereColor] when given; the start is a hollow dot. [routeOnly] loads no map tiles: the tile * server never learns where the map is. While [follow], the camera fits the whole route as it grows inside * [fitPadding] (clear of what's drawn over the map), or centres on the dot until then; a drag on the map calls - * [onPanned], so the caller can stop following. + * [onPanned], so the caller can stop following. [kmMarkers] puts a numbered circle at each kilometre's end; a + * [highlight] of two or more points is drawn with a white casing under the line, and fitted instead of the route. */ +// Callers remember their lists, so a stable list type wouldn't let this skip any more often. +@Suppress("UnstableCollections", "ComposeUnstableCollections") @Composable fun WorkoutMap( stretches: List, Int>>, routeOnly: Boolean, modifier: Modifier = Modifier, here: Route.Point? = null, @@ -67,6 +71,8 @@ fun WorkoutMap( hereColor: Color? = null, follow: Boolean = true, onPanned: () -> Unit = {}, + kmMarkers: List> = emptyList(), + highlight: List = emptyList(), ) { // A preview or a layout test has no native map library: the route only map's black stands in for it. if (LocalInspectionMode.current) { @@ -91,10 +97,7 @@ fun WorkoutMap( m.setMaxZoomPreference(MAX_ZOOM) // MapLibre's licence doesn't ask for its logo; the ⓘ stays, for the OpenStreetMap credit the tiles need. m.uiSettings.isLogoEnabled = false - // In the bottom-right corner, inset to clear the card's rounded edge. - val inset = (18 * context.resources.displayMetrics.density).toInt() m.uiSettings.attributionGravity = android.view.Gravity.BOTTOM or android.view.Gravity.END - m.uiSettings.setAttributionMargins(0, 0, inset, with(density) { creditBottom.roundToPx() }) m.addOnCameraMoveStartedListener { reason -> if (reason == MapLibreMap.OnCameraMoveStartedListener.REASON_API_GESTURE) panned() } @@ -118,6 +121,11 @@ fun WorkoutMap( view.onDestroy() } } + // In the bottom-right corner, inset to clear the card's rounded edge; set again when what's under it changes height. + LaunchedEffect(map, creditBottom) { + val inset = (18 * context.resources.displayMetrics.density).toInt() + map?.uiSettings?.setAttributionMargins(0, 0, inset, with(density) { creditBottom.roundToPx() }) + } LaunchedEffect(map, routeOnly) { val m = map ?: return@LaunchedEffect style = null @@ -126,6 +134,8 @@ fun WorkoutMap( s.addSource(GeoJsonSource(SOURCE, geoJson(emptyList()))) s.addSource(GeoJsonSource(HERE, geoJson(emptyList()))) s.addSource(GeoJsonSource(START, geoJson(emptyList()))) + s.addSource(GeoJsonSource(KM_SRC, geoJson(emptyList()))) + s.addSource(GeoJsonSource(HIGHLIGHT_SRC, geoJson(emptyList()))) s.addLayer( CircleLayer(START_DOT, START).withProperties( PropertyFactory.circleRadius(5f), @@ -142,6 +152,22 @@ fun WorkoutMap( PropertyFactory.lineJoin(Property.LINE_JOIN_ROUND), ), ) + s.addLayerBelow( + LineLayer(HIGHLIGHT_LINE, HIGHLIGHT_SRC).withProperties( + PropertyFactory.lineColor(Color.White.toArgb()), + PropertyFactory.lineWidth(HIGHLIGHT_WIDTH), + PropertyFactory.lineCap(Property.LINE_CAP_ROUND), + PropertyFactory.lineJoin(Property.LINE_JOIN_ROUND), + ), + LINE, + ) + s.addLayer( + SymbolLayer(KM_LAYER, KM_SRC).withProperties( + PropertyFactory.iconImage(Expression.get("icon")), + PropertyFactory.iconAllowOverlap(true), + PropertyFactory.iconIgnorePlacement(true), + ), + ) s.addLayer( CircleLayer(HALO, HERE).withProperties( PropertyFactory.circleRadius(18f), @@ -168,7 +194,12 @@ fun WorkoutMap( ).toTypedArray(), ) } - LaunchedEffect(style, stretches, here, follow) { + // Again for each new style: switching Route only replaces the style, and its images with it. + LaunchedEffect(style, kmMarkers) { style?.showKmMarkers(kmMarkers, density.density) } + LaunchedEffect(style, highlight) { + style?.getSourceAs(HIGHLIGHT_SRC)?.setGeoJson(highlightGeoJson(highlight)) + } + LaunchedEffect(style, stretches, here, follow, highlight, fitPadding) { val s = style ?: return@LaunchedEffect s.getSourceAs(SOURCE)?.setGeoJson(geoJson(stretches)) val last = here ?: stretches.lastOrNull()?.first?.lastOrNull() @@ -176,8 +207,9 @@ fun WorkoutMap( val all = stretches.flatMap { it.first } s.getSourceAs(START)?.setGeoJson(point(all.firstOrNull()?.takeIf { all.size >= 2 })) if (!follow) return@LaunchedEffect - if (all.size >= 2) { - val bounds = LatLngBounds.Builder().includes(all.map { LatLng(it.lat, it.lon) }).build() + val fit = fitTo(highlight, all) + if (fit.size >= 2) { + val bounds = LatLngBounds.Builder().includes(fit.map { LatLng(it.lat, it.lon) }).build() val px = with(density) { listOf(fitPadding.calculateLeftPadding(LayoutDirection.Ltr), fitPadding.calculateTopPadding(), fitPadding.calculateRightPadding(LayoutDirection.Ltr), fitPadding.calculateBottomPadding()).map { it.roundToPx() } } runCatching { map?.easeCamera(CameraUpdateFactory.newLatLngBounds(bounds, px[0], px[1], px[2], px[3])) } } else if (last != null) { @@ -197,13 +229,37 @@ private const val DOT = "here-dot" private const val HALO = "here-halo" private const val START = "start" private const val START_DOT = "start-dot" +private const val KM_SRC = "km" +private const val KM_LAYER = "km-markers" +private const val HIGHLIGHT_SRC = "highlight" +private const val HIGHLIGHT_LINE = "highlight-line" + +/** Twice the route line's width, so the casing shows on both sides of it. */ +private const val HIGHLIGHT_WIDTH = 10f + +/** Each marker's image, then the markers: the style has no images of its own, and a new style drops added ones. */ +private fun Style.showKmMarkers(markers: List>, density: Float) { + markers.forEach { (km, _) -> addImage("km-$km", kmMarkerBitmap(km, density)) } + getSourceAs(KM_SRC)?.setGeoJson(kmMarkerFeatures(markers)) +} /** One point as GeoJSON, or nothing. */ private fun point(p: Route.Point?): String = p?.let { """{"type":"Feature","geometry":{"type":"Point","coordinates":[${coord(it)}]},"properties":{}}""" } ?: """{"type":"FeatureCollection","features":[]}""" -private fun coord(p: Route.Point) = String.format(Locale.ROOT, "%.7f,%.7f", p.lon, p.lat) +internal fun coord(p: Route.Point) = String.format(Locale.ROOT, "%.7f,%.7f", p.lon, p.lat) + +/** What the camera fits: the [highlight] when it can be drawn, else the whole route. */ +private fun fitTo(highlight: List, all: List) = if (highlight.size >= 2) highlight else all + +/** [points] as one LineString feature, or none under two points. */ +internal fun highlightGeoJson(points: List): String = if (points.size < 2) { + """{"type":"FeatureCollection","features":[]}""" +} else { + """{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"LineString","coordinates":[""" + + points.joinToString(",") { "[${coord(it)}]" } + "]}}]}" +} /** Each stretch a LineString feature with its zone's colour (grey without heart rate). */ private fun geoJson(stretches: List, Int>>): String = buildString { diff --git a/app/src/main/res/values/strings_glow_summary.xml b/app/src/main/res/values/strings_glow_summary.xml index bada8171..27e8c3a7 100644 --- a/app/src/main/res/values/strings_glow_summary.xml +++ b/app/src/main/res/values/strings_glow_summary.xml @@ -95,6 +95,16 @@ Route Climb %1$d m + + Open map full screen + + Close + + Route only + + Show map + + Fit route Sets diff --git a/app/src/test/kotlin/org/openstrap/app/data/RouteTest.kt b/app/src/test/kotlin/org/openstrap/app/data/RouteTest.kt index 6eb73866..fa0e3bce 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/RouteTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/RouteTest.kt @@ -74,6 +74,36 @@ class RouteTest { assertTrue(s[2].meters < 1000) } + @Test + fun `legs cut the track at each kilometre`() { + val legs = Route.legs(run(1200)) + assertEquals(4, legs.size) + for (i in 0..2) assertEquals(1000.0, legs[i].points.zipWithNext().sumOf { (a, b) -> Route.meters(a, b) }, 15.0) + for (i in 0 until legs.lastIndex) assertEquals(legs[i].points.last(), legs[i + 1].points.first()) + } + + @Test + fun `legs and splits agree`() { + assertEquals(Route.splits(run(1200)), Route.legs(run(1200)).map { it.split }) + } + + @Test + fun `a run under a kilometre is one part leg`() { + val legs = Route.legs(run(100)) + assertEquals(1, legs.size) + assertTrue(legs[0].split.meters < 1000.0) + } + + @Test + fun `a pause stays out of a leg's metres`() { + val pauses = listOf(500L..600L) + val legs = Route.legs(run(1200), pauses) + val leg = legs.single { it.points.first().t < 550 && it.points.last().t > 550 } + assertEquals(1000.0, leg.split.meters, 15.0) + val whole = Route.legs(run(1200)).sumOf { it.split.meters } + assertEquals(whole - 300.0, legs.sumOf { it.split.meters }, 15.0) + } + @Test fun currentPace() { assertEquals(333.0, Route.currentPace(run(100))!!, 2.0) diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMapRotationTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMapRotationTest.kt new file mode 100644 index 00000000..a4c8410a --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMapRotationTest.kt @@ -0,0 +1,126 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.foundation.clickable +import androidx.compose.material3.Text +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.assertIsNotSelected +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.ViewModelStoreOwner +import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner +import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.test.core.app.ApplicationProvider +import org.openstrap.app.ui.components.ListDetail +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.openstrap.app.R +import org.openstrap.app.data.HeartZones +import org.openstrap.app.data.Route +import org.openstrap.app.data.WorkoutRecorder +import org.openstrap.app.data.db.AppWorkout +import org.openstrap.app.testing.ComposeRules +import org.openstrap.app.ui.workout.PhoneSummary +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * The map's state through what a real device does: the page moves between the phone's stack and the wide screen's pane + * (different places in the layout tree), and a rotation builds everything again around the same ViewModelStore. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35], qualifiers = "w900dp-h891dp") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class FullScreenRouteMapRotationTest { + @get:Rule val rules = ComposeRules() + + private val start = 1_792_000_000L + private val app get() = ApplicationProvider.getApplicationContext() + private fun text(id: Int) = app.getString(id) + + /** A 3 m/s run east along the equator, a fix a second: 1167 s is about 3.5 km, so Km 1 to 3 and a last part. */ + private fun summary(seconds: Int = 1167): PhoneSummary { + val w = AppWorkout(start, start + seconds, 1) + val route = (0..seconds).map { Route.Point(start + it, 0.0, it * 3.0 / 111_195.0, 5f) } + val analysis = WorkoutRecorder.analyse(w, emptyList(), 190, HeartZones.STANDARD) + return PhoneSummary(analysis, emptyList(), start, start + seconds, null, route = route) + } + + private fun km(n: Int) = app.getString(R.string.workout_summary_split_km, n) + private val last get() = text(R.string.workout_summary_split_last).substringBefore('%') + + private fun assertOnlyKm2Selected() { + rules.compose.onNodeWithText(km(2)).assertIsSelected() + rules.compose.onNodeWithText(km(1)).assertIsNotSelected() + rules.compose.onNodeWithText(km(3)).assertIsNotSelected() + rules.compose.onNodeWithText(last, substring = true).assertIsNotSelected() + } + + private val store = ViewModelStore() + private val owner = object : ViewModelStoreOwner { override val viewModelStore = store } + private var wide by mutableStateOf(false) + private var generation by mutableStateOf(0) + + /** The workout page as a pane or a stack page, hosting the map as the real pages do. */ + @Composable private fun Page(model: RouteMapModel = viewModel()) { + Text("open map", Modifier.clickable { model.open(start) }) + if (model.isOpen(start)) FullScreenRouteMap(summary(), model) { model.close() } + } + + private fun host() = rules.compose.setContent { + CompositionLocalProvider(LocalInspectionMode provides true, LocalViewModelStoreOwner provides owner) { + key(generation) { + Box(Modifier.width(if (wide) 800.dp else 400.dp)) { + ListDetail("p", { true }, { listOf("p") }, 720.dp, detail = { Page() }, list = { Text("list") }) + } + } + } + } + + private fun layout(isWide: Boolean) { wide = isWide; rules.compose.waitForIdle() } + private fun rotate() { generation++; rules.compose.waitForIdle() } + private fun assertClosed() = rules.compose.onAllNodesWithText(text(R.string.glow_summary_map_close)).assertCountEquals(0) + + @Test fun `an open map keeps its split and Route only across layouts and rotations`() { + host() + rules.compose.onNodeWithText("open map").performClick() + rules.compose.onNodeWithText(km(2)).performClick() + rules.compose.onNodeWithText(text(R.string.glow_summary_map_route_only)).performClick() + layout(true) + assertOnlyKm2Selected() + rules.compose.onNodeWithText(text(R.string.glow_summary_map_show_map)).assertExists() + rotate() + assertOnlyKm2Selected() + layout(false) + assertOnlyKm2Selected() + } + + @Test fun `a closed map stays closed across layouts and rotations`() { + host() + layout(true) + rules.compose.onNodeWithText("open map").performClick() + rules.compose.onNodeWithText(text(R.string.glow_summary_map_close)).performClick() + assertClosed() + layout(false) + assertClosed() + layout(true) + assertClosed() + rotate() + assertClosed() + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMapTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMapTest.kt new file mode 100644 index 00000000..cac93698 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMapTest.kt @@ -0,0 +1,105 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertIsNotSelected +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.openstrap.app.R +import org.openstrap.app.data.HeartZones +import org.openstrap.app.data.Route +import org.openstrap.app.data.WorkoutRecorder +import org.openstrap.app.data.db.AppWorkout +import org.openstrap.app.testing.ComposeRules +import org.openstrap.app.ui.workout.PhoneSummary +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** The full-screen route map: its pills, and the summary's route card map that opens it. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35], qualifiers = "w411dp-h891dp-port") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class FullScreenRouteMapTest { + @get:Rule val rules = ComposeRules() + + private val start = 1_792_000_000L + + private val app get() = ApplicationProvider.getApplicationContext() + + private fun text(id: Int) = app.getString(id) + + /** A 3 m/s run east along the equator, a fix a second, [seconds] long. */ + private fun summary(seconds: Int = 40): PhoneSummary { + val w = AppWorkout(start, start + seconds, 1) + val route = (0..seconds).map { Route.Point(start + it, 0.0, it * 3.0 / 111_195.0, 5f) } + val analysis = WorkoutRecorder.analyse(w, emptyList(), 190, HeartZones.STANDARD) + return PhoneSummary(analysis, emptyList(), start, start + seconds, null, route = route) + } + + private fun show(content: @androidx.compose.runtime.Composable () -> Unit) { + rules.compose.setContent { CompositionLocalProvider(LocalInspectionMode provides true) { content() } } + } + + @Test fun `closing calls onClose`() { + var closed = 0 + show { FullScreenRouteMapContent(summary(), remember { RouteMapModel() }) { closed++ } } + rules.compose.onNodeWithText(text(R.string.glow_summary_map_close)).performClick() + assertEquals(1, closed) + } + + @Test fun `route only can be switched on and back`() { + show { FullScreenRouteMapContent(summary(), remember { RouteMapModel() }) {} } + rules.compose.onNodeWithText(text(R.string.glow_summary_map_route_only)).performClick() + rules.compose.onNodeWithText(text(R.string.glow_summary_map_show_map)).performClick() + rules.compose.onNodeWithText(text(R.string.glow_summary_map_route_only)).assertExists() + } + + @Test fun `fit route shows only after the map was panned`() { + show { FullScreenRouteMapContent(summary(), remember { RouteMapModel() }) {} } + rules.compose.onAllNodesWithText(text(R.string.glow_summary_map_fit)).assertCountEquals(0) + } + + @Test fun `the summary's route card map opens it`() { + var opened = 0 + show { RouteMap(summary(), onOpen = { opened++ }) } + rules.compose.onNodeWithContentDescription(text(R.string.glow_summary_map_open)).performClick() + assertEquals(1, opened) + } + + @Test fun `the picker lists each kilometre and the last part`() { + show { FullScreenRouteMapContent(summary(seconds = 1167), remember { RouteMapModel() }) {} } + for (km in 1..3) rules.compose.onNodeWithText(app.getString(R.string.workout_summary_split_km, km)).assertExists() + val last = text(R.string.workout_summary_split_last).substringBefore('%') + rules.compose.onNodeWithText(last, substring = true).assertExists() + } + + @Test fun `tapping a split selects it and tapping it again clears it`() { + show { FullScreenRouteMapContent(summary(seconds = 1167), remember { RouteMapModel() }) {} } + val km2 = rules.compose.onNodeWithText(app.getString(R.string.workout_summary_split_km, 2)) + km2.performClick() + km2.assertIsSelected() + km2.performClick() + km2.assertIsNotSelected() + } + + @Test fun `a run under a kilometre shows only its last-part chip`() { + show { FullScreenRouteMapContent(summary(seconds = 134), remember { RouteMapModel() }) {} } + rules.compose.onAllNodesWithText(app.getString(R.string.workout_summary_split_km, 1)).assertCountEquals(0) + val chip = rules.compose.onNodeWithText(text(R.string.workout_summary_split_last).substringBefore('%'), substring = true) + chip.performClick() + chip.assertIsSelected() + chip.performClick() + chip.assertIsNotSelected() + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/KmMarkersTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/KmMarkersTest.kt new file mode 100644 index 00000000..8c382127 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/KmMarkersTest.kt @@ -0,0 +1,50 @@ +package org.openstrap.app.ui.glow + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.openstrap.app.data.Route +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** The full-screen map's km markers and split highlight, as GeoJSON and bitmaps. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class KmMarkersTest { + private val p1 = Route.Point(0, 1.5, 10.25, 5f) + private val p2 = Route.Point(1, 1.6, 10.35, 5f) + + @Test fun `features carry the km as an icon name`() { + val features = JSONObject(kmMarkerFeatures(listOf(1 to p1, 2 to p2))).getJSONArray("features") + assertEquals(2, features.length()) + assertEquals("km-1", features.getJSONObject(0).getJSONObject("properties").getString("icon")) + assertEquals("km-2", features.getJSONObject(1).getJSONObject("properties").getString("icon")) + val coordinates = features.getJSONObject(0).getJSONObject("geometry").getJSONArray("coordinates") + assertEquals(10.25, coordinates.getDouble(0), 1e-9) + assertEquals(1.5, coordinates.getDouble(1), 1e-9) + } + + @Test fun `a marker bitmap is square, sized by density, and drawn`() { + val b = kmMarkerBitmap(7, 2f) + assertEquals(44, b.width) + assertEquals(44, b.height) + assertNotEquals(0, b.getPixel(22, 22) ushr 24) + } + + @Test fun `three digits still fit`() { + val b = kmMarkerBitmap(123, 2f) + assertEquals(44, b.width) + assertEquals(44, b.height) + } + + @Test fun `highlight needs two points`() { + assertEquals(0, JSONObject(highlightGeoJson(emptyList())).getJSONArray("features").length()) + val one = JSONObject(highlightGeoJson(listOf(p1, p2))).getJSONArray("features") + assertEquals(1, one.length()) + assertEquals("LineString", one.getJSONObject(0).getJSONObject("geometry").getString("type")) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/RouteMapModelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/RouteMapModelTest.kt new file mode 100644 index 00000000..e84f507b --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/RouteMapModelTest.kt @@ -0,0 +1,28 @@ +package org.openstrap.app.ui.glow + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class RouteMapModelTest { + @Test fun `opening is per workout and resets the choices`() { + val m = RouteMapModel() + m.routeOnly = true + m.selected = 3 + m.open(10L) + assertTrue(m.isOpen(10L)) + assertFalse(m.isOpen(11L)) + assertFalse(m.routeOnly) + assertNull(m.selected) + } + + @Test fun `closing closes for every workout and keeps nothing open`() { + val m = RouteMapModel() + m.open(10L) + m.close() + assertFalse(m.isOpen(10L)) + assertEquals(null, m.openFor) + } +} diff --git a/docs/superpowers/plans/2026-11-05-outdoor-run-map-and-gpx.md b/docs/superpowers/plans/2026-11-05-outdoor-run-map-and-gpx.md new file mode 100644 index 00000000..42efcd8c --- /dev/null +++ b/docs/superpowers/plans/2026-11-05-outdoor-run-map-and-gpx.md @@ -0,0 +1,247 @@ +# Outdoor Run: Full-Screen Map, Km Markers, Split Highlight and GPX Export Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** From a finished GPS workout's Route card, open the map full screen with a numbered marker at each kilometre and a split picker that highlights one kilometre on the map, and export the run as a GPX file. + +**Architecture:** All of it hangs off the existing `RouteCard` (`ui/glow/SummarySections.kt`), which the just-finished summary and a past workout's page both render. The full-screen map is a `Dialog` hosting the existing `WorkoutMap`, so no navigation changes. Km markers are bitmaps drawn with `android.graphics` and added to the map style as images, so they need no font download and work in route-only mode with no network. Split highlight reuses the existing split rows (`SummaryCopy.splitRows`) and a new `Route.legs` that returns each kilometre's points. GPX is a pure-Kotlin writer over the already cleaned `Route.track`, handed to the system share sheet through the existing `share/` FileProvider path. Two stacked branches, made with git-spice. + +**Tech Stack:** Kotlin, Jetpack Compose, MapLibre (`WorkoutMap`), Room entities already in place, JUnit4 + Robolectric (`ComposeRules`). + +**Spec:** `docs/superpowers/specs/2026-11-05-outdoor-run-map-and-gpx-design.md`. Strava upload and a Health Connect `ExerciseRoute` are out of scope for now (see the end). + +## Global Constraints + +- User-facing text goes in `app/src/main/res/values/strings_glow_summary.xml`, never in Kotlin literals (`i18n/HardcodedEnglishTest`). Each string has an XML comment saying where it shows. +- `i18n/StringsParityTest` must stay green; CI also runs `./gradlew :app:testDebugUnitTest -PtestLocale=de-DE`. +- No new network use: export is a local file handed to the share sheet; `docs/privacy.md` says routes never leave the phone. +- No new permissions and no new FileProvider paths: `res/xml/share_paths.xml` already exposes `cache/share/`. +- Commit messages are `type: summary` with no ticket key. End each with the Co-Authored-By line from the session. +- Branches: git-spice only (`gs branch create`, `gs stack submit` as drafts). No worktrees, no plain `git checkout -b`. +- Verification commands: `./gradlew :app:testDebugUnitTest --tests ''`; before submitting also `./gradlew :app:lintDebug detektMain ktlintCheck`. + +## Review Focus + +- A run under 1 km has no km markers, and its "Last N m" chip is still selectable and highlights the whole route (Task 2). +- A run with pauses or a tunnel gap exports as separate ``s, not one line across the gap (Task 3). +- A device in a decimal-comma locale (de-DE) still writes `51.5000000`, not `51,5000000` (Task 3). +- Rotating the phone or process death with the full-screen map open keeps it open, with the same route-only choice and the same selected split (Tasks 1 and 2). +- Switching Route only on and off with a split selected keeps the km markers and the highlight, since the new style drops the images added to the old one (Task 2). +- A workout name with `&`, `<`, `"` produces well-formed XML, and no heart rate or altitude still gives a valid GPX (Task 3, tested there). + +--- + +## Branch 1: `feat/fullscreen-route-map` + +Start with `gs branch create feat/fullscreen-route-map` from `main`. + +### Task 1: Full-screen route map + +**Files:** +- Create: `app/src/main/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMap.kt` +- Modify: `app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutSummary.kt:328-339` (`RouteMap`) +- Modify: `app/src/main/kotlin/org/openstrap/app/ui/glow/SummarySections.kt:268-277` (`RouteCard`) +- Modify: `app/src/main/res/values/strings_glow_summary.xml` (after `glow_summary_climb`) +- Test: `app/src/test/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMapTest.kt` + +**Interfaces:** +- Consumes: `WorkoutMap(stretches, routeOnly, modifier, here, fitPadding, creditBottom, hereColor, follow, onPanned)` (`ui/glow/WorkoutMap.kt`); `Route.byZone(points, hr, maxHr, zones)`; `LocalHeartZones`; `IconPill(label, onClick, modifier, icon, ...)` (`PageParts.kt:690`); `PhoneSummary`. +- Produces: + - `@Composable internal fun rememberZoneStretches(summary: PhoneSummary): List, Int>>`, extracted from `RouteMap` so both maps colour the line the same way. + - `@Composable internal fun FullScreenRouteMap(summary: PhoneSummary, onClose: () -> Unit)`: a `Dialog` (`usePlatformDefaultWidth = false`, `decorFitsSystemWindows = false`, `onDismissRequest = onClose`) around the content below. + - `@Composable internal fun FullScreenRouteMapContent(summary: PhoneSummary, onClose: () -> Unit)`: the map and its pills, without the `Dialog`, so tests need no window. + - `RouteMap(summary, modifier, onOpen: (() -> Unit)? = null)`: the card's map becomes tappable when `onOpen` is given. + +- [ ] **Step 1: Write the failing test** in `FullScreenRouteMapTest` (Robolectric, `ComposeRules`, content wrapped in `CompositionLocalProvider(LocalInspectionMode provides true)` so `WorkoutMap` draws its black stand-in; see `LiveLandscapeLayoutTest` for the rule and `@Config`). Build a `PhoneSummary` with a mappable route (the `appWorkout` helper in `org.openstrap.app.testing`; a run east of 40 points as in `RouteTest.run`). Tests, with strings read from `R.string`: + - `closing calls onClose`: click the node with text `R.string.glow_summary_map_close`; assert a counter is 1. + - `route only can be switched on and back`: click `glow_summary_map_route_only`, assert the node with text `glow_summary_map_show_map` exists, click it, assert the first label is back. + - `fit route shows only after the map was panned`: assert `glow_summary_map_fit` does not exist initially. (Panning cannot be driven in inspection mode; this pins the initial state only.) + - `the summary's route card map opens it`: render `RouteMap(summary, onOpen = { opened++ })`, click the node with content description `glow_summary_map_open`, assert `opened == 1`. + +- [ ] **Step 2: Run to verify it fails** + +Run: `./gradlew :app:testDebugUnitTest --tests 'org.openstrap.app.ui.glow.FullScreenRouteMapTest'` +Expected: FAIL, compilation error (`FullScreenRouteMapContent` and the strings undefined). + +- [ ] **Step 3: Add the strings** to `strings_glow_summary.xml`, each with a comment: `glow_summary_map_open` ("Open map full screen", content description of the card's map), `glow_summary_map_close` ("Close"), `glow_summary_map_route_only` ("Route only", same wording as `workout_live_map_route_only`), `glow_summary_map_show_map` ("Show map"), `glow_summary_map_fit` ("Fit route"). + +- [ ] **Step 4: Implement `rememberZoneStretches`, `FullScreenRouteMapContent` and `FullScreenRouteMap`** in `FullScreenRouteMap.kt`. Content is a black `Box(fillMaxSize)` with `WorkoutMap(stretches, routeOnly, Modifier.fillMaxSize(), follow = follow, fitPadding = PaddingValues(horizontal = 24.dp, vertical = 96.dp), onPanned = { follow = false })`. `routeOnly` is `rememberSaveable` (default false, matching the card). `follow` is `remember` (true). Pills, inside `WindowInsets.safeDrawing` padding: Close top-end, Route only / Show map top-start, and Fit route top-centre only while `!follow` (tap sets `follow = true`). The bottom edge is left free for Task 2's split picker. Reuse `IconPill`; no new styling. + +- [ ] **Step 5: Wire the card.** `RouteMap` takes `onOpen`; when non-null its `Box` gets `Modifier.clickable(onClickLabel = open label, onClick = onOpen)` and a content description from `glow_summary_map_open`. `RouteCard` holds `var full by rememberSaveable { mutableStateOf(false) }`, passes `onOpen = { full = true }`, and shows `FullScreenRouteMap(summary) { full = false }` while `full`. `RouteMap`'s other caller keeps passing no `onOpen`. + +- [ ] **Step 6: Run the tests** + +Run: `./gradlew :app:testDebugUnitTest --tests 'org.openstrap.app.ui.glow.FullScreenRouteMapTest' --tests 'org.openstrap.app.i18n.*'` +Expected: PASS. + +- [ ] **Step 7: Check on a device.** Per `CLAUDE.md`, check no workout is recording first. Install the debug build, open a past GPS run, tap the route card map. Expect: full screen with the route fitted, drag to pan makes Fit route appear and tapping it refits, Route only shows a plain black map, system Back closes, rotating keeps it open. + +- [ ] **Step 8: Commit** + +```bash +git add -A +git commit -m "feat: open the route map full screen from a workout's summary" +``` + +### Task 2: Km markers and split highlight + +Still on `feat/fullscreen-route-map`. Splits are per kilometre everywhere in the app (`Km 3`), not per mile, so markers and the picker are too. + +**Files:** +- Modify: `app/src/main/kotlin/org/openstrap/app/data/Route.kt` (`splits`, around line 305) +- Modify: `app/src/main/kotlin/org/openstrap/app/ui/glow/WorkoutMap.kt` +- Modify: `app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutSummary.kt:398-410` (`SplitsList`) +- Modify: `app/src/main/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMap.kt` (from Task 1) +- Create: `app/src/main/kotlin/org/openstrap/app/ui/glow/KmMarkers.kt` +- Create: `app/src/main/kotlin/org/openstrap/app/ui/glow/SplitPicker.kt` +- Test: `app/src/test/kotlin/org/openstrap/app/data/RouteTest.kt` (add), `app/src/test/kotlin/org/openstrap/app/ui/glow/KmMarkersTest.kt`, `app/src/test/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMapTest.kt` (add) + +**Interfaces:** +- Consumes: `Route.splits`, `Route.Split(index, endT, seconds, meters)`, `SummaryCopy.splitRows(splits, readings, firstT, totalMeters): List` (`SplitRow(name, time, averageBpm, seconds, kind)`), `workout_summary_split_km` and `workout_summary_split_last` strings, Task 1's `FullScreenRouteMapContent`. +- Produces: + - `Route.Leg(val split: Split, val points: List)` and `Route.legs(points: List, pauses: List = emptyList(), km: Double = 1000.0): List`: the same kilometres as `splits`, each with the smoothed track points it covers, a leg's first point being the previous leg's last. `splits` becomes `legs(...).map { it.split }`, so the two cannot disagree. + - `internal fun splitRowsFor(summary: PhoneSummary, route: List): List` in `GlowWorkoutSummary.kt`, extracted from `SplitsList` (the `SummaryCopy.splitRows(Route.splits(route, summary.pauses), summary.history, route.firstOrNull()?.t, summary.distanceMeters?.takeIf { !summary.distanceFromSteps })` call) so the list and the picker build identical rows. Row `i` is leg `i`. + - `internal fun kmMarkerFeatures(markers: List>): String`: GeoJSON FeatureCollection, one Point feature per marker (lon, lat order), property `icon` = `"km-"`. + - `internal fun kmMarkerBitmap(km: Int, density: Float): Bitmap`: a 22 dp circle, dark fill (`0xFF121316`, as the start dot), white 2 dp ring, the number centred in bold white, text scaled down so 3 digits fit. + - `internal fun highlightGeoJson(points: List): String`: an empty FeatureCollection under 2 points, else one LineString feature. + - `WorkoutMap(..., kmMarkers: List> = emptyList(), highlight: List = emptyList())`: both default to nothing, so the live map is unchanged. + - `@Composable internal fun SplitPicker(rows: List, selected: Int?, onSelect: (Int?) -> Unit, modifier: Modifier = Modifier)`: a `LazyRow` of chips, name over time, the selected one lit white; each chip has `Modifier.semantics { selected = ... }` and `selectable`-style click (tap an unselected chip selects it, tap the selected one clears it). + +- [ ] **Step 1: Write the failing tests.** + - In `RouteTest` (helpers `east`, `run` already there): `legs cut the track at each kilometre` with `run(1200)` (about 3.6 km at 3 m/s): 4 legs; legs 0 to 2 each measure 1000 m ± 15 m summed with `Route.meters`; `legs[i].points.last() == legs[i + 1].points.first()`. `legs and splits agree`: `Route.legs(run(1200)).map { it.split } == Route.splits(run(1200))`. `a run under a kilometre is one part leg`: `Route.legs(run(100))` has one leg with `split.meters < 1000.0`. `a pause stays out of a leg's metres`: pauses `500L..600L` on `run(1200)`: the leg containing it measures 1000 m ± 15 m of unpaused track and the whole-run total is about 100 s × 3 m/s shorter than the unpaused run's. + - `KmMarkersTest` (Robolectric, `@GraphicsMode(NATIVE)`): `features carry the km as an icon name` (markers `1 to p1, 2 to p2` parse with `org.json.JSONObject`: 2 features, `properties.icon` is `km-1` and `km-2`, `coordinates[0]` is the lon); `a marker bitmap is square, sized by density, and drawn` (`kmMarkerBitmap(7, 2f)`: width equals height equals 44, and the centre pixel is not fully transparent); `three digits still fit` (`kmMarkerBitmap(123, 2f)` does not throw and is the same size); `highlight needs two points` (`highlightGeoJson(emptyList())` has no features, a two-point list has one feature of type `LineString`). + - In `FullScreenRouteMapTest`: `the picker lists each kilometre and the last part` (route of 3.5 km: nodes with text `getString(R.string.workout_summary_split_km, 1)` to `3` exist, so does a node starting with the `workout_summary_split_last` text prefix); `tapping a split selects it and tapping it again clears it` (`assertIsSelected()` after the first click on the "Km 2" chip's node, `assertIsNotSelected()` after the second); `a run under a kilometre has no km chips` (route of 400 m: no node with the `workout_summary_split_km` text for 1). + +- [ ] **Step 2: Run to verify they fail** + +Run: `./gradlew :app:testDebugUnitTest --tests 'org.openstrap.app.data.RouteTest' --tests 'org.openstrap.app.ui.glow.KmMarkersTest' --tests 'org.openstrap.app.ui.glow.FullScreenRouteMapTest'` +Expected: FAIL, compilation errors (`Route.legs`, `kmMarkerFeatures` and friends undefined). + +- [ ] **Step 3: Implement `Route.Leg` and `Route.legs`**, moving the body of `splits` into it (the loop over `track(points).zipWithNext()`, skipping paused pairs, closing a leg at `meters >= km`); keep a `current` list of points, seed it with the leg's start point, add each unpaused `b`, and start the next leg's list from the closing point. Make `splits` delegate. Run `RouteTest` alone: the existing splits tests must still pass unchanged. + +- [ ] **Step 4: Implement `splitRowsFor`** and use it in `SplitsList` (behaviour unchanged; `SplitsListTest` or the summary tests that exist must stay green). + +- [ ] **Step 5: Implement `KmMarkers.kt`** (`kmMarkerFeatures`, `kmMarkerBitmap` with `Canvas`, `Paint(ANTI_ALIAS_FLAG)`, `Paint.Align.CENTER`) and `highlightGeoJson` (next to the existing private `geoJson` in `WorkoutMap.kt`, reusing `coord`). + +- [ ] **Step 6: Extend `WorkoutMap`.** In the style-ready callback add a `GeoJsonSource` `KM_SRC` with a `SymbolLayer` `KM_LAYER` (`iconImage(Expression.get("icon"))`, `iconAllowOverlap(true)`, `iconIgnorePlacement(true)`), and a `GeoJsonSource` `HIGHLIGHT_SRC` with a white `LineLayer` (width 10, round caps) added with `addLayerBelow(..., LINE)` so the zone-coloured line sits on top of a white casing. A `LaunchedEffect(style, kmMarkers)` does `style.addImage("km-$n", kmMarkerBitmap(n, density))` for each marker then `setGeoJson(kmMarkerFeatures(kmMarkers))`; it must run again whenever `style` changes, because switching Route only calls `setStyle` and the new style has none of the old images. A `LaunchedEffect(style, highlight)` sets `highlightGeoJson(highlight)`. In the existing camera effect: when `follow` and `highlight.size >= 2`, fit the highlight's bounds (same padding) instead of the whole route. + +- [ ] **Step 7: Implement `SplitPicker`** (`SplitPicker.kt`). Chip label is `row.name`, second line `row.time`; reuse `GlowType` text styles and the pill colours of `IconPill`; no new theme values. + +- [ ] **Step 8: Wire `FullScreenRouteMapContent`.** `val legs = remember(summary) { Route.legs(summary.route, summary.pauses) }`, `val rows = remember(summary) { splitRowsFor(summary, summary.route) }`, `var selected by rememberSaveable { mutableStateOf(null) }`. Pass `kmMarkers = legs.filter { it.split.meters >= 1000.0 }.map { it.split.index + 1 to it.points.last() }` and `highlight = selected?.let { legs.getOrNull(it)?.points }.orEmpty()` to `WorkoutMap`. Place `SplitPicker(rows, selected, onSelect = { selected = it; follow = true })` along the bottom inside `WindowInsets.safeDrawing`; show it only when `rows` is not empty; pass `creditBottom` equal to the picker's height so the OpenStreetMap credit stays visible above it. + +- [ ] **Step 9: Run the tests** + +Run: `./gradlew :app:testDebugUnitTest --tests 'org.openstrap.app.data.*' --tests 'org.openstrap.app.ui.glow.*' --tests 'org.openstrap.app.i18n.*'` +Expected: PASS. + +- [ ] **Step 10: Check on a device.** Open a past run longer than 3 km. Expect: numbered circles at each km along the line; tapping "Km 2" in the picker draws it with a white casing and zooms to it, tapping it again returns to the whole route; Route only keeps markers and highlight and makes no tile requests; a run under 1 km has no markers and only a "Last N m" chip; rotating keeps the selection; the OpenStreetMap credit is visible above the picker. + +- [ ] **Step 11: Commit** + +```bash +git add -A +git commit -m "feat: km markers and split highlight on the full-screen route map" +``` + +--- + +## Branch 2: `feat/gpx-export` + +Start with `gs branch create feat/gpx-export` (stacked on branch 1; the Export pill sits in the same `RouteCard`). + +### Task 3: GPX writer + +**Files:** +- Create: `app/src/main/kotlin/org/openstrap/app/export/GpxWriter.kt` +- Modify: `app/src/main/kotlin/org/openstrap/app/data/Route.kt:411` (`private const val MAX_HR_GAP_S` becomes `const val`, so the writer matches heart rate the same way `byZone` does) +- Test: `app/src/test/kotlin/org/openstrap/app/export/GpxWriterTest.kt` + +**Interfaces:** +- Consumes: `Route.track(points): List`, `Route.MAX_HR_GAP_S` (30 s), `Route.Point`. +- Produces: `object GpxWriter { fun write(name: String, points: List, heartRate: List>, pauses: List = emptyList()): String }`. `heartRate` is (epoch seconds, bpm) ascending, as `PhoneSummary.history`. `pauses` is `PhoneSummary.pauses`. + +Output format (the only decisions the tests do not pin): GPX 1.1, `creator="OpenStrap"`, namespaces `http://www.topografix.com/GPX/1/1` and `gpxtpx` = `http://www.garmin.com/xmlschemas/TrackPointExtension/v1`; one `` with ``; `