diff --git a/app/detekt-baseline-debug.xml b/app/detekt-baseline-debug.xml index 617a3564..d2cfe78b 100644 --- a/app/detekt-baseline-debug.xml +++ b/app/detekt-baseline-debug.xml @@ -175,6 +175,7 @@ InjectDispatcher:RewardsKeeper.kt:RewardsKeeper$IO InjectDispatcher:ShareScreen.kt:IO InjectDispatcher:StrapService.kt:StrapService$Default + InjectDispatcher:SummarySections.kt:IO InjectDispatcher:ZeppCloud.kt:ZeppCloud$IO LambdaParameterEventTrailing:ActivityDetail.kt:onPick: (Int?) -> Unit LambdaParameterEventTrailing:ChooseScreen.kt:onChange: (String) -> Unit diff --git a/app/detekt-baseline-release.xml b/app/detekt-baseline-release.xml index 707ca60f..6e23d9dc 100644 --- a/app/detekt-baseline-release.xml +++ b/app/detekt-baseline-release.xml @@ -177,6 +177,7 @@ InjectDispatcher:RewardsKeeper.kt:RewardsKeeper$IO InjectDispatcher:ShareScreen.kt:IO InjectDispatcher:StrapService.kt:StrapService$Default + InjectDispatcher:SummarySections.kt:IO InjectDispatcher:ZeppCloud.kt:ZeppCloud$IO LambdaParameterEventTrailing:ActivityDetail.kt:onPick: (Int?) -> Unit LambdaParameterEventTrailing:ChooseScreen.kt:onChange: (String) -> Unit 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..b9edb111 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 } @@ -408,5 +417,5 @@ object Route { return out.filter { it.first.size >= 2 } } - private const val MAX_HR_GAP_S = 30L + const val MAX_HR_GAP_S = 30L } diff --git a/app/src/main/kotlin/org/openstrap/app/export/GpxShare.kt b/app/src/main/kotlin/org/openstrap/app/export/GpxShare.kt new file mode 100644 index 00000000..59efa536 --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/export/GpxShare.kt @@ -0,0 +1,36 @@ +package org.openstrap.app.export + +import android.content.ClipData +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.util.Log +import androidx.core.content.FileProvider +import java.io.File + +private const val TAG = "GpxShare" + +// The FileProvider's authority after the package name, as in the manifest; export/ may not reach ui/ for StoryFiles's copy. +private const val AUTHORITY_SUFFIX = ".share" + +/** A workout's GPX as a cached file another app can read for a moment, through the share FileProvider. */ +internal object GpxShare { + /** Named like the story picture: after the workout's start (epoch seconds). */ + fun fileName(workoutStart: Long) = "unstrap_$workoutStart.gpx" + + /** [gpx] written to [fileName] in the share cache, replacing earlier exports; null when it can't be written. Blocks. */ + fun forSharing(context: Context, fileName: String, gpx: String): Uri? = runCatching { + val dir = File(context.cacheDir, "share").apply { mkdirs() } + dir.listFiles { f -> f.extension == "gpx" }?.forEach { it.delete() } + val file = File(dir, fileName) + file.writeText(gpx) + FileProvider.getUriForFile(context, context.packageName + AUTHORITY_SUFFIX, file) + }.onFailure { Log.w(TAG, "writing the route to share failed", it) }.getOrNull() + + /** Opens the share sheet for [uri]. */ + fun send(context: Context, uri: Uri) { + val send = Intent(Intent.ACTION_SEND).setType("application/gpx+xml").putExtra(Intent.EXTRA_STREAM, uri) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION).also { it.clipData = ClipData.newRawUri(null, uri) } + context.startActivity(Intent.createChooser(send, null)) + } +} diff --git a/app/src/main/kotlin/org/openstrap/app/export/GpxWriter.kt b/app/src/main/kotlin/org/openstrap/app/export/GpxWriter.kt new file mode 100644 index 00000000..e220300a --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/export/GpxWriter.kt @@ -0,0 +1,61 @@ +package org.openstrap.app.export + +import org.openstrap.app.data.Route +import java.time.Instant +import java.util.Locale +import kotlin.math.abs + +/** A workout's route as GPX 1.1 with Garmin's heart-rate extension, for sharing to other apps. */ +object GpxWriter { + /** + * [points] go through [Route.track], the line the map draws; a pause starts a new segment. [heartRate] is (epoch + * seconds, bpm) ascending. `ele` is GPS altitude as recorded (WGS84 ellipsoid, not sea level); Strava and similar + * services re-derive elevation. + */ + fun write(name: String, points: List, heartRate: List>, pauses: List = emptyList()): String { + val times = heartRate.map { it.first } + fun hrAt(t: Long): Int? { + val i = times.binarySearch(t).let { if (it < 0) -it - 1 else it } + val near = listOf(i - 1, i).filter { it in heartRate.indices } + .minByOrNull { abs(heartRate[it].first - t) } ?: return null + return heartRate[near].takeIf { abs(it.first - t) <= Route.MAX_HR_GAP_S }?.second + } + val sb = StringBuilder() + sb.append("\n") + sb.append("\n") + sb.append("").append(escape(name)).append("\n") + // Fixes strictly inside a pause are left out, so no line runs through it; a pause ends a segment. + var prev: Route.Point? = null + var gap = false + Route.track(points).forEach { p -> + if (pauses.any { p.t > it.first && p.t < it.last }) { + gap = true + return@forEach + } + val last = prev + val pausedBetween = last != null && pauses.any { it.first < p.t && it.last > last.t } + if (last == null || gap || pausedBetween) { + if (last != null) sb.append("\n") + sb.append("\n") + } + prev = p + gap = false + sb.append("") + p.altitude?.let { sb.append("").append(String.format(Locale.ROOT, "%.1f", it)).append("") } + sb.append("") + hrAt(p.t)?.let { + sb.append("").append(it) + sb.append("") + } + sb.append("\n") + } + if (prev != null) sb.append("\n") + sb.append("\n\n") + return sb.toString() + } + + private fun coord(v: Double) = String.format(Locale.ROOT, "%.7f", v) + + private fun escape(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """) +} 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..4b1e3c4c 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,10 @@ 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..3947fa4f --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/KmMarkers.kt @@ -0,0 +1,44 @@ +package org.openstrap.app.ui.glow + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Typeface +import androidx.core.graphics.createBitmap +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 = createBitmap(size, size) + 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..5adfee5d 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 @@ -1,6 +1,14 @@ package org.openstrap.app.ui.glow +import android.widget.Toast +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.platform.LocalContext +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import org.openstrap.app.R +import org.openstrap.app.export.GpxShare +import org.openstrap.app.export.GpxWriter import org.openstrap.app.data.Weeks import org.openstrap.app.i18n.Strings import androidx.compose.ui.res.pluralStringResource @@ -192,6 +200,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 +209,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 +264,27 @@ 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 + val context = LocalContext.current + val scope = rememberCoroutineScope() + val failed = stringResource(R.string.glow_summary_export_failed) + val name = summary.analysis.sportName + fun export() { + scope.launch { + val uri = withContext(Dispatchers.IO) { + val gpx = GpxWriter.write(name, summary.route, summary.history, summary.pauses) + GpxShare.forSharing(context, GpxShare.fileName(summary.analysis.workout.start), gpx) + } + if (uri != null) GpxShare.send(context, uri) else Toast.makeText(context, failed, Toast.LENGTH_SHORT).show() + } + } 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)) + EdgeTitle(stringResource(R.string.glow_summary_route), climb, action = { + IconPill(stringResource(R.string.glow_summary_export), onClick = { export() }, icon = AppIcons.DownloadSimple, height = 36.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-zh-rCN/strings_glow_summary.xml b/app/src/main/res/values-zh-rCN/strings_glow_summary.xml index 7c5e3d47..0666d792 100644 --- a/app/src/main/res/values-zh-rCN/strings_glow_summary.xml +++ b/app/src/main/res/values-zh-rCN/strings_glow_summary.xml @@ -85,4 +85,11 @@ 第 %1$d 组 休息 %1$s + 全屏打开地图 + 关闭 + 仅显示轨迹,不显示地图 + 显示地图 + 适配轨迹 + 导出 + 无法导出轨迹 diff --git a/app/src/main/res/values/strings_glow_summary.xml b/app/src/main/res/values/strings_glow_summary.xml index bada8171..bfa1ad03 100644 --- a/app/src/main/res/values/strings_glow_summary.xml +++ b/app/src/main/res/values/strings_glow_summary.xml @@ -93,8 +93,22 @@ Route + + Export + + Couldn\'t export the 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/export/GpxShareTest.kt b/app/src/test/kotlin/org/openstrap/app/export/GpxShareTest.kt new file mode 100644 index 00000000..a7caeb53 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/export/GpxShareTest.kt @@ -0,0 +1,48 @@ +package org.openstrap.app.export + +import android.content.Context +import androidx.core.content.FileProvider +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File + +/** The GPX file a workout's Export hands to the share sheet: its name, and the cached copy behind the FileProvider. */ +@RunWith(RobolectricTestRunner::class) +class GpxShareTest { + private val context: Context = ApplicationProvider.getApplicationContext() + + // FileProvider keeps its roots per authority for the process, and Robolectric gives each test its own cache dir. + @Before fun forgetProviderRoots() { + (FileProvider::class.java.getDeclaredField("sCache").apply { isAccessible = true }.get(null) as MutableMap<*, *>).clear() + } + + private fun read(uri: android.net.Uri) = context.contentResolver.openInputStream(uri)!!.use { it.readBytes().decodeToString() } + + @Test fun `fileName names the file after the workout`() { + assertEquals("unstrap_1792000000.gpx", GpxShare.fileName(1_792_000_000)) + } + + @Test fun `forSharing writes the text and returns a content uri`() { + val uri = GpxShare.forSharing(context, "run.gpx", "") + assertNotNull(uri) + assertEquals(context.packageName + ".share", uri!!.authority) + assertEquals("", read(uri)) + } + + @Test fun `a second export replaces the first`() { + GpxShare.forSharing(context, "run.gpx", "first and longer") + val uri = GpxShare.forSharing(context, "run.gpx", "2") + assertEquals("2", read(uri!!)) + } + + @Test fun `an export of another workout removes the earlier file`() { + GpxShare.forSharing(context, "a.gpx", "") + GpxShare.forSharing(context, "b.gpx", "") + assertEquals(listOf("b.gpx"), File(context.cacheDir, "share").list()!!.filter { it.endsWith(".gpx") }) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/export/GpxWriterTest.kt b/app/src/test/kotlin/org/openstrap/app/export/GpxWriterTest.kt new file mode 100644 index 00000000..381a79bc --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/export/GpxWriterTest.kt @@ -0,0 +1,87 @@ +package org.openstrap.app.export + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.openstrap.app.data.Route +import org.w3c.dom.Document +import org.w3c.dom.Element +import java.io.ByteArrayInputStream +import java.time.Instant +import java.util.Locale +import javax.xml.parsers.DocumentBuilderFactory + +class GpxWriterTest { + private val start = 1_700_000_000L + + private fun east(t: Long, metres: Double, altitude: Double? = null) = Route.Point(t, 0.0, metres / 111_195.0, 5f, altitude = altitude) + + /** A steady 3 m/s run east for 100 s, one fix a second. */ + private fun run(altitude: Double? = null) = (0..100).map { east(start + it, it * 3.0, altitude) } + + private fun parse(xml: String): Document = DocumentBuilderFactory.newInstance().apply { isNamespaceAware = true } + .newDocumentBuilder().parse(ByteArrayInputStream(xml.toByteArray())) + + private fun Document.all(tag: String) = getElementsByTagNameNS("*", tag) + + @Test fun `a run is one segment of timed points`() { + val doc = parse(GpxWriter.write("Run", run(), emptyList())) + assertEquals("1.1", doc.documentElement.getAttribute("version")) + assertEquals(1, doc.all("trk").length) + assertEquals(1, doc.all("trkseg").length) + assertTrue(doc.all("trkpt").length > 50) + val first = Route.track(run()).first() + val time = (doc.all("trkpt").item(0) as Element).getElementsByTagNameNS("*", "time").item(0).textContent + assertEquals(Instant.ofEpochSecond(first.t).toString(), time) + } + + @Test fun `a pause splits the track in two segments`() { + val doc = parse(GpxWriter.write("Run", run(), emptyList(), listOf(start + 40..start + 60))) + assertEquals(2, doc.all("trkseg").length) + val times = (0 until doc.all("time").length).map { Instant.parse(doc.all("time").item(it).textContent).epochSecond } + assertTrue(times.isNotEmpty() && times.none { it > start + 40 && it < start + 60 }) + assertTrue(times.any { it <= start + 40 } && times.any { it >= start + 60 }) + } + + @Test fun `a pause between two fixes still splits the track`() { + val gap = (0..40).map { east(start + it, it * 3.0) } + (42..100).map { east(start + it, it * 3.0) } + val doc = parse(GpxWriter.write("Run", gap, emptyList(), listOf(start + 40..start + 42))) + assertEquals(2, doc.all("trkseg").length) + } + + @Test fun `heart rate rides along when a reading is near`() { + val hr = (0L..50L step 5).map { start + it to 140 } + val pts = parse(GpxWriter.write("Run", run(), hr)).all("trkpt") + val first = pts.item(0) as Element + assertEquals("140", first.getElementsByTagNameNS("*", "hr").item(0).textContent) + val last = pts.item(pts.length - 1) as Element + assertEquals(0, last.getElementsByTagNameNS("*", "extensions").length) + } + + @Test fun `altitude appears only when the fix has one`() { + assertTrue(parse(GpxWriter.write("Run", run(12.3), emptyList())).all("ele").item(0).textContent == "12.3") + assertEquals(0, parse(GpxWriter.write("Run", run(), emptyList())).all("ele").length) + } + + @Test fun `a name with markup is escaped`() { + val name = "Run & \"Hill\" <1>" + assertEquals(name, parse(GpxWriter.write(name, run(), emptyList())).all("name").item(0).textContent) + } + + @Test fun `coordinates use a dot whatever the locale`() { + val saved = Locale.getDefault() + Locale.setDefault(Locale.GERMANY) + try { + val xml = GpxWriter.write("Run", run(), emptyList()) + assertTrue(xml.contains("lat=\"0.0000000\"")) + assertFalse(Regex("""(lat|lon)="[^"]*,""").containsMatchIn(xml)) + } finally { + Locale.setDefault(saved) + } + } + + @Test fun `no route is a valid document with no points`() { + assertEquals(0, parse(GpxWriter.write("Run", emptyList(), emptyList())).all("trkpt").length) + } +} 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/privacy.md b/docs/privacy.md index 318495b4..fee4d9fd 100644 --- a/docs/privacy.md +++ b/docs/privacy.md @@ -8,7 +8,8 @@ unstrap goes online for your Zepp account, for firmware and for workout maps onl - **Sign in with Zepp** opens Zepp's own sign-in page (watchface.zepp.com) in an in-app browser. unstrap never sees your password. After sign-in it reads the app token and user ID from the page's cookies. It then makes one request to Zepp's device list (`GET users/{userId}/devices` on `api-mifit*.zepp.com`) and shows you the strap's Bluetooth address and auth key to confirm. It saves the token and user ID for firmware checks and clears the Zepp cookies. - **Check for update** sends your Zepp token, user ID, and the strap's firmware version, hardware version and serial number to the update server you set. **Download** fetches the image from the URL that server returns. -- **Workout maps** load map tiles from [OpenFreeMap](https://openfreemap.org) (`tiles.openfreemap.org`), only when you open the map of a GPS workout. No account, API key or cookies. Like any tile server it sees roughly where the map is and your IP address. **Route only** on the map page loads no tiles at all. Your route itself never leaves the phone. +- **Workout maps** load map tiles from [OpenFreeMap](https://openfreemap.org) (`tiles.openfreemap.org`), only when you open the map of a GPS workout. No account, API key or cookies. Like any tile server it sees roughly where the map is and your IP address. **Route only** on the map page loads no tiles at all. Your route itself never leaves the phone unless you export it. +- **Export route** on a GPS workout's summary hands a GPX file to the app you pick in the share sheet. unstrap itself sends nothing. - **New versions of unstrap.** Once a day, when the phone has a network, unstrap reads the list of its releases from GitHub (`GET api.github.com/repos/sayed0am/unstrap/releases`), and again when you tap **Check now**. The request carries no account, token or ID, only unstrap's version in the user agent. Like any server, GitHub sees your IP address. When a newer release is out, a notification says so once. Turn it off with **Check every day** in **You → Updates**. - **Installing an update** downloads that release's APK from GitHub, only when you tap it. unstrap checks it against the SHA-256 GitHub lists for it, and that it's unstrap signed with the same key, before handing it to Android to install.