Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions app/src/main/kotlin/org/openstrap/app/data/Route.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Point>, pauses: List<LongRange> = emptyList(), km: Double = 1000.0): List<Split> {
fun splits(points: List<Point>, pauses: List<LongRange> = emptyList(), km: Double = 1000.0): List<Split> =
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<Point>)

/** The kilometres of [splits], each with its stretch of the smoothed track; paused stretches are left out. */
fun legs(points: List<Point>, pauses: List<LongRange> = emptyList(), km: Double = 1000.0): List<Leg> {
val clean = track(points)
val out = mutableListOf<Split>()
var startT = clean.firstOrNull()?.t ?: return out
val out = mutableListOf<Leg>()
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
}

Expand Down
112 changes: 112 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/ui/glow/FullScreenRouteMap.kt
Original file line number Diff line number Diff line change
@@ -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<Pair<List<Route.Point>, 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() } },
)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down
34 changes: 24 additions & 10 deletions app/src/main/kotlin/org/openstrap/app/ui/glow/GlowWorkoutSummary.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 }))
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -328,16 +337,23 @@ private fun DropLine(readings: List<Pair<Long, Int>>, 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 },
)
}
}
}

Expand Down Expand Up @@ -406,9 +422,7 @@ internal fun SplitsList(summary: PhoneSummary, liveRoute: List<Route.Point>, 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.
Expand Down
43 changes: 43 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/ui/glow/KmMarkers.kt
Original file line number Diff line number Diff line change
@@ -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-<n>`, added to the style by [WorkoutMap]. */
internal fun kmMarkerFeatures(markers: List<Pair<Int, Route.Point>>): 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
}
30 changes: 30 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/ui/glow/RouteMapModel.kt
Original file line number Diff line number Diff line change
@@ -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<Long?>(null)
private set
var routeOnly by mutableStateOf(false)
var selected by mutableStateOf<Int?>(null)

fun isOpen(start: Long) = openFor == start

fun open(start: Long) {
openFor = start
routeOnly = false
selected = null
}

fun close() {
openFor = null
}
}
Loading