Compare commits

..

No commits in common. "94f9822884770c093d943593ba771ec13c8c5f2e" and "1475ab913b7570ae59618f17a978d644eee6dfa8" have entirely different histories.

91 changed files with 1051 additions and 5336 deletions

View File

@ -48,19 +48,6 @@ so a run finished after 20:00 pushes the hour later without the phone being
plugged in; the per-minute shutdown check then lifts the night lockdown on its
own once the hour is past "now" (digital-wellbeing's check script).
Runs and walks are credited by ONE rule, whatever the TCX sport or the
`_Walking` file-name suffix (RunnerUp's files and the workout app's alike): a
day's activities are summed, and the day counts once their distance reaches
3.5 km (5% GPS tolerance) OR their *moving* time reaches the shared duration
bar (30 min minus the hidden leeway). Both are summed over the track cut into
windows of at least 10 s, each judged by its average speed: faster than 25 km/h
(a vehicle or a GPS jump) counts neither time nor distance; moving time needs
0.5 m/s or more (1 m/s across a signal dropout longer than 30 s, so a pause
earns nothing but a run through a dropout keeps its time). Files without
trackpoints earn nothing (the lap totals are never used). The reward is the usual one
workout credit per day (`runnerup_verified:<date>`); the log's `activity`
field is display only. Code: `screen_locker/_walk_tcx.py`.
**Retiring RunnerUp.** A week after the PC first credits a run recorded by the
workout app (TCX author `kuhy workout_app`), `runnerup-retire.timer` (daily, retries
until the phone is attached) backs `/sdcard/Documents/RunnerUp` up to

View File

@ -1,133 +0,0 @@
"""A day's activities summed under the one crediting rule (see ``_walk_tcx``).
The day counts as the workout once EITHER its summed distance reaches
``MIN_RUN_DISTANCE_KM`` (within the GPS tolerance) OR its summed moving time
reaches the shared duration bar. The sport only labels messages.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from screen_locker._constants import (
MIN_RUN_DISTANCE_KM,
MIN_WORKOUT_DURATION_MINUTES,
RUNNERUP_DISTANCE_TOLERANCE,
WORKOUT_DURATION_ACCEPT_MINUTES,
)
if TYPE_CHECKING:
from collections.abc import Iterable
# RunnerUp's sport codes, for labels only (the label never decides credit).
SPORT_NAMES: dict[int, str] = {
0: "Running",
1: "Biking",
2: "Other",
3: "Orienteering",
4: "Walking",
5: "Treadmill",
6: "Gym",
7: "Stationary Bike",
}
def distance_qualifies(distance_km: float) -> bool:
"""Whether a distance meets the minimum, with the GPS tolerance."""
return distance_km * (1 + RUNNERUP_DISTANCE_TOLERANCE) >= MIN_RUN_DISTANCE_KM
def moving_qualifies(moving_minutes: float) -> bool:
"""Whether moving time meets the shared duration bar (leeway included)."""
return moving_minutes >= WORKOUT_DURATION_ACCEPT_MINUTES
def _distance_metres(activity: dict[str, Any]) -> float:
"""Credited metres; the root-DB path has no trackpoints, so its total stands in."""
return float(activity.get("track_distance_m", activity.get("distance_m", 0.0)))
def _moving_seconds(activity: dict[str, Any]) -> float:
"""Moving seconds; the root-DB path has no trackpoints, so wall-clock stands in."""
return float(activity.get("moving_seconds", activity.get("duration_seconds", 0.0)))
@dataclass(frozen=True)
class ActivityDay:
"""A day's activities, summed.
Attributes:
legs: Distinct activities (deduplicated by the activity's ``Id``: the
WebDAV copy and the phone's copy are the same activity).
moving_minutes: Their summed moving time.
distance_km: Their summed distance.
completed_at: Unix time the activity that took the day over the bar
ended -- when the workout was actually done -- or ``None`` if the
day never got there (or the activity recorded no end).
all_walks: Whether every activity was a walk (label only).
sport: The sport code when the day is a single non-walk activity.
"""
legs: int
moving_minutes: float
distance_km: float
completed_at: float | None
all_walks: bool = False
sport: int = -1
@property
def qualifies(self) -> bool:
"""Whether the day counts as its workout: distance OR moving time."""
return distance_qualifies(self.distance_km) or moving_qualifies(
self.moving_minutes
)
def message(self) -> str:
"""The verification line, in the RunnerUp verifier's own style."""
if self.all_walks:
return (
f"Walking: {self.legs} walk(s), {self.distance_km:.1f} km, "
f"{self.moving_minutes:.0f} min moving"
)
if self.legs == 1:
name = SPORT_NAMES.get(self.sport, str(self.sport))
return f"{name}: {self.distance_km:.1f} km in {self.moving_minutes:.0f} min"
return (
f"Activity: {self.legs} activities, {self.distance_km:.1f} km, "
f"{self.moving_minutes:.0f} min moving"
)
def activity_shortfall(day: ActivityDay) -> str:
"""Why a day's activity did not count yet."""
return (
f"{day.message()} -- need {MIN_RUN_DISTANCE_KM:g}+ km or "
f"{MIN_WORKOUT_DURATION_MINUTES}+ min moving"
)
def activity_day(activities: Iterable[dict[str, Any]]) -> ActivityDay:
"""Sum parsed exports (``parse_tcx_file`` dicts) into one :class:`ActivityDay`."""
unique: dict[str, dict[str, Any]] = {}
for activity in activities:
unique.setdefault(str(activity.get("activity_id") or id(activity)), activity)
ordered = sorted(unique.values(), key=lambda a: a.get("ended_at") or 0.0)
moving = 0.0
metres = 0.0
completed_at: float | None = None
for activity in ordered:
moving += _moving_seconds(activity)
metres += _distance_metres(activity)
if completed_at is None and (
moving_qualifies(moving / 60) or distance_qualifies(metres / 1000)
):
completed_at = activity.get("ended_at")
return ActivityDay(
legs=len(ordered),
moving_minutes=moving / 60,
distance_km=metres / 1000,
completed_at=completed_at,
all_walks=bool(ordered) and all(a.get("walking") for a in ordered),
sport=int(ordered[0].get("sport", -1)) if ordered else -1,
)

View File

@ -73,11 +73,11 @@ WORKOUT_DURATION_ACCEPT_MINUTES = (
)
RUNNERUP_PACKAGES = ("org.runnerup", "org.runnerup.free")
RUNNERUP_DB_SDCARD_TMP = "/sdcard/.runnerup_tmp_verification.db"
# A day's activity (run or walk alike) qualifies on EITHER criterion — they are
# an OR, not an AND. A short but long-lasting session counts, and so does a
# fast 5 km that takes under the duration bar. Do not reinstate an AND here:
# it would reject exactly the slow case this pair exists to allow. The
# duration arm is the shared MIN_WORKOUT_DURATION_MINUTES above (moving time).
# A run qualifies on EITHER criterion — they are an OR, not an AND. A short
# but long-lasting run counts, and so does a fast 5 km that takes under the
# duration bar. Do not reinstate an AND here: it would reject exactly the
# slow-run case this pair exists to allow. The duration arm is the shared
# MIN_WORKOUT_DURATION_MINUTES above; only the distance arm is run-specific.
MIN_RUN_DISTANCE_KM = 3.5 # inclusive: "as low as 3.5 km"
# GPS distance tracking undershoots on tight turns/tree cover/urban canyons;
# a run within 5% of the minimum is accepted rather than rejected on
@ -105,22 +105,11 @@ SHUTDOWN_BASE_FILE = Path(__file__).resolve().parent / "shutdown_base.json"
REST_DAY_FILE = Path(__file__).resolve().parent / "rest_days.json"
REST_DAYS_PER_ISO_WEEK = 2
GRACE_STATE_FILE = Path(__file__).resolve().parent / "grace_floor.json"
# Every GPS activity (run or walk, whatever its TCX sport) is judged the same
# way: a day's activities count as the workout once their summed distance
# reaches MIN_RUN_DISTANCE_KM OR their summed MOVING time reaches
# WORKOUT_DURATION_ACCEPT_MINUTES. Moving = trackpoint pairs seen within
# WALK_MAX_GAP_SECONDS and travelled at least this fast (slower is standing
# still). A pair faster than MAX_MOVING_SPEED_MPS (25 km/h, the app's running
# jump filter) is a vehicle or a GPS jump and counts neither moving time NOR
# distance, for every activity. The Dart app mirrors the bounds.
MIN_MOVING_SPEED_MPS = 0.5
MAX_MOVING_SPEED_MPS = 25 / 3.6
# A day's RunnerUp walks (commute legs) count as the workout once their
# MOVING time reaches WORKOUT_DURATION_ACCEPT_MINUTES (the shared bar above);
# moving = trackpoint pairs at walking speed.
WALK_SPEED_MPS = (0.5, 3.0)
WALK_MAX_GAP_SECONDS = 30
# Speed is judged over windows of at least this long (1 s fixes jitter), and a
# window longer than WALK_MAX_GAP_SECONDS (a GPS dropout) only counts as
# moving time at this speed or faster, so standing through a gap earns nothing.
TRACK_WINDOW_SECONDS = 10
MIN_DROPOUT_SPEED_MPS = 1.0
# Workout records this PC must keep deleted in the sync store, pushed as
# tombstones on every tick (see _sync_tombstones for why once is not enough).
SYNC_TOMBSTONES_FILE = Path(__file__).resolve().parent / "sync_tombstones.json"

View File

@ -15,7 +15,7 @@ import logging
from typing import TYPE_CHECKING, Any
from screen_locker._log_mixin import write_signed_entry
from screen_locker._walk_tcx import activity_day, activity_shortfall
from screen_locker._walk_tcx import walk_day, walk_shortfall
if TYPE_CHECKING:
from collections.abc import Callable
@ -72,47 +72,66 @@ class RunnerUpBackfillMixin:
Returns True if a new verified entry was appended for ``date_str``.
"""
activities = [
data
for remote in self._find_runnerup_exports_for_date(date_str)
if (data := self._pull_and_parse_tcx(remote)) is not None
]
return self._try_fill_day(date_str, activities, log_file, on_ingested)
walks: list[dict[str, Any]] = []
for remote in self._find_runnerup_exports_for_date(date_str):
data = self._pull_and_parse_tcx(remote)
if data is None:
continue
if data.get("walking"):
# Never one walk at a time: a day's walks are summed below.
walks.append(data)
continue
status, msg = self._validate_runnerup_data(data)
if status != "verified":
_logger.warning(
"RunnerUp export %s for %s did not qualify (%s): %s",
remote,
date_str,
status,
msg,
)
continue
workout_data = {
"type": "runnerup_verified",
"source": f"Auto-scanned: {msg}",
"distance_km": round(data["distance_m"] / 1000, 2),
"duration_minutes": round(data["duration_seconds"] / 60, 1),
"completed_at": data.get("ended_at"),
}
return _record(log_file, date_str, workout_data, on_ingested)
return self._try_fill_walks(date_str, walks, log_file, on_ingested)
@staticmethod
def _try_fill_day(
def _try_fill_walks(
date_str: str,
activities: list[dict[str, Any]],
walks: list[dict[str, Any]],
log_file: Path,
on_ingested: OnIngestedCallback | None,
) -> bool:
"""Append the day's activity as its RunnerUp workout, once it adds up.
"""Append the day's walking as its RunnerUp workout, once it adds up.
One rule for runs and walks alike (see :mod:`screen_locker._walk_tcx`):
the day's activities are summed, never judged one file at a time. They
share the ``runnerup_verified:{date}`` slot, so a walk and a run on
one day are one RunnerUp credit. ``activity: walking`` is kept for the
phone's history display only; it never decides credit.
Same type and so the same ``runnerup_verified:{date}`` slot as a run:
a walk and a run on one day are one RunnerUp credit, exactly as two
runs already were.
"""
if not activities:
if not walks:
return False
day = activity_day(activities)
day = walk_day(walks)
if not day.qualifies:
_logger.warning(
"RunnerUp activity for %s does not count yet: %s",
"RunnerUp walks for %s do not count yet: %s",
date_str,
activity_shortfall(day),
walk_shortfall(day),
)
return False
workout_data: dict[str, Any] = {
workout_data = {
"type": "runnerup_verified",
"activity": "walking",
"source": f"Auto-scanned: {day.message()}",
"distance_km": round(day.distance_km, 2),
"duration_minutes": round(day.moving_minutes, 1),
"completed_at": day.completed_at,
}
if day.all_walks:
workout_data["activity"] = "walking"
return _record(log_file, date_str, workout_data, on_ingested)
def _scan_and_fill_week_runnerup(

View File

@ -12,26 +12,31 @@ from typing import Any
from screen_locker._constants import (
MIN_RUN_DISTANCE_KM,
MIN_WORKOUT_DURATION_MINUTES,
RUNNERUP_DISTANCE_TOLERANCE,
RUNNERUP_EXPORT_DIRS,
RUNNERUP_WEBDAV_DIRS,
WORKOUT_DURATION_ACCEPT_MINUTES,
)
from screen_locker._day import today_str
from screen_locker._runnerup_backfill import RunnerUpBackfillMixin
from screen_locker._runnerup_db import RunnerUpDbMixin
from screen_locker._runnerup_tcx import RunnerUpTcxMixin
from screen_locker._time_check import check_clock_skew
from screen_locker._walk_tcx import (
SPORT_NAMES,
activity_day,
activity_shortfall,
distance_qualifies,
)
from screen_locker._walk_tcx import walk_day, walk_shortfall
_logger = logging.getLogger(__name__)
# Kept for importers; the labels live next to the one crediting rule.
_SPORT_NAMES = SPORT_NAMES
_SPORT_NAMES: dict[int, str] = {
0: "Running",
1: "Biking",
2: "Other",
3: "Orienteering",
4: "Walking",
5: "Treadmill",
6: "Gym",
7: "Stationary Bike",
}
# TCX uses sport name strings; map back to integer codes for unified validation.
@ -116,46 +121,73 @@ class RunnerUpVerificationMixin(
)
return None
# One rule for the whole day, whatever the sport or file name: the
# day's activities are summed (see _walk_tcx), never judged one file
# at a time.
activities = [
data
for remote in exports
if (data := self._pull_and_parse_tcx(remote)) is not None
]
if not activities:
return (
"not_verified",
"RunnerUp TCX export found but could not be read",
)
day = activity_day(activities)
if day.qualifies:
return "verified", day.message()
return "too_short", activity_shortfall(day)
# Try each file; return the best result (verified > validation error).
# Walks never qualify one file at a time: they are summed below.
best: tuple[str, str] | None = None
walks: list[dict[str, Any]] = []
for remote in exports:
data = self._pull_and_parse_tcx(remote)
if data is None:
continue
if data.get("walking"):
walks.append(data)
continue
status, msg = self._validate_runnerup_data(data)
if status == "verified":
return status, msg
if best is None:
best = (status, msg)
if walks:
day = walk_day(walks)
if day.qualifies:
return "verified", day.message()
best = best or ("too_short", walk_shortfall(day))
# All files found but none passed validation.
return best or (
"not_verified",
"RunnerUp TCX export found but could not be read",
)
def _validate_runnerup_data(self, data: dict[str, Any]) -> tuple[str, str]:
"""Validate a RunnerUp activity against configured thresholds.
Returns ``(status, message)`` following the same contract as
``PhoneVerificationMixin._verify_phone_workout``. The one rule is
:func:`screen_locker._walk_tcx.activity_day`; a dict without
``moving_seconds`` (the root-DB path) is judged by its duration.
``PhoneVerificationMixin._verify_phone_workout``.
"""
day = activity_day([data])
if not day.qualifies:
return "too_short", activity_shortfall(day)
if day.distance_km < MIN_RUN_DISTANCE_KM and distance_qualifies(
day.distance_km
):
sport = data["sport"]
duration_min = data["duration_seconds"] / 60
distance_km = data["distance_m"] / 1000
# Either criterion qualifies the run on its own (see _constants.py).
# Distance gets the GPS tolerance (a measurement correction); duration
# gets the shared hidden leeway (a deliberate concession). Different
# reasons, so they stay separate constants.
distance_ok = (
distance_km * (1 + RUNNERUP_DISTANCE_TOLERANCE) >= MIN_RUN_DISTANCE_KM
)
duration_ok = duration_min >= WORKOUT_DURATION_ACCEPT_MINUTES
if not distance_ok and not duration_ok:
msg = (
f"Run was {distance_km:.1f} km / {duration_min:.0f} min — need "
f"{MIN_RUN_DISTANCE_KM:g}+ km or {MIN_WORKOUT_DURATION_MINUTES}+ min"
)
return "too_short", msg
if distance_ok and distance_km < MIN_RUN_DISTANCE_KM:
_logger.info(
"RunnerUp distance %.2f km is under the %.1f km minimum but "
"within %.0f%% GPS tolerance — accepted.",
day.distance_km,
distance_km,
MIN_RUN_DISTANCE_KM,
RUNNERUP_DISTANCE_TOLERANCE * 100,
)
return "verified", day.message()
sport_name = _SPORT_NAMES.get(sport, str(sport))
return (
"verified",
f"{sport_name}: {distance_km:.1f} km in {duration_min:.0f} min",
)
# ------------------------------------------------------------------
# Main entry point

View File

@ -1,64 +1,42 @@
"""One crediting rule for every GPS activity, from its RunnerUp-style TCX export.
"""Walking in RunnerUp TCX exports: which files are walks, and their moving time.
A day's activities -- runs and walks, RunnerUp's files and the workout app's
alike -- are summed, and the day counts as the workout once EITHER
A day's walking counts as the workout once its walks -- usually separate
commute legs, one file each -- add up to the shared workout duration bar
(``WORKOUT_DURATION_ACCEPT_MINUTES``) of *moving* time.
* their distance reaches ``MIN_RUN_DISTANCE_KM`` (within the GPS tolerance), OR
* their *moving* time reaches the shared duration bar
(``WORKOUT_DURATION_ACCEPT_MINUTES``).
The TCX sport and the ``_Walking`` file-name suffix never change the outcome;
they only decide the label a message and the log's ``activity`` field carry
(the phone's history shows it).
**Which files are walks (label only).** RunnerUp's WebDAV and File
synchronisers both export with ``ExportOptions.getDefault()``, whose TCX writer
knows only Running/Biking and writes ``Sport="Other"`` for a walk. The sport
survives only in the file name (``Sport.TapiriikType()``): ``..._Walking.tcx``.
The Strava export variant writes ``Sport="Walking"``, so that counts too.
**Which files are walks.** RunnerUp's WebDAV and File synchronisers both
export with ``ExportOptions.getDefault()``, whose TCX writer knows only
Running/Biking and writes ``Sport="Other"`` for a walk. The sport survives
only in the file name (``Sport.TapiriikType()``): ``..._Walking.tcx``. The
Strava export variant writes ``Sport="Walking"``, so that counts too.
``Other`` alone is not a walk: it is every sport RunnerUp cannot name.
**Moving time, not elapsed.** A lap's ``TotalTimeSeconds`` is wall-clock: one
real lap reads 101 min for 1 km of standing about. The track is cut into
windows of at least ``TRACK_WINDOW_SECONDS`` (a fix every second jitters, so
one raw pair can read 15 m/s inside a 3 m/s run) and each window is judged by
its average speed. Faster than ``MAX_MOVING_SPEED_MPS`` (25 km/h) is a vehicle
or a GPS jump: neither time nor distance counts, so a bus ride earns nothing.
Otherwise its metres count, and its seconds count as moving time at
``MIN_MOVING_SPEED_MPS`` or faster; standing still is too slow. A window longer
than ``WALK_MAX_GAP_SECONDS`` is a signal dropout (real exports have 2 minute
ones): the runner may have kept running unseen, so it counts as moving only at
``MIN_DROPOUT_SPEED_MPS`` or faster, while a pause (no distance across the
gap) earns nothing -- a pause cannot buy a run its duration.
The day's distance is the sum of the windows (``track_distance_m``), never the
lap's ``DistanceMeters`` total, and an export with no trackpoints cannot be
speed-checked, so it credits nothing. Only the root-DB fallback, which has no
trackpoints at all, is judged by its recorded distance and duration.
real lap reads 101 min for 1 km of standing about. Moving time is summed over
consecutive trackpoint pairs whose speed is walking speed
(``WALK_SPEED_MPS``): standing still is too slow, a tram or a bus too fast.
A pair further apart than ``WALK_MAX_GAP_SECONDS`` is a GPS dropout whose
motion is unknown and earns nothing -- the walk is never credited for time
nobody saw.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
import itertools
import logging
from typing import TYPE_CHECKING, Any
from screen_locker._activity_day import (
SPORT_NAMES,
ActivityDay,
activity_day,
activity_shortfall,
distance_qualifies,
moving_qualifies,
)
from screen_locker._constants import (
MAX_MOVING_SPEED_MPS,
MIN_DROPOUT_SPEED_MPS,
MIN_MOVING_SPEED_MPS,
TRACK_WINDOW_SECONDS,
MIN_WORKOUT_DURATION_MINUTES,
WALK_MAX_GAP_SECONDS,
WALK_SPEED_MPS,
WORKOUT_DURATION_ACCEPT_MINUTES,
)
if TYPE_CHECKING:
from collections.abc import Iterator
from collections.abc import Iterable
import xml.etree.ElementTree as ET
_logger = logging.getLogger(__name__)
@ -95,78 +73,73 @@ def _trackpoints(activity: ET.Element) -> list[tuple[float, float]]:
return points
def _segments(
points: list[tuple[float, float]],
) -> Iterator[tuple[float, float]]:
"""``(seconds, metres)`` of the track cut into windows of >= TRACK_WINDOW_SECONDS.
A fix every second jitters (one pair can read 15 m/s inside a 3 m/s run),
so speed is judged over a window, never over a raw 1 s pair. Fixes that
are already further apart than the window are their own segment.
"""
if not points:
return
anchor = points[0]
for point in points[1:]:
if point[0] - anchor[0] >= TRACK_WINDOW_SECONDS:
yield point[0] - anchor[0], point[1] - anchor[1]
anchor = point
if points[-1] is not anchor:
yield points[-1][0] - anchor[0], points[-1][1] - anchor[1]
def track_summary(activity: ET.Element) -> dict[str, Any]:
"""Moving seconds, credited distance and end time, from the trackpoints.
A segment (see :func:`_segments`) counts unless it was travelled faster
than ``MAX_MOVING_SPEED_MPS``: it then adds its metres to
``track_distance_m``, and its seconds to ``moving_seconds`` too when it was
travelled at least at ``MIN_MOVING_SPEED_MPS``. A segment longer than
``WALK_MAX_GAP_SECONDS`` is a signal dropout whose motion is unknown; it
only counts as moving time at ``MIN_DROPOUT_SPEED_MPS``, so a pause (no
distance across the gap) earns no time while a runner whose GPS went away
for two minutes keeps the time and metres the far side proves.
"""
"""Moving seconds and end time of one activity, from its trackpoints."""
points = _trackpoints(activity)
slow, fast = WALK_SPEED_MPS
moving = 0.0
metres = 0.0
for seconds, travelled in _segments(points):
if seconds <= 0:
continue
speed = travelled / seconds
if speed > MAX_MOVING_SPEED_MPS:
continue
metres += max(travelled, 0.0)
floor = (
MIN_MOVING_SPEED_MPS
if seconds <= WALK_MAX_GAP_SECONDS
else MIN_DROPOUT_SPEED_MPS
)
if speed >= floor:
moving += seconds
for (t0, d0), (t1, d1) in itertools.pairwise(points):
gap = t1 - t0
if 0 < gap <= WALK_MAX_GAP_SECONDS and slow <= (d1 - d0) / gap <= fast:
moving += gap
return {
"activity_id": activity.findtext(f"{_TCX_NS}Id") or "",
"moving_seconds": moving,
"track_distance_m": metres,
"ended_at": points[-1][0] if points else None,
}
# The day aggregate lives in ``_activity_day``; these names stay importable here,
# along with the walk-only names they replaced.
WalkDay = ActivityDay
walk_day = activity_day
walk_shortfall = activity_shortfall
__all__ = [
"SPORT_NAMES",
"ActivityDay",
"WalkDay",
"activity_day",
"activity_shortfall",
"distance_qualifies",
"is_walking_export",
"moving_qualifies",
"track_summary",
"walk_day",
"walk_shortfall",
]
@dataclass(frozen=True)
class WalkDay:
"""A day's walks, summed.
Attributes:
legs: Distinct walks (deduplicated by the activity's ``Id``: the
WebDAV copy and the phone's copy are the same walk).
moving_minutes: Their summed moving time.
distance_km: Their summed distance.
completed_at: Unix time the walk that crossed the bar ended -- when
the workout was actually done -- or ``None`` if it never did.
"""
legs: int
moving_minutes: float
distance_km: float
completed_at: float | None
@property
def qualifies(self) -> bool:
"""Whether the day's walking counts as its workout."""
return self.moving_minutes >= WORKOUT_DURATION_ACCEPT_MINUTES
def message(self) -> str:
"""The verification line, in the RunnerUp verifier's own style."""
return (
f"Walking: {self.legs} walk(s), {self.distance_km:.1f} km, "
f"{self.moving_minutes:.0f} min moving"
)
def walk_shortfall(day: WalkDay) -> str:
"""Why a day's walking did not count yet."""
return f"{day.message()} -- need {MIN_WORKOUT_DURATION_MINUTES}+ min moving"
def walk_day(walks: Iterable[dict[str, Any]]) -> WalkDay:
"""Sum parsed walk exports (``_parse_tcx`` dicts) into one :class:`WalkDay`."""
unique: dict[str, dict[str, Any]] = {}
for walk in walks:
unique.setdefault(str(walk.get("activity_id") or id(walk)), walk)
ordered = sorted(unique.values(), key=lambda w: w.get("ended_at") or 0.0)
moving = 0.0
completed_at: float | None = None
for walk in ordered:
moving += float(walk.get("moving_seconds", 0.0))
if completed_at is None and moving / 60 >= WORKOUT_DURATION_ACCEPT_MINUTES:
completed_at = walk.get("ended_at")
return WalkDay(
legs=len(ordered),
moving_minutes=moving / 60,
distance_km=sum(float(w.get("distance_m", 0.0)) for w in ordered) / 1000,
completed_at=completed_at,
)

View File

@ -4,8 +4,8 @@ Every other earner publishes its credits as HMAC-signed rows in a ledger that
``earned_time`` reads (``first_credit_at``, ``credit_units``). This is the
workout's: ``~/.local/share/workout_locker/ledger.json``, one row per
* workout credit slot in ``log.json`` -- RunnerUp (the day's runs and walks,
summed by one rule), StrongLifts (phone or PC session), manual, any lock-screen or
* workout credit slot in ``log.json`` -- RunnerUp (a run, or the day's walks
summed), StrongLifts (phone or PC session), manual, any lock-screen or
verify path -- appended by the one log write chokepoint
(``_log_mixin.write_signed_entry``), so no path can credit without it; and
* declared rest day -- appended when it is declared.

View File

@ -1,96 +0,0 @@
"""Helpers for the unified-activity tests: TCX builder and a phone-less verifier."""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import TYPE_CHECKING
from unittest.mock import patch
from screen_locker._runnerup_verification import RunnerUpVerificationMixin
if TYPE_CHECKING:
from pathlib import Path
_NS = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"
DAY = "2026-10-10"
def tcx(
sport: str,
start: str,
*,
moving_min: float,
metres: float,
pause_min: float = 0.0,
) -> str:
"""A RunnerUp-shaped export: ``moving_min`` of steady motion covering ``metres``.
A ``pause_min`` pause sits in the middle of the track as ONE gap between
two trackpoints (the clock runs, the distance does not), so the lap's
wall-clock time is ``moving_min + pause_min``.
"""
begin = datetime.fromisoformat(f"{DAY}T{start}:00+00:00")
speed = metres / (moving_min * 60)
total = int(moving_min * 60)
half = total // 2 // 5 * 5
pause = int(pause_min * 60)
points = ""
for s in range(0, total + 1, 5):
offset = s + (pause if s > half else 0)
points += (
f"<Trackpoint><Time>{(begin + timedelta(seconds=offset)).isoformat()}"
f"</Time><DistanceMeters>{s * speed:.1f}</DistanceMeters></Trackpoint>"
)
return (
f'<TrainingCenterDatabase xmlns="{_NS}"><Activities>'
f'<Activity Sport="{sport}"><Id>{DAY}T{start}</Id><Lap>'
f"<TotalTimeSeconds>{total + pause}</TotalTimeSeconds>"
f"<DistanceMeters>{metres}</DistanceMeters>"
f"<Track>{points}</Track></Lap></Activity></Activities>"
"</TrainingCenterDatabase>"
)
class Verifier(RunnerUpVerificationMixin):
"""The real mixin reading one temporary drop directory and no phone."""
def __init__(self, folder: Path) -> None:
self.folder = folder
def _has_adb_device(self) -> bool:
return False
def _run_adb(self, args: list[str]) -> tuple[bool, str]:
return False, ""
def _find_runnerup_exports_for_date(self, date_str: str) -> list[str]:
return sorted(str(p) for p in self.folder.glob(f"*{date_str}*.tcx"))
def drop(folder: Path, stamp: str, suffix: str, body: str) -> None:
"""Write a RunnerUp-named export for the test day."""
(folder / f"RunnerUp_Pixel_6a_{DAY}-{stamp}{suffix}.tcx").write_text(body)
def verify(verifier: Verifier) -> tuple[str, str] | None:
"""The file-based verdict for the test day."""
with patch("screen_locker._runnerup_verification.today_str", return_value=DAY):
return verifier._verify_runnerup_via_files()
def tcx_points(sport: str, start: str, points: list[tuple[int, float]]) -> str:
"""An export whose track is exactly ``(seconds after start, cumulative metres)``."""
begin = datetime.fromisoformat(f"{DAY}T{start}:00+00:00")
body = "".join(
f"<Trackpoint><Time>{(begin + timedelta(seconds=s)).isoformat()}</Time>"
f"<DistanceMeters>{m:.1f}</DistanceMeters></Trackpoint>"
for s, m in points
)
return (
f'<TrainingCenterDatabase xmlns="{_NS}"><Activities>'
f'<Activity Sport="{sport}"><Id>{DAY}T{start}</Id><Lap>'
f"<TotalTimeSeconds>{points[-1][0]}</TotalTimeSeconds>"
f"<DistanceMeters>{points[-1][1]}</DistanceMeters>"
f"<Track>{body}</Track></Lap></Activity></Activities>"
"</TrainingCenterDatabase>"
)

View File

@ -1,811 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">
<Activities>
<Activity Sport="Running">
<Id>2026-11-09T17:00:00Z</Id>
<Lap StartTime="2026-11-09T17:00:00Z">
<TotalTimeSeconds>1800</TotalTimeSeconds>
<DistanceMeters>5400.009</DistanceMeters>
<Calories>0</Calories>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2026-11-09T17:00:00Z</Time>
<Position>
<LatitudeDegrees>48.8584000</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>0.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:00:20Z</Time>
<Position>
<LatitudeDegrees>48.8589396</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>60.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:00:40Z</Time>
<Position>
<LatitudeDegrees>48.8594792</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>120.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:01:00Z</Time>
<Position>
<LatitudeDegrees>48.8600188</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>180.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:01:20Z</Time>
<Position>
<LatitudeDegrees>48.8605584</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>240.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:01:40Z</Time>
<Position>
<LatitudeDegrees>48.8610980</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>300.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:02:00Z</Time>
<Position>
<LatitudeDegrees>48.8616376</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>360.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:02:20Z</Time>
<Position>
<LatitudeDegrees>48.8621772</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>420.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:02:40Z</Time>
<Position>
<LatitudeDegrees>48.8627167</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>480.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:03:00Z</Time>
<Position>
<LatitudeDegrees>48.8632563</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>540.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:03:20Z</Time>
<Position>
<LatitudeDegrees>48.8637959</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>600.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:03:40Z</Time>
<Position>
<LatitudeDegrees>48.8643355</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>660.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:04:00Z</Time>
<Position>
<LatitudeDegrees>48.8648751</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>720.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:04:20Z</Time>
<Position>
<LatitudeDegrees>48.8654147</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>780.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:04:40Z</Time>
<Position>
<LatitudeDegrees>48.8659543</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>840.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:05:00Z</Time>
<Position>
<LatitudeDegrees>48.8664939</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>900.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:05:20Z</Time>
<Position>
<LatitudeDegrees>48.8670335</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>960.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:05:40Z</Time>
<Position>
<LatitudeDegrees>48.8675731</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1020.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:06:00Z</Time>
<Position>
<LatitudeDegrees>48.8681127</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1080.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:06:20Z</Time>
<Position>
<LatitudeDegrees>48.8686523</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1140.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:06:40Z</Time>
<Position>
<LatitudeDegrees>48.8691919</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1200.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:07:00Z</Time>
<Position>
<LatitudeDegrees>48.8697315</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1260.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:07:20Z</Time>
<Position>
<LatitudeDegrees>48.8702710</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1320.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:07:40Z</Time>
<Position>
<LatitudeDegrees>48.8708106</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1380.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:08:00Z</Time>
<Position>
<LatitudeDegrees>48.8713502</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1440.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:08:20Z</Time>
<Position>
<LatitudeDegrees>48.8718898</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1500.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:08:40Z</Time>
<Position>
<LatitudeDegrees>48.8724294</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1560.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:09:00Z</Time>
<Position>
<LatitudeDegrees>48.8729690</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1620.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:09:20Z</Time>
<Position>
<LatitudeDegrees>48.8735086</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1680.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:09:40Z</Time>
<Position>
<LatitudeDegrees>48.8740482</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1740.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:10:00Z</Time>
<Position>
<LatitudeDegrees>48.8745878</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>1800.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:12:00Z</Time>
<Position>
<LatitudeDegrees>48.8778254</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2160.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:12:20Z</Time>
<Position>
<LatitudeDegrees>48.8783649</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2220.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:12:40Z</Time>
<Position>
<LatitudeDegrees>48.8789045</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2280.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:13:00Z</Time>
<Position>
<LatitudeDegrees>48.8794441</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2340.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:13:20Z</Time>
<Position>
<LatitudeDegrees>48.8799837</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2400.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:13:40Z</Time>
<Position>
<LatitudeDegrees>48.8805233</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2460.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:14:00Z</Time>
<Position>
<LatitudeDegrees>48.8810629</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2520.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:14:20Z</Time>
<Position>
<LatitudeDegrees>48.8816025</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2580.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:14:40Z</Time>
<Position>
<LatitudeDegrees>48.8821421</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2640.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:15:00Z</Time>
<Position>
<LatitudeDegrees>48.8826817</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2700.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:15:20Z</Time>
<Position>
<LatitudeDegrees>48.8832213</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2760.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:15:40Z</Time>
<Position>
<LatitudeDegrees>48.8837609</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2820.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:16:00Z</Time>
<Position>
<LatitudeDegrees>48.8843005</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2880.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:16:20Z</Time>
<Position>
<LatitudeDegrees>48.8848401</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>2940.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:16:40Z</Time>
<Position>
<LatitudeDegrees>48.8853797</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3000.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:17:00Z</Time>
<Position>
<LatitudeDegrees>48.8859192</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3060.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:17:20Z</Time>
<Position>
<LatitudeDegrees>48.8864588</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3120.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:17:40Z</Time>
<Position>
<LatitudeDegrees>48.8869984</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3180.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:18:00Z</Time>
<Position>
<LatitudeDegrees>48.8875380</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3240.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:18:20Z</Time>
<Position>
<LatitudeDegrees>48.8880776</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3300.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:18:40Z</Time>
<Position>
<LatitudeDegrees>48.8886172</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3360.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:19:00Z</Time>
<Position>
<LatitudeDegrees>48.8891568</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3420.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:19:20Z</Time>
<Position>
<LatitudeDegrees>48.8896964</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3480.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:19:40Z</Time>
<Position>
<LatitudeDegrees>48.8902360</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3540.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:20:00Z</Time>
<Position>
<LatitudeDegrees>48.8907756</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3600.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:20:20Z</Time>
<Position>
<LatitudeDegrees>48.8913152</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3660.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:20:40Z</Time>
<Position>
<LatitudeDegrees>48.8918548</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3720.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:21:00Z</Time>
<Position>
<LatitudeDegrees>48.8923944</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3780.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:21:20Z</Time>
<Position>
<LatitudeDegrees>48.8929340</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3840.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:21:40Z</Time>
<Position>
<LatitudeDegrees>48.8934736</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3900.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:22:00Z</Time>
<Position>
<LatitudeDegrees>48.8940131</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>3960.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:22:20Z</Time>
<Position>
<LatitudeDegrees>48.8945527</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4020.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:22:40Z</Time>
<Position>
<LatitudeDegrees>48.8950923</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4080.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:23:00Z</Time>
<Position>
<LatitudeDegrees>48.8956319</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4140.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:23:20Z</Time>
<Position>
<LatitudeDegrees>48.8961715</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4200.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:23:40Z</Time>
<Position>
<LatitudeDegrees>48.8967111</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4260.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:24:00Z</Time>
<Position>
<LatitudeDegrees>48.8972507</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4320.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:24:20Z</Time>
<Position>
<LatitudeDegrees>48.8977903</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4380.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:24:40Z</Time>
<Position>
<LatitudeDegrees>48.8983299</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4440.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:25:00Z</Time>
<Position>
<LatitudeDegrees>48.8988695</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4500.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:25:20Z</Time>
<Position>
<LatitudeDegrees>48.8994091</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4560.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:25:40Z</Time>
<Position>
<LatitudeDegrees>48.8999487</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4620.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:26:00Z</Time>
<Position>
<LatitudeDegrees>48.9004883</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4680.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:26:20Z</Time>
<Position>
<LatitudeDegrees>48.9010279</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4740.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:26:40Z</Time>
<Position>
<LatitudeDegrees>48.9015674</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4800.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:27:00Z</Time>
<Position>
<LatitudeDegrees>48.9021070</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4860.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:27:20Z</Time>
<Position>
<LatitudeDegrees>48.9026466</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4920.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:27:40Z</Time>
<Position>
<LatitudeDegrees>48.9031862</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>4980.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:28:00Z</Time>
<Position>
<LatitudeDegrees>48.9037258</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>5040.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:28:20Z</Time>
<Position>
<LatitudeDegrees>48.9042654</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>5100.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:28:40Z</Time>
<Position>
<LatitudeDegrees>48.9048050</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>5160.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:29:00Z</Time>
<Position>
<LatitudeDegrees>48.9053446</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>5220.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:29:20Z</Time>
<Position>
<LatitudeDegrees>48.9058842</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>5280.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:29:40Z</Time>
<Position>
<LatitudeDegrees>48.9064238</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>5340.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T17:30:00Z</Time>
<Position>
<LatitudeDegrees>48.9069634</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>30.0</AltitudeMeters>
<DistanceMeters>5400.009</DistanceMeters>
</Trackpoint>
</Track>
</Lap>
<Creator xsi:type="Device_t">
<Name>kuhy workout_app</Name>
<UnitId>0</UnitId>
<ProductID>0</ProductID>
<Version>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
</Version>
</Creator>
</Activity>
</Activities>
<Author xsi:type="Application_t">
<Name>kuhy workout_app</Name>
<Build>
<Version>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
</Version>
</Build>
<LangID>en</LangID>
<PartNumber>000-00000-00</PartNumber>
</Author>
</TrainingCenterDatabase>

View File

@ -152,36 +152,6 @@ class TestGoldenWalk:
assert by_name["walking"] is True
class TestGoldenDropout:
"""A run whose GPS dropped out for 2 minutes, written by the app's filter.
The app bridges a dropout it did not pause the way RunnerUp's export does
(straight-line metres across the gap), so the PC's dropout rule keeps both
the distance and the moving time. Pinned by the Dart twin
``test/services/run_dropout_tcx_test.dart``.
"""
NAME = "RunnerUp_2026-11-09-18-00-00_Running.tcx"
def test_pc_credits_the_bridged_dropouts_metres_and_moving_time(
self, inbox: Path
) -> None:
"""30 min at 3 m/s with seconds 600-720 unseen: 5400 m and 1800 s."""
_drop(inbox, self.NAME)
data = Verifier()._pull_and_parse_tcx(str(inbox / self.NAME))
assert data is not None
# Zeroed across the gap (the old app) this was 5040 m and 1680 s.
assert data["track_distance_m"] == pytest.approx(5400, abs=1)
assert data["moving_seconds"] == pytest.approx(1800)
def test_the_run_is_verified_on_its_day(self, inbox: Path) -> None:
"""The whole file passes the real file-based verification."""
_drop(inbox, self.NAME)
result = _verify(inbox, "2026-11-09")
assert result is not None
assert result[0] == "verified"
class TestRunnerUpSample:
"""The trimmed real RunnerUp export parses to the numbers Dart's decoder sees."""

View File

@ -116,31 +116,26 @@ class TestVerifyToday:
drop(verifier.folder, "08-00-00_Walking", tcx("Other", 60, "08:00", 0.1))
assert self._verify(verifier) == (
"too_short",
"Walking: 1 walk(s), 0.4 km, 0 min moving -- need 3.5+ km or 30+ min moving",
"Walking: 1 walk(s), 0.4 km, 0 min moving -- need 30+ min moving",
)
def test_a_run_beside_short_walks_is_one_summed_day(
self, verifier: Verifier
) -> None:
def test_a_run_still_verifies_beside_short_walks(self, verifier: Verifier) -> None:
"""A long enough run verifies even when the day also has short walks."""
drop(verifier.folder, "07-00-00_Walking", tcx("Other", 10, "07:00"))
drop(verifier.folder, "18-00-00_Running", tcx("Running", 45, "18:00", 2.5))
result = self._verify(verifier)
assert result is not None
assert result[0] == "verified"
assert result[1].startswith("Activity: 2 activities")
assert result[1].startswith("Running")
def test_a_short_run_and_short_walks_share_one_shortfall(
self, verifier: Verifier
) -> None:
"""A too-short run and short walks are summed into one shortfall."""
def test_a_short_run_outranks_the_walk_shortfall(self, verifier: Verifier) -> None:
"""A too-short run is the reported shortfall rather than the walks'."""
drop(verifier.folder, "07-00-00_Walking", tcx("Other", 10, "07:00"))
drop(verifier.folder, "18-00-00_Running", tcx("Running", 5, "18:00", 2.5))
result = self._verify(verifier)
assert result is not None
assert result[0] == "too_short"
assert result[1].startswith("Activity: 2 activities")
assert "need 3.5+ km or 30+ min moving" in result[1]
assert result[1].startswith("Run was")
class TestBackfill:
@ -179,7 +174,7 @@ class TestBackfill:
log = tmp_path / "log.json"
with caplog.at_level(logging.WARNING):
assert verifier._try_fill_runnerup_for_date(_DAY, log) is False
assert "does not count yet" in caplog.text
assert "do not count yet" in caplog.text
assert not log.exists()
def test_a_run_records_its_end_time(

View File

@ -12,14 +12,25 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker.tests._activity_helpers import tcx
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
# A 5.8 km / 70 min run WITH its trackpoints: lap totals alone credit nothing.
_TCX = tcx("Running", "18:58", moving_min=70, metres=5800)
_TCX = """\
<?xml version="1.0" encoding="UTF-8"?>
<TrainingCenterDatabase
xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2">
<Activities>
<Activity Sport="Running">
<Lap>
<TotalTimeSeconds>4200.0</TotalTimeSeconds>
<DistanceMeters>5800.0</DistanceMeters>
</Lap>
</Activity>
</Activities>
</TrainingCenterDatabase>
"""
def _webdav_tree(tmp_path: Path) -> tuple[Path, Path]:
@ -176,11 +187,11 @@ class TestLocalVerifyAndParse:
) -> None:
"""A path that exists locally is parsed without any adb pull."""
locker = create_locker(mock_tk, tmp_path)
tcx_file = tmp_path / "run.tcx"
tcx_file.write_text(_TCX)
tcx = tmp_path / "run.tcx"
tcx.write_text(_TCX)
object.__setattr__(locker, "_run_adb", MagicMock())
data = locker._pull_and_parse_tcx(str(tcx_file))
data = locker._pull_and_parse_tcx(str(tcx))
assert data is not None
assert data["distance_m"] == 5800.0

View File

@ -1,127 +0,0 @@
"""Speed cap, lap-only files and the shapes real exports have (dropouts, jitter)."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from screen_locker.tests._activity_helpers import (
DAY,
Verifier,
drop,
tcx,
tcx_points,
verify,
)
if TYPE_CHECKING:
from pathlib import Path
@pytest.fixture(name="verifier")
def verifier_fixture(tmp_path: Path) -> Verifier:
"""A Verifier reading a temporary drop directory."""
return Verifier(tmp_path)
def parsed(verifier: Verifier, sport: str, points: list[tuple[int, float]]) -> dict:
"""Drop a track made of exactly ``points`` and return its parsed summary."""
drop(verifier.folder, "08-00-00", "_Running", tcx_points(sport, "08:00", points))
(path,) = verifier._find_runnerup_exports_for_date(DAY)
data = verifier._pull_and_parse_tcx(path)
assert data is not None
return data
class TestLapOnlyExport:
"""An export with laps but no trackpoints has no moving time to credit."""
def test_wall_clock_alone_credits_nothing(self, verifier: Verifier) -> None:
"""40 min on the lap clock, 1 km, no trackpoints: too short."""
body = (
'<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/'
'TrainingCenterDatabase/v2"><Activities><Activity Sport="Running">'
"<Id>2026-10-10T08:00</Id><Lap><TotalTimeSeconds>2400</TotalTimeSeconds>"
"<DistanceMeters>1000</DistanceMeters></Lap></Activity></Activities>"
"</TrainingCenterDatabase>"
)
drop(verifier.folder, "08-00-00", "_Running", body)
result = verify(verifier)
assert result is not None
assert result[0] == "too_short"
class TestSpeedCap:
"""Segments faster than 25 km/h count neither moving time nor distance."""
def test_a_car_trip_credits_nothing(self, verifier: Verifier) -> None:
"""10 km at 40 km/h (15 min) is a vehicle, not a workout."""
drop(
verifier.folder,
"08-00-00",
"_Walking",
tcx("Walking", "08:00", moving_min=15, metres=10000),
)
result = verify(verifier)
assert result is not None
assert result[0] == "too_short"
def test_one_gps_jump_drops_only_its_window(self, verifier: Verifier) -> None:
"""A 60 km/h jump inside a 3 m/s run loses its 10 s window and no more."""
points = [(s, s * 3.0 + (83.0 if s > 600 else 0.0)) for s in range(0, 1201, 5)]
data = parsed(verifier, "Running", points)
assert data["moving_seconds"] == pytest.approx(1190)
assert data["track_distance_m"] == pytest.approx(3570)
result = verify(verifier)
assert result is not None
assert result[0] == "verified"
def test_a_car_with_sparse_fixes_still_credits_nothing(
self, verifier: Verifier
) -> None:
"""40 km/h with a fix every 60 s is dropped as a dropout too."""
points = [(s, s * 11.1) for s in range(0, 1500, 60)]
drop(
verifier.folder,
"08-00-00",
"_Walking",
tcx_points("Walking", "08:00", points),
)
result = verify(verifier)
assert result is not None
assert result[0] == "too_short"
class TestRealRunShapes:
"""Shapes seen in real exports (checked on 27 days of them) stay whole."""
def test_sparse_fixes_every_18_seconds_still_count(
self, verifier: Verifier
) -> None:
"""Old RunnerUp files have a fix every 15-60 s: a 4 km run in 42 min."""
points = [(s, s * 1.6) for s in range(0, 2520, 18)]
data = parsed(verifier, "Running", points)
assert data["track_distance_m"] == pytest.approx(points[-1][1])
assert data["moving_seconds"] == pytest.approx(points[-1][0])
def test_a_gps_dropout_at_running_pace_is_kept(self, verifier: Verifier) -> None:
"""A 2 minute signal loss with the runner still moving keeps both."""
points = [(s, s * 1.7) for s in range(600)]
points += [(s, s * 1.7) for s in range(720, 1320)]
data = parsed(verifier, "Running", points)
assert data["track_distance_m"] == pytest.approx(1319 * 1.7, rel=0.01)
assert data["moving_seconds"] == pytest.approx(1319, rel=0.01)
def test_a_standing_pause_earns_nothing(self, verifier: Verifier) -> None:
"""A 5 minute gap with ~no movement adds no time (and ~no metres)."""
points = [(s, s * 1.7) for s in range(600)]
points += [(s, 600 * 1.7 + 2) for s in range(900, 910)]
data = parsed(verifier, "Running", points)
assert data["moving_seconds"] == pytest.approx(599, abs=12)
def test_one_second_jitter_is_smoothed(self, verifier: Verifier) -> None:
"""A 1 s fix 12 m ahead (12 m/s alone) is noise inside a 3 m/s run."""
points = [(s, s * 3.0 + (12.0 if not s % 50 else 0.0)) for s in range(600)]
data = parsed(verifier, "Running", points)
assert data["track_distance_m"] > 0.97 * points[-1][1]

View File

@ -1,183 +0,0 @@
"""The unified rule sums a day's activities; the root DB and the pure aggregate."""
from __future__ import annotations
from datetime import UTC, datetime
import json
import logging
from typing import TYPE_CHECKING
import pytest
from screen_locker._walk_tcx import (
ActivityDay,
activity_day,
activity_shortfall,
walk_day,
)
from screen_locker.tests._activity_helpers import (
DAY,
Verifier,
drop,
tcx,
verify,
)
if TYPE_CHECKING:
from pathlib import Path
@pytest.fixture(name="verifier")
def verifier_fixture(tmp_path: Path) -> Verifier:
"""A Verifier reading a temporary drop directory."""
return Verifier(tmp_path)
class TestDaySums:
"""Time AND distance add up across a day's files, whatever their sport."""
def test_two_15_min_sessions_make_the_bar(self, verifier: Verifier) -> None:
"""A run and a walk of 15 moving minutes each credit together."""
drop(
verifier.folder,
"07-00-00",
"_Running",
tcx("Running", "07:00", moving_min=15, metres=900),
)
drop(
verifier.folder,
"18-00-00",
"_Walking",
tcx("Other", "18:00", moving_min=15, metres=900),
)
result = verify(verifier)
assert result is not None
assert result[0] == "verified"
def test_two_short_distances_make_the_distance_bar(
self, verifier: Verifier
) -> None:
"""Distance sums per day too: 2 km + 1.6 km is 3.6 km."""
drop(
verifier.folder,
"07-00-00",
"_Running",
tcx("Running", "07:00", moving_min=10, metres=2000),
)
drop(
verifier.folder,
"18-00-00",
"_Walking",
tcx("Other", "18:00", moving_min=10, metres=1600),
)
result = verify(verifier)
assert result is not None
assert result[0] == "verified"
def test_the_same_activity_from_two_sources_counts_once(
self, verifier: Verifier
) -> None:
"""The WebDAV and phone copies of one export are one activity."""
body = tcx("Running", "07:00", moving_min=15, metres=900)
drop(verifier.folder, "07-00-00", "_Running", body)
drop(verifier.folder, "07-00-01", "_Running", body)
result = verify(verifier)
assert result is not None
assert result[0] == "too_short"
def test_a_short_day_reports_what_is_missing(
self, verifier: Verifier, caplog: pytest.LogCaptureFixture
) -> None:
"""The shortfall names both bars and what the day had."""
drop(
verifier.folder,
"07-00-00",
"_Running",
tcx("Running", "07:00", moving_min=10, metres=800),
)
with caplog.at_level(logging.WARNING):
result = verify(verifier)
assert result is not None
assert result[0] == "too_short"
assert "need 3.5+ km or 30+ min moving" in result[1]
def test_the_completion_time_is_the_activity_that_crossed_the_bar(
self, verifier: Verifier, tmp_path: Path
) -> None:
"""completed_at is when the day's total crossed the bar, not its last file."""
drop(
verifier.folder,
"07-00-00",
"_Running",
tcx("Running", "07:00", moving_min=20, metres=1200),
)
drop(
verifier.folder,
"12-00-00",
"_Walking",
tcx("Other", "12:00", moving_min=10, metres=600),
)
drop(
verifier.folder,
"18-00-00",
"_Walking",
tcx("Other", "18:00", moving_min=10, metres=600),
)
log = tmp_path / "log.json"
assert verifier._try_fill_runnerup_for_date(DAY, log) is True
(entry,) = json.loads(log.read_text())[DAY]
crossed = datetime(2026, 10, 10, 12, 10, tzinfo=UTC).timestamp()
assert entry["workout_data"]["completed_at"] == crossed
class TestRootDbFallback:
"""The root DB path has no trackpoints: wall-clock is all it knows."""
def test_a_db_row_is_judged_by_its_duration(self, verifier: Verifier) -> None:
"""No moving_seconds in the dict: the recorded duration stands in."""
row = {"sport": 0, "duration_seconds": 31 * 60, "distance_m": 2000.0}
assert verifier._validate_runnerup_data(row)[0] == "verified"
row["duration_seconds"] = 10 * 60
assert verifier._validate_runnerup_data(row)[0] == "too_short"
def test_sport_code_does_not_change_the_verdict(self, verifier: Verifier) -> None:
"""Every RunnerUp sport code gets the same answer for the same numbers."""
base = {"duration_seconds": 31 * 60, "distance_m": 2000.0}
verdicts = {
verifier._validate_runnerup_data({**base, "sport": code})[0]
for code in (-1, 0, 1, 2, 3, 4, 5, 6, 7)
}
assert verdicts == {"verified"}
class TestActivityDay:
"""The pure day aggregate."""
def test_distance_gets_the_gps_tolerance(self) -> None:
"""3.4 km is within 5% of the 3.5 km minimum; 3.3 km is not."""
near = activity_day([{"distance_m": 3400.0, "moving_seconds": 0.0}])
assert near.qualifies
far = activity_day([{"distance_m": 3300.0, "moving_seconds": 0.0}])
assert not far.qualifies
def test_the_alias_still_imports(self) -> None:
"""walk_day is the old name of activity_day."""
assert walk_day is activity_day
def test_message_styles(self) -> None:
"""A lone run reads like a run, walks like walks, a mix like activities."""
run = {"sport": 0, "distance_m": 4200.0, "moving_seconds": 1560.0}
walk = {"walking": True, "distance_m": 2300.0, "moving_seconds": 1680.0}
assert activity_day([run]).message() == "Running: 4.2 km in 26 min"
assert activity_day([walk]).message() == (
"Walking: 1 walk(s), 2.3 km, 28 min moving"
)
assert activity_day([run, walk]).message() == (
"Activity: 2 activities, 6.5 km, 54 min moving"
)
assert activity_day([{"sport": 99}]).message().startswith("99:")
def test_shortfall_text(self) -> None:
"""The shortfall names both ways to qualify."""
day: ActivityDay = activity_day([{"distance_m": 100.0, "moving_seconds": 60.0}])
assert activity_shortfall(day).endswith("need 3.5+ km or 30+ min moving")

View File

@ -1,158 +0,0 @@
"""One crediting rule for every GPS activity: sport and file name never matter.
A day's activities (runs, walks, RunnerUp's files and the workout app's alike)
are summed and credit once their distance reaches ``MIN_RUN_DISTANCE_KM`` (with
the GPS tolerance) OR their *moving* time reaches the shared duration bar.
Wall-clock time never counts: a pause or a standing-still stretch earns
nothing. Everything runs on temporary directories.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
import pytest
from screen_locker.tests._activity_helpers import DAY, Verifier, drop, tcx, verify
if TYPE_CHECKING:
from pathlib import Path
@pytest.fixture(name="verifier")
def verifier_fixture(tmp_path: Path) -> Verifier:
"""A Verifier reading a temporary drop directory."""
return Verifier(tmp_path)
class TestRequiredCases:
"""The four cases kuhy named when he unified runs and walks."""
def test_a_walking_file_of_3_6_km_in_40_min_is_credited(
self, verifier: Verifier
) -> None:
"""(a) A Walking-sport export at 3.6 km / 40 min credits."""
drop(
verifier.folder,
"08-00-00",
"_Walking",
tcx("Walking", "08:00", moving_min=40, metres=3600),
)
result = verify(verifier)
assert result is not None
assert result[0] == "verified"
def test_a_walking_file_of_3_6_km_in_18_min_is_credited_by_distance(
self, verifier: Verifier
) -> None:
"""(a) Distance alone credits a walk, as it always did a run."""
drop(
verifier.folder,
"08-00-00",
"_Walking",
tcx("Walking", "08:00", moving_min=18, metres=3600),
)
result = verify(verifier)
assert result is not None
assert result[0] == "verified"
def test_a_running_file_with_31_min_moving_and_2_km_is_credited(
self, verifier: Verifier
) -> None:
"""(b) Moving time alone credits a run."""
drop(
verifier.folder,
"18-00-00",
"_Running",
tcx("Running", "18:00", moving_min=31, metres=2000),
)
result = verify(verifier)
assert result is not None
assert result[0] == "verified"
def test_a_pause_does_not_buy_a_run_its_duration(self, verifier: Verifier) -> None:
"""(c) 24 min moving + 10 min pause = 34 min wall-clock: not credited.
(24 not 25: the duration bar is 30 minus the 5 minute leeway, so a
full 25 minutes of motion DOES credit.)
"""
drop(
verifier.folder,
"18-00-00",
"_Running",
tcx("Running", "18:00", moving_min=24, metres=1600, pause_min=10),
)
result = verify(verifier)
assert result is not None
assert result[0] == "too_short"
def test_a_pause_does_not_buy_a_run_its_log_entry(
self, verifier: Verifier, tmp_path: Path
) -> None:
"""(c) The backfill path agrees: nothing is logged."""
drop(
verifier.folder,
"18-00-00",
"_Running",
tcx("Running", "18:00", moving_min=24, metres=1600, pause_min=10),
)
log = tmp_path / "log.json"
assert verifier._try_fill_runnerup_for_date(DAY, log) is False
assert not log.exists()
_TRACKS = {
"qualifying_by_time": {"moving_min": 31, "metres": 2000},
"qualifying_by_distance": {"moving_min": 18, "metres": 3600},
"paused_short": {"moving_min": 24, "metres": 1600, "pause_min": 10},
"short": {"moving_min": 10, "metres": 800},
}
_DRESSINGS = [
("Running", "_Running"),
("Walking", "_Walking"),
("Other", "_Walking"),
("Other", ""),
("Biking", ""),
]
class TestSportAndNameNeverMatter:
"""(d) The same track gives the same outcome under any sport or file name."""
@pytest.mark.parametrize("track", sorted(_TRACKS))
def test_status_and_log_are_identical(self, track: str, tmp_path: Path) -> None:
"""Every dressing of one track verifies, logs and credits alike."""
outcomes = set()
for index, (sport, suffix) in enumerate(_DRESSINGS):
folder = tmp_path / f"d{index}"
folder.mkdir()
verifier = Verifier(folder)
drop(folder, "08-00-00", suffix, tcx(sport, "08:00", **_TRACKS[track]))
status = verify(verifier)
assert status is not None
log = folder / "log.json"
filled = verifier._try_fill_runnerup_for_date(DAY, log)
credited = (
json.loads(log.read_text())[DAY][0]["workout_data"]["completed_at"]
if filled
else None
)
outcomes.add((status[0], filled, credited))
assert len(outcomes) == 1
def test_the_activity_label_is_kept_but_never_decides(
self, verifier: Verifier, tmp_path: Path
) -> None:
"""A walk keeps ``activity: walking`` in the log for the phone's display."""
drop(
verifier.folder,
"08-00-00",
"_Walking",
tcx("Other", "08:00", moving_min=31, metres=2000),
)
log = tmp_path / "log.json"
assert verifier._try_fill_runnerup_for_date(DAY, log) is True
(entry,) = json.loads(log.read_text())[DAY]
assert entry["workout_data"]["activity"] == "walking"
assert entry["workout_data"]["type"] == "runnerup_verified"

View File

@ -72,36 +72,15 @@ class TestTrackSummary:
assert summary["activity_id"] == "A1"
assert summary["ended_at"] == (_START + timedelta(seconds=600)).timestamp()
def test_standing_is_not_moving_but_a_run_is(self) -> None:
"""Standing still adds no moving time; any speed above it does (runs)."""
def test_standing_and_vehicles_are_not_moving(self) -> None:
"""Standing-still and vehicle speeds add no moving time."""
assert not track_summary(walk(600, speed=0.1))["moving_seconds"]
assert track_summary(walk(600, speed=4.5))["moving_seconds"] == (
pytest.approx(600)
)
assert not track_summary(walk(600, speed=8.0))["moving_seconds"]
def test_a_repeated_timestamp_tail_adds_nothing(self) -> None:
"""A final fix with the same time as the one before it has no duration."""
summary = track_summary(
activity([(0, "0", None), (20, "30", None), (20, "31", None)])
)
assert summary["moving_seconds"] == pytest.approx(20)
def test_a_slow_dropout_earns_nothing(self) -> None:
"""Two points 100 s apart, 30 m: a pause, not motion. No time."""
summary = track_summary(activity([(0, "0.1", None), (100, "30", None)]))
assert not summary["moving_seconds"]
def test_a_dropout_at_walking_pace_keeps_its_time(self) -> None:
"""Two points 100 s apart, 130 m: the walker kept walking while unseen."""
def test_a_gps_dropout_earns_nothing(self) -> None:
"""Two points 100 s apart at walking pace: motion unseen, not counted."""
summary = track_summary(activity([(0, "0.1", None), (100, "130", None)]))
assert summary["moving_seconds"] == pytest.approx(100)
assert summary["track_distance_m"] == pytest.approx(129.9)
def test_a_vehicle_across_a_dropout_earns_nothing(self) -> None:
"""Two points 100 s apart, 2 km: 72 km/h is not a person."""
summary = track_summary(activity([(0, "0", None), (100, "2000", None)]))
assert not summary["moving_seconds"]
assert not summary["track_distance_m"]
def test_unusable_points_are_skipped(
self, caplog: pytest.LogCaptureFixture
@ -122,12 +101,7 @@ class TestTrackSummary:
def test_no_points_has_no_end(self) -> None:
"""A track with no points has zero moving time and no end."""
summary = track_summary(activity([]))
assert summary == {
"activity_id": "A1",
"moving_seconds": 0.0,
"track_distance_m": 0.0,
"ended_at": None,
}
assert summary == {"activity_id": "A1", "moving_seconds": 0.0, "ended_at": None}
def leg(
@ -136,7 +110,6 @@ def leg(
"""Build a per-walk summary dict like track_summary produces."""
return {
"activity_id": ident,
"walking": True,
"moving_seconds": minutes * 60,
"ended_at": ended,
"distance_m": metres,
@ -175,7 +148,7 @@ class TestWalkDay:
def test_shortfall_says_what_is_missing(self) -> None:
"""The shortfall text states how much moving time is still needed."""
text = walk_shortfall(walk_day([leg("a", 20, 1.0)]))
assert text.endswith("need 3.5+ km or 30+ min moving")
assert text.endswith("need 30+ min moving")
def test_walks_share_the_one_workout_accept_bar(self) -> None:
# Same advertised-30 / accept-25 bar as every other workout type.

View File

@ -105,9 +105,7 @@ run_precommit_group() {
run_pytest_clean_venv() {
log "pytest in the clean venv (mirrors the Tests workflow)"
# CI_MIRROR_WORKERS: xdist worker count (default auto = one per core; on a
# busy 24-core box that is ~3 GiB and trips the capped.sh memory ceiling).
"$VENV_DIR/bin/python" -m pytest -n "${CI_MIRROR_WORKERS:-auto}" --dist worksteal "$@" \
"$VENV_DIR/bin/python" -m pytest -n auto --dist worksteal "$@" \
|| fail "pytest (clean requirements.txt venv)"
}

View File

@ -16,25 +16,17 @@ Implementing design_v2.md improvements.
sync layer owns that database's ordering)
## GPS runs (foundation, 2026-11-10)
- The app records one mode: every GPS activity is a run (25 km/h jump cap,
`Sport="Running"`, `_Running.tcx`); the PC credits all with one rule. No
run/walk toggle. `decodeTcx` still reads old `_Walking.tcx` imports. Optional
pace target (`pace_band.dart`, picker `run_pace_picker.dart`); idle map follows
the user's fix (`idle_location.dart`, display-only); location refused = no
map and no start, only the red icon. The app uploads a TCX the PC credits unchanged.
- The app records runs/walks itself and uploads a TCX the PC credits unchanged.
Contract = the PC parser, pinned by `screen_locker/tests/fixtures/run_tcx/`
(Dart `test/services/tcx_golden_fixture_test.dart` <-> pytest
`screen_locker/tests/test_run_tcx_golden.py`). Regenerate after a deliberate
codec change: `UPDATE_GOLDEN=1 flutter test test/services/tcx_golden_fixture_test.dart`.
- File name `RunnerUp_YYYY-MM-DD-HH-MM-SS_<Running>.tcx` (historic: `Walking`), stamp in
- File name `RunnerUp_YYYY-MM-DD-HH-MM-SS_<Running|Walking>.tcx`, stamp in
LOCAL time; `<Id>`/`<Time>` UTC `Z`; source tag `kuhy workout_app` in
`Author/Name` + `Creator/Name`.
- Trackpoints must be <= 30 s apart with cumulative `DistanceMeters`, or the PC
credits no moving time (`lib/services/run_math.dart` mirrors that rule).
- Thresholds that decide credit live on the PC only, one rule for runs and
walks alike: a day's summed distance >= 3.5 km OR summed moving time >= 25 min (pairs
faster than 25 km/h count neither)
(`screen_locker/_walk_tcx.py`); sport and file-name suffix never matter.
credits no walking time (`lib/services/run_math.dart` mirrors that rule).
- Thresholds that decide credit (3.5 km / 25 min) live on the PC only.
- GPS sits behind `PositionSource` (`position_source*.dart`); imported
RunnerUp runs are stored with `upload_state='never'` (table CHECK).
- RunnerUp history import (`runnerup_importer.dart`): once, on app start, on

View File

@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-all.zip

View File

@ -1,48 +1,4 @@
{
"pace_fast.wav": {
"file": "pace_fast.wav",
"frames": 12348,
"recipe": {
"attack_seconds": 0.01,
"notes": [
[
880.0,
0.11
],
[
1319.0,
0.17
]
],
"peak": 0.6,
"sample_rate": 44100
},
"sample_rate": 44100,
"seconds": 0.28,
"sha256": "9d9297b0f681cf00490cbbb0b4316b9607002ca7e0cb2ef3d33622b52091349e"
},
"pace_slow.wav": {
"file": "pace_slow.wav",
"frames": 24696,
"recipe": {
"attack_seconds": 0.01,
"notes": [
[
494.0,
0.22
],
[
370.0,
0.34
]
],
"peak": 0.6,
"sample_rate": 44100
},
"sample_rate": 44100,
"seconds": 0.56,
"sha256": "5bea2e6c64b57065fb72436f8246ea6ded4e58f2c8f070a0aef3b135fb871bf6"
},
"workout_done.wav": {
"file": "workout_done.wav",
"frames": 24255,

View File

@ -6,11 +6,10 @@ import 'package:flutter/foundation.dart';
/// The sports the app records.
enum RunSport {
/// A run. The PC credits every GPS activity alike: a day's distance OR
/// moving time, whatever the sport.
/// A run; credited on distance OR duration by the PC.
running('Running', 'Running'),
/// A walk; read from old files only (the app records everything as a run).
/// A walk; the PC sums a day's walks and credits their moving time.
///
/// Written as `Sport="Other"` exactly like RunnerUp does (the TCX schema
/// only knows Running, Biking and Other); the `_Walking.tcx` file-name
@ -80,7 +79,7 @@ class RunPoint {
/// Cumulative credited distance from the start, in metres.
///
/// The PC derives speed from the difference between two points'
/// The PC derives walking speed from the difference between two points'
/// values, so this is the field the recorder must keep honest.
final double distanceM;

View File

@ -7,7 +7,7 @@ import 'package:flutter/foundation.dart';
import 'package:workout_app/services/pc_poke_wire.dart';
/// Makes every `dart:io` HTTP connection fail before a socket is opened --
/// except the workout poke to the configured PC and OSM map tiles.
/// except the workout poke to the configured PC.
///
/// Installed as `HttpOverrides.global` by `main` in the sandbox. Firebase and
/// GitHub sync both go through `package:http`, whose IO client is built from
@ -19,11 +19,6 @@ import 'package:workout_app/services/pc_poke_wire.dart';
/// workout can time the PC round trip. The PC verifies the signed
/// `"sandbox": true` and never writes or credits it. Firebase and GitHub are
/// https on 443 and can never match.
///
/// The other exception is `https://tile.openstreetmap.org/{z}/{x}/{y}.png`
/// (zoom 0-19) for the run map, under OSM's tile usage policy: the map sends
/// a real User-Agent, caches tiles on disk, never prefetches, and nothing else
/// in the app GETs that host.
class SandboxHttpOverrides extends HttpOverrides {
/// The PC host the poke may reach; set by `PcPairing` whenever the host is
/// loaded or saved. Null means no exception at all.
@ -37,19 +32,6 @@ class SandboxHttpOverrides extends HttpOverrides {
uri.port == kPcPokePort &&
uri.path == kPcPokePath;
/// The only tile host the sandbox may reach.
static const tileHost = 'tile.openstreetmap.org';
static final _tilePath = RegExp(r'^/(\d|1[0-9])/\d+/\d+\.png$');
/// Whether [uri] is an OSM raster tile (https, port 443, zoom <= 19).
static bool allowsTile(Uri uri) =>
uri.scheme == 'https' &&
uri.host == tileHost &&
uri.port == 443 &&
!uri.hasQuery &&
_tilePath.hasMatch(uri.path);
@override
HttpClient createHttpClient(SecurityContext? context) {
return super.createHttpClient(context)
@ -60,12 +42,6 @@ class SandboxHttpOverrides extends HttpOverrides {
);
return Socket.startConnect(uri.host, uri.port);
}
if (proxyHost == null && allowsTile(uri)) {
debugPrint('WorkoutSandbox: allowing OSM tile ${uri.path}');
// A connection factory must return the TLS socket itself; a plain
// one makes the server answer https with "Invalid request method".
return SecureSocket.startConnect(uri.host, uri.port);
}
debugPrint(
'WorkoutSandbox: refused network connection to ${uri.host} — the '
'sandbox never talks to Firebase or GitHub.',

View File

@ -1,12 +1,13 @@
/// The sandbox's GPS: a synthetic loop replayed faster than real time.
///
/// There is no bundled asset (that would need a pubspec entry): the track is a
/// pure function of the start time, so every replay gets its own
/// pure function of the start time and sport, so every replay gets its own
/// `RunTrack.id` and two replays never collide in the `runs` table.
library;
import 'dart:math' as math;
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
@ -23,14 +24,19 @@ const int kFixStepSeconds = 2;
const double _centreLat = 50;
const double _centreLon = 10;
/// Pace of the replay: 10 km/h.
const double kReplaySpeedMps = 10 / 3.6;
/// Pace of the replay: 10 km/h for a run, a stroll for a walk (a run's speed
/// would trip the walking jump cap and credit nothing).
double replaySpeedMps(RunSport sport) => switch (sport) {
RunSport.running => 10 / 3.6,
RunSport.walking => 5 / 3.6,
};
/// Fixes for one lap of a [kLoopLengthM] circle starting at [start], one every
/// [kFixStepSeconds], 5 m accuracy.
List<GpsFix> sandboxLoopFixes(DateTime start) {
List<GpsFix> sandboxLoopFixes(DateTime start, RunSport sport) {
const radius = kLoopLengthM / (2 * math.pi);
final steps = (kLoopLengthM / kReplaySpeedMps / kFixStepSeconds).round();
final steps = (kLoopLengthM / replaySpeedMps(sport) / kFixStepSeconds)
.round();
const metresPerDegree = 111194.9;
final lonScale = metresPerDegree * math.cos(_centreLat * math.pi / 180);
return [
@ -50,21 +56,15 @@ List<GpsFix> sandboxLoopFixes(DateTime start) {
/// The sandbox's [PositionSource]: the loop at [Sandbox.runReplayFactor] times
/// real speed, starting now.
PositionSource sandboxRunSource({DateTime? now}) => ScriptedPositionSource(
sandboxLoopFixes(now ?? DateTime.now()),
fixDelay: Duration(
microseconds: kFixStepSeconds * 1000000 ~/ Sandbox.runReplayFactor,
),
);
PositionSource sandboxRunSource(RunSport sport, {DateTime? now}) =>
ScriptedPositionSource(
sandboxLoopFixes(now ?? DateTime.now(), sport),
fixDelay: Duration(
microseconds: kFixStepSeconds * 1000000 ~/ Sandbox.runReplayFactor,
),
);
/// The source a recording uses: the replay in the sandbox, the phone's GPS
/// otherwise.
PositionSource positionSourceFor() =>
Sandbox.enabled ? sandboxRunSource() : GeolocatorPositionSource();
/// The source the idle map watches: in the sandbox just the replay's first
/// fix (so the marker sits at the loop's start and does not walk the lap
/// before the run), the phone's GPS otherwise.
PositionSource idlePositionSourceFor({DateTime? now}) => Sandbox.enabled
? ScriptedPositionSource([sandboxLoopFixes(now ?? DateTime.now()).first])
: GeolocatorPositionSource();
PositionSource positionSourceFor(RunSport sport) =>
Sandbox.enabled ? sandboxRunSource(sport) : GeolocatorPositionSource();

View File

@ -1,9 +1,8 @@
/// The live run screen: map, big numbers, pace target, start/pause/finish.
/// The live run/walk screen: sport, start/pause/finish, and big numbers.
///
/// One screen, no scrolling (R7), and no words (textgate): icons, colours and
/// digits only. Icons that report a problem are tappable where the fix is in
/// system settings. With location refused there is no map and no start, only
/// the red problem icon; coming back from settings with a grant recovers it.
/// system settings.
library;
import 'dart:async';
@ -11,7 +10,6 @@ import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:latlong2/latlong.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
@ -19,8 +17,6 @@ import 'package:workout_app/sandbox/sandbox_run_replay.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/foreground_run_client_flutter.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/pace_target_store.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_format.dart';
import 'package:workout_app/services/run_recorder.dart';
@ -29,17 +25,14 @@ import 'package:workout_app/services/run_uploader.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_map_slot.dart';
import 'package:workout_app/widgets/run_pace_picker.dart';
import 'package:workout_app/widgets/run_upload_badge.dart';
part 'run_screen_numbers.dart';
part 'run_screen_parts.dart';
/// The controller the app uses: real GPS (or the sandbox replay), the real
/// foreground service, the real database and the app-wide upload queue.
RunController buildRunController() => RunController(
sourceFor: positionSourceFor,
idleSourceFor: idlePositionSourceFor,
service: FlutterForegroundRunClient(),
cues: FeedbackCues(AudioPlayer()),
save: (track) => saveRecordedRun(
@ -49,23 +42,13 @@ RunController buildRunController() => RunController(
),
);
/// Builds the live map from the run's accepted points and the user's current
/// position (shown until the run has points).
typedef RunMapBuilder =
Widget Function(
BuildContext context,
ValueListenable<List<RunPoint>> points,
ValueListenable<LatLng?> position,
);
/// Records one GPS activity (always a run).
/// Records one run or walk.
class RunScreen extends StatefulWidget {
/// Creates the screen; every argument is a test or map seam.
const RunScreen({
super.key,
this.controllerFactory = buildRunController,
this.uploader,
this.paceStore,
this.mapBuilder,
this.openSettings = openAppSettings,
});
@ -76,11 +59,10 @@ class RunScreen extends StatefulWidget {
/// The upload queue shown in the badge; defaults to the app-wide one.
final RunUploader? uploader;
/// Where the last pace target is kept; defaults to shared_preferences.
final PaceTargetStore? paceStore;
/// Builds the live map; defaults to [RunMapSlot].
final RunMapBuilder? mapBuilder;
/// Builds the live map from the run's accepted points; defaults to the
/// [RunMapSlot] placeholder. This is where the map widget goes.
final Widget Function(BuildContext, ValueListenable<List<RunPoint>>)?
mapBuilder;
/// Opens the system settings page for this app.
final Future<bool> Function() openSettings;
@ -89,55 +71,27 @@ class RunScreen extends StatefulWidget {
State<RunScreen> createState() => _RunScreenState();
}
class _RunScreenState extends State<RunScreen> with WidgetsBindingObserver {
class _RunScreenState extends State<RunScreen> {
late RunController _controller = widget.controllerFactory();
late final RunUploader _uploader = widget.uploader ?? RunUploader.instance;
late final PaceTargetStore _paceStore =
widget.paceStore ?? PrefsPaceTargetStore();
bool _starting = false;
bool _paceOn = false;
int _paceTarget = kDefaultPaceTarget;
@override
void initState() {
super.initState();
SandboxLog.event('open run');
WidgetsBinding.instance.addObserver(this);
unawaited(_controller.watchIdle());
unawaited(_loadPaceTarget());
// So the badge shows the real queue, not the pre-first-pass default.
unawaited(_uploader.uploadPending());
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_controller.dispose();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// A silent re-check: the permission prompt itself backgrounds the app, so
// asking again here would loop.
if (state == AppLifecycleState.resumed) {
unawaited(_controller.recheckAccess());
}
}
Future<void> _loadPaceTarget() async {
final stored = await _paceStore.load();
if (mounted) setState(() => _paceTarget = stored);
}
void _setPaceTarget(int seconds) {
setState(() => _paceTarget = seconds);
unawaited(_paceStore.save(seconds));
}
Future<void> _start() async {
setState(() => _starting = true);
_controller.recorder.setPaceTarget(_paceOn ? _paceTarget : null);
try {
await _controller.start();
} finally {
@ -148,30 +102,15 @@ class _RunScreenState extends State<RunScreen> with WidgetsBindingObserver {
void _again() {
final old = _controller;
setState(() => _controller = widget.controllerFactory());
unawaited(_controller.watchIdle());
old.dispose();
}
/// Fixable refusals open the system settings; a plain denial asks again.
VoidCallback? _issueTap(RunIssue issue) => switch (issue) {
RunIssue.deniedForever ||
RunIssue.serviceOff => () => unawaited(widget.openSettings()),
RunIssue.denied => () => unawaited(_controller.watchIdle()),
_ => null,
};
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final c = _controller;
final r = c.recorder;
final blocked = c.blocked;
final issue = _IssueButton(
issue: r.issue,
onTap: _issueTap(r.issue),
size: blocked ? 96 : 24,
);
return PopScope(
// A recording lives in this screen's controller: leaving would lose it.
canPop: !c.active,
@ -184,38 +123,25 @@ class _RunScreenState extends State<RunScreen> with WidgetsBindingObserver {
_StatusRow(
controller: c,
uploader: _uploader,
issue: blocked ? null : issue,
openSettings: widget.openSettings,
),
const SizedBox(height: AppSpacing.sm),
if (blocked)
Expanded(child: Center(child: issue))
else ...[
Expanded(
flex: 4,
child: KeyedSubtree(
key: ObjectKey(c),
child: (widget.mapBuilder ?? _defaultMap)(
context,
r.livePoints,
c.position,
),
),
),
const SizedBox(height: AppSpacing.md),
Expanded(flex: 3, child: _Numbers(recorder: r)),
const SizedBox(height: AppSpacing.md),
_Controls(
controller: c,
starting: _starting,
paceOn: _paceOn,
paceTarget: _paceTarget,
onPaceToggle: () => setState(() => _paceOn = !_paceOn),
onPaceChanged: _setPaceTarget,
onStart: () => unawaited(_start()),
onAgain: _again,
onClose: () => Navigator.of(context).maybePop(),
),
],
Expanded(
flex: 4,
child:
widget.mapBuilder?.call(context, r.livePoints) ??
RunMapSlot(points: r.livePoints),
),
const SizedBox(height: AppSpacing.md),
Expanded(flex: 3, child: _Numbers(recorder: r)),
const SizedBox(height: AppSpacing.md),
_Controls(
controller: c,
starting: _starting,
onStart: () => unawaited(_start()),
onAgain: _again,
onClose: () => Navigator.of(context).maybePop(),
),
],
),
),
@ -225,9 +151,3 @@ class _RunScreenState extends State<RunScreen> with WidgetsBindingObserver {
},
);
}
Widget _defaultMap(
BuildContext context,
ValueListenable<List<RunPoint>> points,
ValueListenable<LatLng?> position,
) => RunMapSlot(points: points, position: position);

View File

@ -1,87 +0,0 @@
// The run screen's big numbers: moving time, distance, the run's average pace
// and, with a pace target on, the current pace coloured by the band.
part of 'run_screen.dart';
class _Numbers extends StatelessWidget {
const _Numbers({required this.recorder});
final RunRecorder recorder;
/// Green on pace, red off it, plain while there is no verdict yet.
Color _paceColour(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final colors = Theme.of(context).extension<AppStatusColors>()!;
final band = recorder.coach.band;
if (band == null) return scheme.onSurface;
return band == PaceBand.onPace ? colors.success : scheme.error;
}
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
const figures = [FontFeature.tabularFigures()];
Widget big(Key key, String text, double size, Color color) => FittedBox(
fit: BoxFit.scaleDown,
child: Text(
text,
key: key,
style: TextStyle(
fontSize: size,
fontWeight: FontWeight.w600,
color: color,
fontFeatures: figures,
),
),
);
Widget small(IconData icon, Key key, String text, {Color? colour}) =>
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: scheme.onSurfaceVariant),
const SizedBox(width: AppSpacing.xs),
Flexible(child: big(key, text, 48, colour ?? scheme.onSurface)),
],
),
);
final current = recorder.coach.pace;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: big(
const Key('run_time'),
formatDuration(recorder.seconds),
96,
scheme.onSurface,
),
),
const SizedBox(height: AppSpacing.sm),
Row(
children: [
small(
Icons.straighten,
const Key('run_distance'),
formatDistanceKm(recorder.distanceM),
),
small(
Icons.speed,
const Key('run_pace'),
formatPace(
seconds: recorder.seconds,
distanceM: recorder.distanceM,
),
),
if (recorder.coach.target != null)
small(
Icons.bolt,
const Key('run_pace_now'),
current == null ? '-:--' : formatPaceSeconds(current.round()),
colour: _paceColour(context),
),
],
),
],
);
}
}

View File

@ -1,7 +1,11 @@
// The run screen's bands: status icons and the buttons (the numbers have
// their own part).
// The run screen's three bands: status icons, the big numbers, the buttons.
part of 'run_screen.dart';
IconData _sportIcon(RunSport sport) => switch (sport) {
RunSport.running => Icons.directions_run,
RunSport.walking => Icons.directions_walk,
};
/// Problems with the recording, as an icon (null when there is none).
({IconData icon, bool danger})? _issueFace(RunIssue issue) => switch (issue) {
RunIssue.none => null,
@ -13,55 +17,26 @@ part of 'run_screen.dart';
RunIssue.tooShort => (icon: Icons.error_outline, danger: true),
};
/// The red problem icon; [size] 24 in the status row, large when it is the
/// only thing on the screen (location refused).
class _IssueButton extends StatelessWidget {
const _IssueButton({
required this.issue,
required this.onTap,
required this.size,
});
final RunIssue issue;
final VoidCallback? onTap;
final double size;
@override
Widget build(BuildContext context) {
final face = _issueFace(issue);
if (face == null) return const SizedBox.shrink();
final scheme = Theme.of(context).colorScheme;
final colors = Theme.of(context).extension<AppStatusColors>()!;
return IconButton(
key: Key('run_issue_${issue.name}'),
onPressed: onTap,
iconSize: size,
icon: Icon(
face.icon,
color: face.danger ? scheme.error : colors.warning,
semanticLabel: issue.name,
),
);
}
}
class _StatusRow extends StatelessWidget {
const _StatusRow({
required this.controller,
required this.uploader,
required this.issue,
required this.openSettings,
});
final RunController controller;
final RunUploader uploader;
/// The problem icon, or null when it is shown elsewhere (or not at all).
final Widget? issue;
final Future<bool> Function() openSettings;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final colors = Theme.of(context).extension<AppStatusColors>()!;
final recorder = controller.recorder;
final issue = _issueFace(recorder.issue);
final fixable =
recorder.issue == RunIssue.deniedForever ||
recorder.issue == RunIssue.serviceOff;
final serviceIcon = switch (controller.serviceState) {
RunServiceState.runningHidden => (Icons.notifications_off, false),
RunServiceState.failed => (Icons.warning_amber, true),
@ -99,21 +74,100 @@ class _StatusRow extends StatelessWidget {
semanticLabel: controller.serviceState.name,
),
),
?issue,
if (issue != null)
IconButton(
key: Key('run_issue_${recorder.issue.name}'),
onPressed: fixable ? () => unawaited(openSettings()) : null,
icon: Icon(
issue.icon,
color: issue.danger ? scheme.error : colors.warning,
semanticLabel: recorder.issue.name,
),
),
Padding(
padding: const EdgeInsets.only(left: AppSpacing.sm),
child: Icon(
_sportIcon(recorder.sport),
color: scheme.onSurfaceVariant,
semanticLabel: recorder.sport.name,
),
),
],
),
);
}
}
class _Numbers extends StatelessWidget {
const _Numbers({required this.recorder});
final RunRecorder recorder;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
const figures = [FontFeature.tabularFigures()];
Widget big(Key key, String text, double size, Color color) => FittedBox(
fit: BoxFit.scaleDown,
child: Text(
text,
key: key,
style: TextStyle(
fontSize: size,
fontWeight: FontWeight.w600,
color: color,
fontFeatures: figures,
),
),
);
Widget small(IconData icon, Key key, String text) => Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: scheme.onSurfaceVariant),
const SizedBox(width: AppSpacing.sm),
Flexible(child: big(key, text, 48, scheme.onSurface)),
],
),
);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: big(
const Key('run_time'),
formatDuration(recorder.seconds),
96,
scheme.onSurface,
),
),
const SizedBox(height: AppSpacing.sm),
Row(
children: [
small(
Icons.straighten,
const Key('run_distance'),
formatDistanceKm(recorder.distanceM),
),
small(
Icons.speed,
const Key('run_pace'),
formatPace(
seconds: recorder.seconds,
distanceM: recorder.distanceM,
),
),
],
),
],
);
}
}
class _Controls extends StatelessWidget {
const _Controls({
required this.controller,
required this.starting,
required this.paceOn,
required this.paceTarget,
required this.onPaceToggle,
required this.onPaceChanged,
required this.onStart,
required this.onAgain,
required this.onClose,
@ -121,10 +175,6 @@ class _Controls extends StatelessWidget {
final RunController controller;
final bool starting;
final bool paceOn;
final int paceTarget;
final VoidCallback onPaceToggle;
final ValueChanged<int> onPaceChanged;
final VoidCallback onStart;
final VoidCallback onAgain;
final VoidCallback onClose;
@ -154,19 +204,20 @@ class _Controls extends StatelessWidget {
final buttons = switch (recorder.phase) {
RunPhase.idle => [
Flexible(
child: RunPacePicker(
on: paceOn,
seconds: paceTarget,
onToggle: onPaceToggle,
onChanged: onPaceChanged,
),
),
button(
'start',
Icons.play_arrow,
starting || !controller.canStart ? null : onStart,
SegmentedButton<RunSport>(
key: const Key('run_sport'),
showSelectedIcon: false,
segments: [
for (final sport in RunSport.values)
ButtonSegment(
value: sport,
icon: Icon(_sportIcon(sport), semanticLabel: sport.name),
),
],
selected: {recorder.sport},
onSelectionChanged: (s) => recorder.selectSport(s.single),
),
button('start', Icons.play_arrow, starting ? null : onStart),
],
RunPhase.recording => [
button('pause', Icons.pause, controller.pause),

View File

@ -76,7 +76,7 @@ class _SandboxSectionState extends State<_SandboxSection> {
const _SectionHeader('SANDBOX'),
const SizedBox(height: 4),
Text(
'This install is the sandbox: its own data, no sync (only the '
'This install is the sandbox: its own data, no network (only the '
'signed sandbox poke to the PC LINK address, which the PC never '
'credits), no LAN server. Nothing here can reach the daily build.',
style: TextStyle(

View File

@ -8,23 +8,8 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:vibration/vibration.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/storage_service.dart';
/// The vibration pattern (pause, buzz, pause, buzz ... in ms) of a pace cue:
/// one long buzz to speed up, three short ones to ease off. Both differ from
/// the kilometre double buzz.
List<int> paceCuePattern(PaceCue cue) => switch (cue) {
PaceCue.tooSlow => const [0, 700],
PaceCue.tooFast => const [0, 90, 70, 90, 70, 90],
};
/// The tone of a pace cue: falling to speed up, rising to ease off.
String paceCueSound(PaceCue cue) => switch (cue) {
PaceCue.tooSlow => 'sounds/pace_slow.wav',
PaceCue.tooFast => 'sounds/pace_fast.wav',
};
/// Cues for recording a set and finishing a workout.
///
/// They reward the RECORDING, never the number recorded: a deloaded or failed
@ -91,22 +76,4 @@ class FeedbackCues {
debugPrint('WorkoutApp: kilometre chime failed to play ($error).');
});
}
/// The runner left the pace band: the cue's buzz pattern and, if allowed,
/// its tone. Silent while on pace (the caller only calls this off pace).
Future<void> paceOff(PaceCue cue) async {
SandboxLog.event('cue pace', {'cue': cue.name, 'sound': soundOn});
if (await Vibration.hasVibrator()) {
// Android/iOS-only: hasVibrator() is false on the Linux test host.
// coverage:ignore-start
unawaited(Vibration.vibrate(pattern: paceCuePattern(cue)));
// coverage:ignore-end
}
if (!soundOn) return;
await _player.play(AssetSource(paceCueSound(cue))).catchError((
Object error,
) {
debugPrint('WorkoutApp: pace tone failed to play ($error).');
});
}
}

View File

@ -58,21 +58,21 @@ enum FixVerdict {
/// Dropped: not strictly later (whole seconds) than the last point.
outOfOrder,
/// Dropped: implies a speed above [kRunningMaxSpeedMps], i.e. a GPS jump.
/// Dropped: implies a speed above the sport's cap, i.e. a GPS jump.
tooFast,
}
/// Accumulates accepted points and their cumulative credited distance.
///
/// A step between two accepted points adds its straight-line distance only
/// when it is a moving step (see [isMovingStep]). A signal dropout (a gap over
/// [kMaxCreditGapSeconds] with no pause) is bridged the way RunnerUp's export
/// bridges it, provided it implies [kMinDropoutSpeedMps] or faster; anything
/// above the jump cap is rejected, and standing-still jitter credits nothing.
/// A user pause ([breakSegment]) never bridges: pauses earn nothing.
/// A step between two accepted points adds distance only when it is a moving
/// step (see [isMovingStep]): a dropout longer than [kMaxCreditGapSeconds]
/// and standing-still jitter credit nothing, same as the PC reads a walk.
class GpsFilter {
/// Creates a filter; every recording uses the running jump cap.
GpsFilter();
/// Creates a filter for [sport] (which picks the speed cap).
GpsFilter({required this.sport});
/// The sport being recorded.
final RunSport sport;
final List<RunPoint> _points = [];
int _jumps = 0;
@ -121,14 +121,15 @@ class GpsFilter {
fix.latitude,
fix.longitude,
);
if (step / gap > kRunningMaxSpeedMps) {
if (step / gap > maxSpeedMps(sport)) {
_jumps++;
if (_jumps < kMaxConsecutiveJumps) return FixVerdict.tooFast;
// The anchor, not the fixes, was wrong: continue from here, no credit.
_accept(fix, time, 0);
return FixVerdict.accepted;
}
final moving = step / gap >= minStepSpeed(gap);
final moving =
gap <= kMaxCreditGapSeconds && step / gap >= kMinMovingSpeedMps;
_accept(fix, time, moving ? step : 0);
return FixVerdict.accepted;
}

View File

@ -1,98 +0,0 @@
/// Where the user is before a run starts: display-only fixes for the map.
///
/// These fixes never touch the recorder, the filter or the track -- they only
/// move the idle map's camera and position marker. The watch ends when the run
/// starts (one location stream at a time), and the recorder's own accepted
/// points take over from there.
library;
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:latlong2/latlong.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
/// Watches the position while idle and reports the access it found.
class IdleLocation {
/// Creates a watcher over [_source]; [onAccess] hears every access check.
IdleLocation(this._source, {required this.onAccess});
final PositionSource _source;
/// Told the access after each [open] and [recheck].
final void Function(LocationAccess access) onAccess;
/// The latest fix, or null before the first one (or once access is lost).
final position = ValueNotifier<LatLng?>(null);
/// The last access found, or null before the first check resolves.
LocationAccess? access;
StreamSubscription<GpsFix>? _sub;
bool _closed = false;
/// Asks for access (this may show the system prompt) and, once granted,
/// starts watching.
Future<void> open() async {
_closed = false;
await _apply(await _source.requestAccess());
}
/// Re-reads the access without prompting (the app came back to the
/// foreground); a grant starts the watch, a revocation ends it.
Future<void> recheck() async {
if (_closed) return;
await _apply(await _source.checkAccess());
}
/// Lets [recheck] work again after [stop], without watching yet: for a start
/// that was refused, so coming back from settings can recover the screen.
void reopen() => _closed = false;
/// Ends the watch (a run took over, or the screen is going away).
Future<void> stop() async {
_closed = true;
await _unwatch();
}
Future<void> _apply(LocationAccess found) async {
if (_closed) return;
access = found;
onAccess(found);
if (found.isGranted) {
if (_sub != null) return;
_sub = _source.fixes().listen(_onFix, onError: _onError);
return;
}
position.value = null;
await _unwatch();
}
Future<void> _unwatch() async {
final cancelling = _sub?.cancel();
_sub = null;
await cancelling;
}
void _onFix(GpsFix fix) {
position.value = LatLng(fix.latitude, fix.longitude);
}
void _onError(Object error, StackTrace stack) {
log(
'IdleLocation: the location stream failed ($error) -- the idle map '
'keeps the last known position until fixes resume.',
level: 1000,
error: error,
stackTrace: stack,
);
}
/// Stops watching and releases the position notifier.
Future<void> dispose() async {
await stop();
position.dispose();
}
}

View File

@ -1,114 +0,0 @@
/// The optional pace target: current pace, the band around the target and the
/// cue throttle. Pure Dart, no clock of its own -- everything runs on fix time,
/// so it is deterministic in tests and right at the sandbox's replay speed.
library;
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/run_math.dart';
/// The trailing window, in seconds of fix time, the current pace is read over.
const int kPaceWindowSeconds = 30;
/// The window must span at least this long before a pace is reported: the
/// first fixes of a run (or after a resume) say nothing yet.
const int kPaceWarmupSeconds = 20;
/// Half-width of the band around the target, in seconds per kilometre.
const int kPaceToleranceSeconds = 10;
/// The least time between two cues, in seconds of fix time.
const int kPaceCueGapSeconds = 30;
/// Fastest target, 3:00 per kilometre.
const int kMinPaceTarget = 180;
/// Slowest target, 12:00 per kilometre.
const int kMaxPaceTarget = 720;
/// The picker's step, in seconds per kilometre.
const int kPaceStep = 5;
/// [seconds] rounded to a [kPaceStep] and held inside the target range.
int clampPaceTarget(int seconds) => ((seconds / kPaceStep).round() * kPaceStep)
.clamp(kMinPaceTarget, kMaxPaceTarget);
/// Pace in seconds per kilometre over the last [kPaceWindowSeconds] of
/// [points], reading only from index [from] on (the first point after a
/// resume, so the time spent paused never counts as slow running).
///
/// Null while the window spans under [kPaceWarmupSeconds], and null when it
/// moved slower than [kMinMovingSpeedMps]: standing still is not a pace, so it
/// earns neither a colour nor a cue (the pause button is for that).
double? currentPaceSeconds(List<RunPoint> points, {int from = 0}) {
if (points.length - from < 2) return null;
final last = points.last;
var oldest = points.length - 1;
while (oldest > from &&
last.time.difference(points[oldest - 1].time).inSeconds <=
kPaceWindowSeconds) {
oldest--;
}
final span = last.time.difference(points[oldest].time).inMilliseconds / 1000;
if (span < kPaceWarmupSeconds) return null;
final metres = last.distanceM - points[oldest].distanceM;
if (metres / span < kMinMovingSpeedMps) return null;
return span / (metres / 1000);
}
/// Where the current pace stands against the target.
enum PaceBand {
/// Within the tolerance, ends included.
onPace,
/// Slower than the band (more seconds per kilometre).
tooSlow,
/// Faster than the band (fewer seconds per kilometre).
tooFast,
}
/// The band [current] falls in around [target], or null with no pace yet.
PaceBand? paceBandOf({required double? current, required int target}) {
if (current == null) return null;
final off = current - target;
if (off > kPaceToleranceSeconds) return PaceBand.tooSlow;
if (off < -kPaceToleranceSeconds) return PaceBand.tooFast;
return PaceBand.onPace;
}
/// What the runner is told when off pace.
enum PaceCue {
/// Speed up.
tooSlow,
/// Ease off.
tooFast,
}
/// Lets a cue through at most once per [kPaceCueGapSeconds] of fix time.
///
/// On pace it is silent. Coming back into the band does not reset the gap, so
/// drifting in and out cannot nag; and a slow-to-fast flip inside the gap is
/// held back too.
class PaceCueThrottle {
DateTime? _last;
/// The cue for [band] at fix time [at], or null when silent or throttled.
PaceCue? cueFor(PaceBand? band, DateTime at) {
final cue = switch (band) {
PaceBand.tooSlow => PaceCue.tooSlow,
PaceBand.tooFast => PaceCue.tooFast,
PaceBand.onPace || null => null,
};
if (cue == null) return null;
final last = _last;
if (last != null && at.difference(last).inSeconds < kPaceCueGapSeconds) {
return null;
}
_last = at;
return cue;
}
/// Forgets the last cue, so the next off-pace fix speaks at once.
void reset() => _last = null;
}

View File

@ -1,48 +0,0 @@
/// The pace target's running state: current pace, band and throttled cues.
library;
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/pace_band.dart';
/// Tracks the current pace as accepted points arrive and fires [onCue] when
/// the runner is off the target (see [PaceCueThrottle]).
class PaceCoach {
/// Creates a coach with no target; [onCue] hears each cue that passes.
PaceCoach({this.onCue});
/// Called with the cue to give.
final void Function(PaceCue cue)? onCue;
final _throttle = PaceCueThrottle();
int _from = 0;
/// The target in seconds per kilometre, or null when off.
int? target;
/// Pace over the last 30 s of accepted fixes, once warmed up.
double? pace;
/// Where [pace] stands against [target]; null with no target or no pace.
PaceBand? get band =>
target == null ? null : paceBandOf(current: pace, target: target!);
/// Sets the target (null turns it off); the next off-pace fix cues at once.
void setTarget(int? seconds) {
target = seconds;
_throttle.reset();
}
/// Starts a fresh window at [index] (the first point after a resume), so
/// the time spent paused never reads as slow running.
void restartAt(int index) {
_from = index;
pace = null;
}
/// Folds in the newest of [points] (accepted, oldest first).
void update(List<RunPoint> points) {
pace = currentPaceSeconds(points, from: _from);
final cue = _throttle.cueFor(band, points.last.time);
if (cue != null) onCue?.call(cue);
}
}

View File

@ -1,51 +0,0 @@
/// Where the last pace target is kept between runs (shared_preferences).
library;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:workout_app/services/pace_band.dart';
/// The preferences key of the last pace target, in seconds per kilometre.
const String kPaceTargetKey = 'run_pace_target_v1';
/// The target the picker starts at when none was ever chosen, 6:00.
const int kDefaultPaceTarget = 360;
/// Reads and writes the last target; an interface so screen tests need no
/// platform channel.
abstract class PaceTargetStore {
/// The stored target, or [kDefaultPaceTarget].
Future<int> load();
/// Stores [seconds] as the last target.
Future<void> save(int seconds);
}
/// The real store, over `SharedPreferencesAsync` (resolved on first use, so
/// merely owning one costs nothing on the test host).
class PrefsPaceTargetStore implements PaceTargetStore {
/// Creates a store over [prefs], defaulting to a fresh async instance.
PrefsPaceTargetStore([SharedPreferencesAsync? prefs]) : _prefs = prefs;
SharedPreferencesAsync? _prefs;
SharedPreferencesAsync get _resolved => _prefs ??= SharedPreferencesAsync();
@override
Future<int> load() async {
final stored = await _resolved.getInt(kPaceTargetKey);
return clampPaceTarget(stored ?? kDefaultPaceTarget);
}
@override
Future<void> save(int seconds) => _resolved.setInt(kPaceTargetKey, seconds);
/// The target as stored, or null when none was ever chosen (the "off"
/// state the /sdcard backup carries).
Future<int?> stored() => _resolved.getInt(kPaceTargetKey);
/// Puts a backed-up target back; null means none chosen, so a leftover
/// value is removed rather than kept.
Future<void> restore(int? seconds) => seconds == null
? _resolved.remove(kPaceTargetKey)
: save(clampPaceTarget(seconds));
}

View File

@ -27,19 +27,12 @@ enum LocationAccess {
/// A stream of GPS fixes plus the permission handshake that guards it.
abstract class PositionSource {
/// Asks for location permission (this may show the system prompt); never
/// throws for a refusal.
/// Asks for (or re-checks) location permission; never throws for a refusal.
Future<LocationAccess> requestAccess();
/// Reads the access as it stands, without ever prompting. For re-checks
/// when the app comes back to the foreground: the permission dialog itself
/// backgrounds the app, so re-asking there would loop.
Future<LocationAccess> checkAccess();
/// Fixes roughly every [interval], best accuracy, until cancelled.
///
/// [interval] must stay well under the PC's 30 s credit gap
/// (`kMaxCreditGapSeconds`): a quieter stream is treated as a dropout and
/// only counts at 1 m/s or faster.
/// (`kMaxCreditGapSeconds`): a quieter stream earns nothing.
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)});
}

View File

@ -25,26 +25,15 @@ class GeolocatorPositionSource implements PositionSource {
if (permission == LocationPermission.denied) {
permission = await _platform.requestPermission();
}
return _access(permission);
return switch (permission) {
LocationPermission.always ||
LocationPermission.whileInUse => LocationAccess.granted,
LocationPermission.deniedForever => LocationAccess.deniedForever,
LocationPermission.denied ||
LocationPermission.unableToDetermine => LocationAccess.denied,
};
}
@override
Future<LocationAccess> checkAccess() async {
if (!await _platform.isLocationServiceEnabled()) {
return LocationAccess.serviceOff;
}
return _access(await _platform.checkPermission());
}
static LocationAccess _access(LocationPermission permission) =>
switch (permission) {
LocationPermission.always ||
LocationPermission.whileInUse => LocationAccess.granted,
LocationPermission.deniedForever => LocationAccess.deniedForever,
LocationPermission.denied ||
LocationPermission.unableToDetermine => LocationAccess.denied,
};
@override
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) =>
_platform

View File

@ -31,9 +31,6 @@ class ScriptedPositionSource implements PositionSource {
@override
Future<LocationAccess> requestAccess() async => access;
@override
Future<LocationAccess> checkAccess() async => access;
@override
Stream<GpsFix> fixes({
Duration interval = const Duration(seconds: 2),

View File

@ -6,13 +6,10 @@ import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:latlong2/latlong.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/idle_location.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_notification.dart';
import 'package:workout_app/services/run_recorder.dart';
@ -25,28 +22,19 @@ import 'package:workout_app/services/run_saver.dart';
/// the permission), then the first fix.
class RunController extends ChangeNotifier {
/// Creates a controller; it builds its own [recorder] over [sourceFor].
///
/// [idleSourceFor] feeds the idle map before the run (display only); it
/// defaults to [sourceFor].
RunController({
required PositionSource Function() sourceFor,
required PositionSource Function(RunSport sport) sourceFor,
required this._service,
required this._cues,
required this._save,
PositionSource Function()? idleSourceFor,
}) {
recorder = RunRecorder(
sourceFor: sourceFor,
onKilometre: _onKilometre,
onPaceCue: _onPaceCue,
)..addListener(_onRecorderChanged);
_idle = IdleLocation((idleSourceFor ?? sourceFor)(), onAccess: _onAccess);
recorder = RunRecorder(sourceFor: sourceFor, onKilometre: _onKilometre)
..addListener(_onRecorderChanged);
}
/// The state machine; the live map reads its points.
late final RunRecorder recorder;
late final IdleLocation _idle;
final ForegroundRunClient _service;
final FeedbackCues _cues;
final Future<RunSaveResult> Function(RunTrack track) _save;
@ -68,32 +56,10 @@ class RunController extends ChangeNotifier {
/// True from start to finish: the screen must not be left meanwhile.
bool get active => recorder.phase.isActive;
/// Where the user is before the run starts (display only, never recorded).
ValueListenable<LatLng?> get position => _idle.position;
/// True while location is refused and the run has not started: the screen
/// shows only the problem icon, no map and no start.
bool get blocked =>
recorder.phase == RunPhase.idle && recorder.issue.isAccess;
/// Whether access has been found granted, so a start cannot race a prompt.
bool get canStart => _idle.access?.isGranted ?? false;
/// Asks for location (this may show the prompt) and starts watching the
/// position for the idle map. Also the retry after a refusal.
Future<void> watchIdle() => _idle.open();
/// Re-reads the access silently (the app came back to the foreground).
Future<void> recheckAccess() =>
recorder.phase == RunPhase.idle ? _idle.recheck() : Future.value();
/// Asks for access, starts the service, begins recording.
Future<void> start() async {
await _idle.stop();
await _cues.load();
final started = await recorder.start(afterAccess: _startService);
// A refused start leaves the screen blocked; let a resume recheck it.
if (!started && recorder.issue.isAccess) _idle.reopen();
await recorder.start(afterAccess: _startService);
}
/// Pauses crediting.
@ -170,20 +136,11 @@ class RunController extends ChangeNotifier {
void _onKilometre(int km) => unawaited(_cues.kilometreReached(km));
void _onPaceCue(PaceCue cue) => unawaited(_cues.paceOff(cue));
void _onAccess(LocationAccess access) {
recorder.noteAccess(access);
// canStart follows the access, which the recorder does not report.
notifyListeners();
}
void _onRecorderChanged() {
if (_serviceState == RunServiceState.running) {
final copy = runNotificationCopy(
metres: recorder.distanceM,
movingSeconds: recorder.seconds,
currentPace: recorder.coach.target == null ? null : recorder.coach.pace,
);
// Only when the words changed: an update per fix would redraw twice a
// second for nothing.
@ -197,7 +154,6 @@ class RunController extends ChangeNotifier {
@override
void dispose() {
unawaited(_idle.dispose());
recorder
..removeListener(_onRecorderChanged)
..dispose();

View File

@ -22,12 +22,10 @@ String formatDuration(int seconds) {
/// covered (the quotient is meaningless, and 0 would divide by zero).
String formatPace({required int seconds, required double distanceM}) {
if (distanceM < 10) return '-:--';
return formatPaceSeconds((seconds / (distanceM / 1000)).round());
final perKm = (seconds / (distanceM / 1000)).round();
return '${perKm ~/ 60}:${_two(perKm % 60)}';
}
/// A pace of [perKm] seconds per kilometre as `m:ss`.
String formatPaceSeconds(int perKm) => '${perKm ~/ 60}:${_two(perKm % 60)}';
/// `dd.MM` of [when] in the device's local time.
String formatRunDay(DateTime when) {
final l = when.toLocal();

View File

@ -1,23 +1,4 @@
/// Distance and moving-time maths for recorded tracks (pure, no I/O).
///
/// The PC's one crediting rule (`screen_locker/_activity_day.py`, `_walk_tcx.py`),
/// for every GPS activity whatever its sport: a day's activities are summed and
/// count once the distance reaches 3.5 km (5 % tolerance) OR the moving time
/// reaches 25 min. Only the PC decides that; the app has no "qualifies" test.
///
/// The PC judges speed over windows of at least 10 s (`TRACK_WINDOW_SECONDS`).
/// A window faster than 25 km/h earns neither distance nor time; a window of
/// 30 s or less earns moving time at 0.5 m/s or faster; a longer one (a GPS
/// dropout) at 1 m/s or faster; paused time earns nothing.
///
/// The app mirrors those bounds per pair of its 2 s fixes, and bridges a
/// dropout the way a RunnerUp export does: the straight-line distance across a
/// gap over 30 s that the runner did not pause is credited when it implies
/// 1 m/s to 25 km/h (`GpsFilter`); a user pause credits nothing. The
/// on-screen distance, the saved run and the TCX `DistanceMeters` all come from
/// that one cumulative figure. The only remaining difference is that the PC
/// judges 10 s windows rather than single pairs, so its moving time can differ
/// slightly on a jittery or stop-and-go stretch.
library;
import 'dart:math' as math;
@ -27,30 +8,32 @@ import 'package:workout_app/models/run_track.dart';
/// Mean Earth radius in metres (IUGG), the haversine constant.
const double kEarthRadiusM = 6371008.8;
/// A pair of fixes further apart in time than this is a GPS dropout whose
/// motion is unknown: it counts only at [kMinDropoutSpeedMps] or faster.
/// A pair of fixes further apart in time than this earns neither distance
/// nor moving time: a GPS dropout whose motion is unknown.
///
/// Mirrors `WALK_MAX_GAP_SECONDS` in the PC's `screen_locker/_constants.py`.
/// This is a mirror of the rule the PC applies to a walk's trackpoints, so the
/// app never reports moving time the PC would discard -- it is NOT a crediting
/// threshold (those stay on the PC).
const int kMaxCreditGapSeconds = 30;
/// A pair slower than this is standing still, not moving.
///
/// Mirrors `MIN_MOVING_SPEED_MPS` on the PC.
/// Mirrors the lower bound of `WALK_SPEED_MPS` on the PC.
const double kMinMovingSpeedMps = 0.5;
/// A dropout (a gap over [kMaxCreditGapSeconds]) counts only when the straight
/// line across it implies at least this speed; slower is standing or a pause.
///
/// Mirrors `MIN_DROPOUT_SPEED_MPS` on the PC.
const double kMinDropoutSpeedMps = 1;
/// Speed cap above which a fix is a GPS jump, 25 km/h.
///
/// Mirrors `MAX_MOVING_SPEED_MPS` on the PC, which applies it to each window
/// of 10 s or more rather than to each fix. One cap for every recording: the
/// PC credits every GPS activity with the same rule.
/// Speed cap above which a fix is a GPS jump, 25 km/h for a run.
const double kRunningMaxSpeedMps = 25 / 3.6;
/// Speed cap above which a fix is a GPS jump, 8 km/h for a walk.
const double kWalkingMaxSpeedMps = 8 / 3.6;
/// The jump cap for [sport].
double maxSpeedMps(RunSport sport) => switch (sport) {
RunSport.running => kRunningMaxSpeedMps,
RunSport.walking => kWalkingMaxSpeedMps,
};
double _rad(double degrees) => degrees * math.pi / 180;
/// Great-circle distance in metres between two WGS-84 positions.
@ -65,30 +48,25 @@ double haversineM(double lat1, double lon1, double lat2, double lon2) {
return 2 * kEarthRadiusM * math.asin(math.min(1, math.sqrt(a)));
}
/// The slowest speed that counts as moving across a [gapSeconds] step.
double minStepSpeed(num gapSeconds) => gapSeconds > kMaxCreditGapSeconds
? kMinDropoutSpeedMps
: kMinMovingSpeedMps;
/// Whether the step from [a] to [b] counts as moving: travelled at a speed in
/// `[kMinMovingSpeedMps, maxSpeed]`, or in `[kMinDropoutSpeedMps, maxSpeed]`
/// when the fixes are further apart than [kMaxCreditGapSeconds] (a dropout).
/// Whether the step from [a] to [b] counts as moving: seen within
/// [kMaxCreditGapSeconds] and travelled at a speed in
/// `[kMinMovingSpeedMps, maxSpeed]`.
///
/// Speed comes from the cumulative `distanceM` difference, as the PC reads a
/// TCX, but over one pair of fixes rather than a window of 10 s or more, so the
/// two can disagree on a jittery or stop-and-go stretch.
/// Speed comes from the cumulative `distanceM` difference, exactly as the PC
/// reads a TCX, so app and PC agree on which steps count.
bool isMovingStep(RunPoint a, RunPoint b, double maxSpeed) {
final gap = b.time.difference(a.time).inMilliseconds / 1000;
if (gap <= 0) return false;
if (gap <= 0 || gap > kMaxCreditGapSeconds) return false;
final speed = (b.distanceM - a.distanceM) / gap;
return speed >= minStepSpeed(gap) && speed <= maxSpeed;
return speed >= kMinMovingSpeedMps && speed <= maxSpeed;
}
/// Moving seconds over [points]: the summed gaps of every moving step.
int movingSeconds(List<RunPoint> points) {
int movingSeconds(List<RunPoint> points, RunSport sport) {
final cap = maxSpeedMps(sport);
var total = 0.0;
for (var i = 1; i < points.length; i++) {
if (isMovingStep(points[i - 1], points[i], kRunningMaxSpeedMps)) {
if (isMovingStep(points[i - 1], points[i], cap)) {
total += points[i].time.difference(points[i - 1].time).inSeconds;
}
}

View File

@ -1,23 +1,15 @@
/// The two lines of the ongoing run notification (numbers only, textgate).
library;
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/run_format.dart';
/// Distance as the title; moving time and average pace as the body, plus the
/// current pace (to the nearest [kPaceStep], so GPS jitter does not redraw it
/// every fix) when a pace target is on.
/// Distance as the title; moving time and average pace as the body.
({String title, String body}) runNotificationCopy({
required double metres,
required int movingSeconds,
double? currentPace,
}) {
final average = formatPace(seconds: movingSeconds, distanceM: metres);
final current = currentPace == null
? ''
: ' ${formatPaceSeconds((currentPace / kPaceStep).round() * kPaceStep)}';
return (
title: formatDistanceKm(metres),
body: '${formatDuration(movingSeconds)} $average$current',
);
}
}) => (
title: formatDistanceKm(metres),
body:
'${formatDuration(movingSeconds)} '
'${formatPace(seconds: movingSeconds, distanceM: metres)}',
);

View File

@ -1,11 +1,9 @@
/// The phases and problems of a GPS recording.
library;
import 'package:workout_app/services/position_source.dart';
/// Where a recording stands.
enum RunPhase {
/// Nothing recorded yet.
/// Nothing recorded yet; the sport can still be chosen.
idle,
/// Fixes are being kept and credited.
@ -42,16 +40,5 @@ enum RunIssue {
streamError,
/// Finished with too few usable fixes to make a track; nothing was saved.
tooShort;
/// The issue a refused [access] raises (never [none]; a grant has none).
static RunIssue forAccess(LocationAccess access) => switch (access) {
LocationAccess.deniedForever => deniedForever,
LocationAccess.serviceOff => serviceOff,
_ => denied,
};
/// Whether this is a refused location access (no map, no start).
bool get isAccess =>
this == denied || this == deniedForever || this == serviceOff;
tooShort,
}

View File

@ -1,4 +1,4 @@
/// The GPS activity state machine: idle, recording, paused, finished.
/// The GPS run/walk state machine: idle, recording, paused, finished.
library;
import 'dart:async';
@ -8,40 +8,30 @@ import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/pace_coach.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_math.dart';
import 'package:workout_app/services/run_phase.dart';
export 'package:workout_app/services/run_phase.dart';
/// Records one GPS activity from a [PositionSource].
///
/// Every activity is a run (one jump cap, one `Sport="Running"` TCX): the PC
/// credits every GPS activity with the same rule.
/// Records one run or walk from a [PositionSource].
///
/// A pause ignores fixes and breaks the filter's segment, so the stretch
/// walked while paused and the first fix after it credit nothing. Moving time
/// is [movingSeconds] applied as fixes arrive: an estimate that mirrors the
/// PC's bounds per pair of fixes, not its 10 s windows (see `run_math.dart`).
/// is the PC's rule ([movingSeconds]) applied as fixes arrive, so the number
/// on screen is the number the PC will credit.
class RunRecorder extends ChangeNotifier {
/// Creates a recorder; [sourceFor] builds the fix stream on [start].
RunRecorder({
required this.sourceFor,
this.onKilometre,
void Function(PaceCue cue)? onPaceCue,
}) : coach = PaceCoach(onCue: onPaceCue);
/// Creates a recorder; [sourceFor] builds the fix stream for the chosen
/// sport when [start] is called (the sandbox's replay speed follows it).
RunRecorder({required this.sourceFor, this.onKilometre});
/// Builds the source for one recording.
final PositionSource Function() sourceFor;
final PositionSource Function(RunSport sport) sourceFor;
/// Called with 1, 2, 3 ... as each whole kilometre is credited.
final void Function(int km)? onKilometre;
/// The pace target's state: current pace, band and cues.
final PaceCoach coach;
RunSport _sport = RunSport.running;
RunPhase _phase = RunPhase.idle;
RunIssue _issue = RunIssue.none;
GpsFilter? _filter;
@ -52,6 +42,9 @@ class RunRecorder extends ChangeNotifier {
final _live = ValueNotifier<List<RunPoint>>(const []);
final _seenVerdicts = <FixVerdict>{};
/// Running or walking.
RunSport get sport => _sport;
/// The state machine's phase.
RunPhase get phase => _phase;
@ -67,20 +60,12 @@ class RunRecorder extends ChangeNotifier {
/// Credited distance in metres.
double get distanceM => _filter?.distanceM ?? 0;
/// Sets the pace target ([seconds] per kilometre), or off with null.
void setPaceTarget(int? seconds) {
coach.setTarget(seconds);
notifyListeners();
}
/// Folds an access check in while idle: a refusal becomes the issue, a
/// grant clears it.
void noteAccess(LocationAccess access) {
if (_phase != RunPhase.idle) return;
if (!access.isGranted) return _refuse(access);
if (!_issue.isAccess) return;
_issue = RunIssue.none;
/// Picks the sport; only possible while [RunPhase.idle].
bool selectSport(RunSport sport) {
if (_phase != RunPhase.idle) return false;
_sport = sport;
notifyListeners();
return true;
}
/// Asks for location access, runs [afterAccess] (where the caller starts the
@ -91,20 +76,20 @@ class RunRecorder extends ChangeNotifier {
if (_phase != RunPhase.idle || _starting) return false;
_starting = true;
try {
final source = sourceFor();
final source = sourceFor(_sport);
final access = await source.requestAccess();
if (!access.isGranted) {
_refuse(access);
return false;
}
await afterAccess?.call();
_filter = GpsFilter();
_filter = GpsFilter(sport: _sport);
_sub = source
.fixes() // the source's default 2 s, far under kMaxCreditGapSeconds
.listen(_onFix, onError: _onError, onDone: _onDone);
_issue = RunIssue.none;
_phase = RunPhase.recording;
SandboxLog.event('run started');
SandboxLog.event('run started', {'sport': _sport.tcxName});
notifyListeners();
return true;
} finally {
@ -117,7 +102,7 @@ class RunRecorder extends ChangeNotifier {
if (_phase != RunPhase.recording) return;
_filter!.breakSegment();
_phase = RunPhase.paused;
SandboxLog.event('run paused', {'m': distanceM});
SandboxLog.event('run paused', {'km': distanceM});
notifyListeners();
}
@ -125,8 +110,7 @@ class RunRecorder extends ChangeNotifier {
void resume() {
if (_phase != RunPhase.paused) return;
_phase = RunPhase.recording;
coach.restartAt(_filter!.points.length);
SandboxLog.event('run resumed', {'m': distanceM});
SandboxLog.event('run resumed', {'km': distanceM});
notifyListeners();
}
@ -138,7 +122,7 @@ class RunRecorder extends ChangeNotifier {
_sub = null;
_phase = RunPhase.finished;
final points = _filter!.points;
_moving = movingSeconds(points);
_moving = movingSeconds(points, _sport);
RunTrack? track;
if (points.length < 2) {
_issue = RunIssue.tooShort;
@ -149,7 +133,7 @@ class RunRecorder extends ChangeNotifier {
);
} else {
track = RunTrack.started(
sport: RunSport.running,
sport: _sport,
startedAt: points.first.time,
points: points,
totalSeconds: _moving,
@ -157,7 +141,7 @@ class RunRecorder extends ChangeNotifier {
);
}
SandboxLog.event('run finished', {
'm': distanceM,
'km': distanceM,
'secs': _moving,
'points': points.length,
'saved': track != null,
@ -167,7 +151,11 @@ class RunRecorder extends ChangeNotifier {
}
void _refuse(LocationAccess access) {
_issue = RunIssue.forAccess(access);
_issue = switch (access) {
LocationAccess.deniedForever => RunIssue.deniedForever,
LocationAccess.serviceOff => RunIssue.serviceOff,
_ => RunIssue.denied,
};
final fix = access == LocationAccess.serviceOff
? 'Switch location on'
: 'Grant location to the app in system settings';
@ -190,11 +178,10 @@ class RunRecorder extends ChangeNotifier {
final points = _filter!.points;
final n = points.length;
if (n >= 2 &&
isMovingStep(points[n - 2], points[n - 1], kRunningMaxSpeedMps)) {
isMovingStep(points[n - 2], points[n - 1], maxSpeedMps(_sport))) {
_moving += points[n - 1].time.difference(points[n - 2].time).inSeconds;
}
_live.value = points;
coach.update(points);
while (distanceM ~/ 1000 > _km) {
_km++;
SandboxLog.event('run km', {'km': _km, 'secs': _moving});
@ -236,7 +223,7 @@ class RunRecorder extends ChangeNotifier {
'finish the run to save what was captured.',
level: 900,
);
SandboxLog.event('run stream ended', {'m': distanceM});
SandboxLog.event('run stream ended', {'km': distanceM});
}
@override

View File

@ -19,7 +19,6 @@ import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/manual_workout_port.dart';
import 'package:workout_app/services/pace_target_store.dart';
import 'package:workout_app/services/progression_sync_service.dart';
// Re-exported: ExerciseState was defined here until it moved to models/, and

View File

@ -51,45 +51,9 @@ extension StorageServiceBackup on StorageService {
'settings': settingsRows,
'progression_events': eventRows,
'runs': runRows,
...await _paceTargetForBackup(),
});
}
/// The pace target for the backup: `pace_target` is seconds per kilometre,
/// or null when none was ever chosen (off). Lives in shared_preferences, not
/// the DB, so it is added by hand. An unreadable store leaves the field out
/// (a restore then reads "off") and says so.
Future<Map<String, Object?>> _paceTargetForBackup() async {
try {
return {'pace_target': await PrefsPaceTargetStore().stored()};
} on Object catch (error) {
debugPrint(
'WorkoutApp: pace target NOT in this backup -- could not read it '
'($error). A restore will bring the pace target back as off.',
);
return const {};
}
}
/// Puts the backup's `pace_target` back. Absent (an older backup), null or
/// unusable all mean off, so a restore never keeps a stale target.
Future<void> _restorePaceTarget(Object? raw) async {
if (raw != null && raw is! int) {
debugPrint(
'WorkoutApp: backup pace_target is not a number ($raw) -- restoring '
'the pace target as off.',
);
}
try {
await PrefsPaceTargetStore().restore(raw is int ? raw : null);
} on Object catch (error) {
debugPrint(
'WorkoutApp: pace target NOT restored -- could not write it ($error). '
'It stays as it was; pick the target again on the run screen.',
);
}
}
/// Whether this database has never recorded a workout on this install.
///
/// "Empty" means no workout history and no [last_workout_type] setting —
@ -220,6 +184,5 @@ extension StorageServiceBackup on StorageService {
// Absent from older backups; null merges as nothing.
await _mergeRuns(txn, backup['runs']);
});
await _restorePaceTarget(backup['pace_target']);
}
}

View File

@ -8,13 +8,9 @@
/// screen. Pass a `ValueListenable<List<RunPoint>>` (the recorder's
/// accepted points, oldest first); the route
/// redraws on every change and, in follow mode (the default), the camera
/// keeps the last point centred. With no points yet, an optional
/// `positionListenable` (where the user is right now) stands in: the map
/// centres on it, draws a position marker, and the recentre button jumps to
/// it. Once the run has points they win. Dragging the map ends follow
/// mode; the recentre button (icon only) turns it back on. The listenables
/// must stay the same objects for the widget's lifetime (give it a new
/// `Key` to swap).
/// keeps the last point centred. Dragging the map ends follow mode; the
/// recentre button (icon only) turns it back on. The listenable must stay
/// the same object for the widget's lifetime (give it a new `Key` to swap).
///
/// Tiles are OSM raster tiles from tile.openstreetmap.org, cached on disk
/// (`map_tile_cache.dart`) so revisited areas draw offline. The OSM credit is
@ -52,13 +48,11 @@ class RunMap extends StatefulWidget {
super.key,
this.fitPadding = const EdgeInsets.all(40),
this.tileProviderOpener = openOsmTileProvider,
}) : pointsListenable = null,
positionListenable = null;
}) : pointsListenable = null;
/// A live run: follows the last point in [pointsListenable].
const RunMap.live({
required ValueListenable<List<RunPoint>> this.pointsListenable,
this.positionListenable,
super.key,
this.tileProviderOpener = openOsmTileProvider,
}) : points = null,
@ -70,9 +64,6 @@ class RunMap extends StatefulWidget {
/// The accepted points in live mode; null in detail mode.
final ValueListenable<List<RunPoint>>? pointsListenable;
/// Where the user is before the first run point; null in detail mode.
final ValueListenable<LatLng?>? positionListenable;
/// Space kept free around the fitted route (detail mode).
final EdgeInsets fitPadding;
@ -92,21 +83,14 @@ class _RunMapState extends State<RunMap> {
bool get _live => widget.pointsListenable != null;
List<RunPoint> get _points =>
_live ? widget.pointsListenable!.value : widget.points!;
/// What the camera follows: the last run point, else the current position.
LatLng? get _target {
final points = _points;
if (points.isEmpty) return widget.positionListenable?.value;
return LatLng(points.last.latitude, points.last.longitude);
}
List<RunPoint> get _points => _live
? widget.pointsListenable!.value
: widget.points!;
@override
void initState() {
super.initState();
widget.pointsListenable?.addListener(_followLast);
widget.positionListenable?.addListener(_followLast);
unawaited(
widget.tileProviderOpener().then((p) {
if (mounted) setState(() => _tiles = p);
@ -117,16 +101,15 @@ class _RunMapState extends State<RunMap> {
@override
void dispose() {
widget.pointsListenable?.removeListener(_followLast);
widget.positionListenable?.removeListener(_followLast);
_controller.dispose();
super.dispose();
}
void _followLast() {
final target = _target;
if (!_ready || !_follow || target == null) return;
final coords = toLatLngs(_points);
if (!_ready || !_follow || coords.isEmpty) return;
final zoom = _controller.camera.zoom;
_controller.move(target, zoom < 12 ? _closeZoom : zoom);
_controller.move(coords.last, zoom < 12 ? _closeZoom : zoom);
}
void _warnOnce(Object error) {
@ -138,7 +121,7 @@ class _RunMapState extends State<RunMap> {
);
}
MapOptions _options(List<LatLng> coords, ColorScheme scheme, LatLng? here) {
MapOptions _options(List<LatLng> coords, ColorScheme scheme) {
final fit = !_live && coords.length > 1
? CameraFit.coordinates(
coordinates: coords,
@ -147,8 +130,8 @@ class _RunMapState extends State<RunMap> {
)
: null;
return MapOptions(
initialCenter: coords.isEmpty ? here ?? _fallbackCenter : coords.last,
initialZoom: coords.isEmpty && here == null ? _fallbackZoom : _closeZoom,
initialCenter: coords.isEmpty ? _fallbackCenter : coords.last,
initialZoom: coords.isEmpty ? _fallbackZoom : _closeZoom,
initialCameraFit: fit,
backgroundColor: scheme.surfaceContainerHigh,
onMapReady: () {
@ -164,10 +147,9 @@ class _RunMapState extends State<RunMap> {
Widget _map(BuildContext context, List<RunPoint> points) {
final scheme = Theme.of(context).colorScheme;
final coords = toLatLngs(points);
final here = widget.positionListenable?.value;
return FlutterMap(
mapController: _controller,
options: _options(coords, scheme, here),
options: _options(coords, scheme),
children: [
if (_tiles != null)
TileLayer(
@ -177,7 +159,6 @@ class _RunMapState extends State<RunMap> {
errorTileCallback: (tile, error, stack) => _warnOnce(error),
),
if (coords.length > 1) routeLayer(coords, scheme),
if (coords.isEmpty && here != null) positionLayer(here, scheme),
if (coords.isNotEmpty)
endpointLayer(
coords,
@ -197,9 +178,9 @@ class _RunMapState extends State<RunMap> {
return Stack(
fit: StackFit.expand,
children: [
ListenableBuilder(
listenable: Listenable.merge([listenable, widget.positionListenable]),
builder: (context, _) => _map(context, listenable.value),
ValueListenableBuilder<List<RunPoint>>(
valueListenable: listenable,
builder: (context, points, _) => _map(context, points),
),
if (!_follow)
Positioned(

View File

@ -38,11 +38,6 @@ Marker _dot(LatLng at, Color fill, IconData icon, Color ink) => Marker(
),
);
/// The user's own position before any run point exists: the accent dot.
MarkerLayer positionLayer(LatLng at, ColorScheme scheme) => MarkerLayer(
markers: [_dot(at, scheme.primary, Icons.navigation, scheme.surface)],
);
/// Start marker (green play), and either the live position (accent dot) or
/// the finish flag (red); no end marker for a one-point track.
MarkerLayer endpointLayer(

View File

@ -3,22 +3,19 @@ library;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:latlong2/latlong.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/map_tile_cache.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_map.dart';
/// The live map on the run screen: [RunMap.live] over the recorder's points
/// (and, before the first one, the user's current [position]), clipped to the
/// card shape.
/// The live map on the run screen: [RunMap.live] over the recorder's points,
/// clipped to the card shape.
///
/// `RunScreen` fills this space from `mapBuilder`, defaulting to this widget.
class RunMapSlot extends StatelessWidget {
/// Creates the slot; [points] updates with every accepted GPS fix.
const RunMapSlot({
required this.points,
this.position,
super.key,
this.tileProviderOpener = openOsmTileProvider,
});
@ -26,9 +23,6 @@ class RunMapSlot extends StatelessWidget {
/// The accepted points of the run so far, oldest first.
final ValueListenable<List<RunPoint>> points;
/// Where the user is now, shown until the run has points; null for none.
final ValueListenable<LatLng?>? position;
/// Where the map's tiles come from; tests pass a fake.
final TileProviderOpener tileProviderOpener;
@ -44,7 +38,6 @@ class RunMapSlot extends StatelessWidget {
clipBehavior: Clip.antiAlias,
child: RunMap.live(
pointsListenable: points,
positionListenable: position,
tileProviderOpener: tileProviderOpener,
),
);

View File

@ -1,161 +0,0 @@
/// The optional pace target before a run: a flag icon that switches it on,
/// and then `- m:ss +` in [kPaceStep] steps (holding a button repeats).
///
/// Icons and digits only (textgate). Deliberately not a wheel: a wheel is a
/// `Scrollable`, and the run screen must have nothing that scrolls (R7).
library;
import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/run_format.dart';
import 'package:workout_app/ui/theme.dart';
/// How often a held step button repeats once it has started.
const Duration kPaceRepeatEvery = Duration(milliseconds: 120);
/// The pace-target control shown beside the start button.
class RunPacePicker extends StatelessWidget {
/// Creates the control; [seconds] is the target in seconds per kilometre.
const RunPacePicker({
required this.on,
required this.seconds,
required this.onToggle,
required this.onChanged,
super.key,
});
/// Whether a target is set.
final bool on;
/// The target while [on].
final int seconds;
/// Called when the flag is tapped.
final VoidCallback onToggle;
/// Called with the new target for each step.
final ValueChanged<int> onChanged;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
key: const Key('run_pace_toggle'),
onPressed: onToggle,
color: on ? scheme.primary : scheme.onSurfaceVariant,
icon: Icon(
on ? Icons.flag : Icons.flag_outlined,
semanticLabel: 'pace target',
),
),
if (on) ...[
_StepButton(
id: 'run_pace_minus',
icon: Icons.remove,
onStep: seconds > kMinPaceTarget
? () => onChanged(seconds - kPaceStep)
: null,
),
Flexible(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xs),
// Scales down rather than overflow at large system text sizes.
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
formatPaceSeconds(seconds),
key: const Key('run_pace_value'),
style: const TextStyle(
fontSize: 28,
fontWeight: FontWeight.w600,
fontFeatures: [FontFeature.tabularFigures()],
),
),
),
),
),
_StepButton(
id: 'run_pace_plus',
icon: Icons.add,
onStep: seconds < kMaxPaceTarget
? () => onChanged(seconds + kPaceStep)
: null,
),
],
],
);
}
}
/// A step button: a tap steps once, holding steps on repeat. Null [onStep]
/// disables it (the end of the range), which also ends a hold.
class _StepButton extends StatefulWidget {
const _StepButton({required this.id, required this.icon, this.onStep});
final String id;
final IconData icon;
final VoidCallback? onStep;
@override
State<_StepButton> createState() => _StepButtonState();
}
class _StepButtonState extends State<_StepButton> {
Timer? _timer;
bool _held = false;
void _down() {
_held = false;
_timer = Timer(kLongPressTimeout, _startRepeating);
}
void _startRepeating() {
_held = true;
_step();
_timer = Timer.periodic(kPaceRepeatEvery, (_) => _step());
}
void _step() {
final onStep = widget.onStep;
if (onStep == null) return _release();
onStep();
}
void _release() {
_timer?.cancel();
_timer = null;
}
void _tap() {
// The release of a hold is not one more tap.
if (_held) {
_held = false;
return;
}
widget.onStep?.call();
}
@override
void dispose() {
_release();
super.dispose();
}
@override
Widget build(BuildContext context) => Listener(
onPointerDown: (_) => _down(),
onPointerUp: (_) => _release(),
onPointerCancel: (_) => _release(),
child: IconButton(
key: Key(widget.id),
onPressed: widget.onStep == null ? null : _tap,
icon: Icon(widget.icon, semanticLabel: widget.id),
),
);
}

View File

@ -91,8 +91,6 @@ flutter:
assets:
- assets/sounds/break_end.mp3
- assets/sounds/workout_done.wav
- assets/sounds/pace_slow.wav
- assets/sounds/pace_fast.wav
# Launcher icon generation. Source art is produced by the shared generator:
# PYTHONPATH=~/src/testsAndMisc python3 -m python_pkg.app_icons generate --app <key>

View File

@ -1,27 +0,0 @@
/// A geolocator platform that answers from fields, for tests that build the
/// real run controller (and so the real position source) without a device.
library;
import 'package:geolocator/geolocator.dart';
/// Location on, permission granted, no positions.
class FakeGeolocator extends GeolocatorPlatform {
/// Whether the device's location switch is on.
bool serviceOn = true;
/// The permission [checkPermission] reports.
LocationPermission permission = LocationPermission.whileInUse;
@override
Future<bool> isLocationServiceEnabled() async => serviceOn;
@override
Future<LocationPermission> checkPermission() async => permission;
@override
Future<LocationPermission> requestPermission() async => permission;
@override
Stream<Position> getPositionStream({LocationSettings? locationSettings}) =>
const Stream.empty();
}

View File

@ -4,7 +4,6 @@ library;
import 'package:audioplayers/audioplayers.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/pace_band.dart';
/// Stands in for `flutter_foreground_task` on the run screen's side.
class FakeForegroundRunClient implements ForegroundRunClient {
@ -86,15 +85,9 @@ class QuietCues extends FeedbackCues {
/// How many times the finish cue fired.
int finishes = 0;
/// Pace cues given, in order.
final paceCues = <PaceCue>[];
@override
Future<void> load() async {}
@override
Future<void> paceOff(PaceCue cue) async => paceCues.add(cue);
@override
Future<void> kilometreReached(int km) async => kilometres.add(km);

View File

@ -36,15 +36,8 @@ class ManualPositionSource implements PositionSource {
/// Creates a source answering [access].
ManualPositionSource({this.access = LocationAccess.granted});
/// What [requestAccess] and [checkAccess] answer; tests flip it to play a
/// grant in system settings.
LocationAccess access;
/// How many times the permission prompt path ran.
int requests = 0;
/// How many times the silent re-check ran.
int checks = 0;
/// What [requestAccess] answers.
final LocationAccess access;
/// The stream the recorder listens to.
final controller = StreamController<GpsFix>.broadcast();
@ -53,16 +46,7 @@ class ManualPositionSource implements PositionSource {
int subscriptions = 0;
@override
Future<LocationAccess> requestAccess() async {
requests++;
return access;
}
@override
Future<LocationAccess> checkAccess() async {
checks++;
return access;
}
Future<LocationAccess> requestAccess() async => access;
@override
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) {

View File

@ -9,8 +9,7 @@ void main() {
final printed = <String>[];
setUp(() {
printed.clear();
debugPrint = (String? message, {int? wrapWidth}) =>
printed.add(message ?? '');
debugPrint = (String? message, {int? wrapWidth}) => printed.add(message ?? '');
});
tearDown(() {
debugPrint = debugPrintThrottled;
@ -25,10 +24,7 @@ void main() {
() async => client.getUrl(Uri.parse('http://firebase.example.invalid/x')),
throwsA(isA<SocketException>()),
);
expect(
printed.single,
contains('refused network connection to firebase.example.invalid'),
);
expect(printed.single, contains('refused network connection to firebase.example.invalid'));
client.close(force: true);
});
@ -58,8 +54,9 @@ void main() {
SandboxHttpOverrides.pokeHost = host;
final client = SandboxHttpOverrides().createHttpClient(null);
await expectLater(
() async =>
client.postUrl(Uri.parse('https://$host:$kPcPokePort$kPcPokePath')),
() async => client.postUrl(
Uri.parse('https://$host:$kPcPokePort$kPcPokePath'),
),
throwsA(isA<SocketException>()),
);
expect(printed.single, contains('refused network connection to $host'));
@ -75,10 +72,7 @@ void main() {
),
throwsA(isA<SocketException>()),
);
expect(
printed.single,
contains('refused network connection to 10.0.0.9'),
);
expect(printed.single, contains('refused network connection to 10.0.0.9'));
client.close(force: true);
});
@ -98,98 +92,8 @@ void main() {
if (outcome is SocketException) {
expect(outcome.message, isNot(contains('sandbox')));
}
expect(
printed.first,
contains('allowing the PC poke to $host:$kPcPokePort'),
);
expect(printed.first, contains('allowing the PC poke to $host:$kPcPokePort'));
client.close(force: true);
});
});
group('the OSM tile exception', () {
Uri tile([
String path = '/17/70123/42650.png',
String host = 'tile.openstreetmap.org',
]) => Uri.parse('https://$host$path');
test('allows https tiles on the one host, zoom 0 to 19', () {
for (final path in [
'/0/0/0.png',
'/9/1/2.png',
'/17/70123/42650.png',
'/19/1/2.png',
]) {
expect(
SandboxHttpOverrides.allowsTile(tile(path)),
isTrue,
reason: path,
);
}
});
test('refuses everything else, including look-alike hosts', () {
for (final other in [
tile('/20/1/2.png'),
tile('/17/1/2.png?x=1'),
tile('/17/1/2.jpg'),
tile('/'),
tile('/api/0.6/map'),
tile('/17/1/2.png', 'a.tile.openstreetmap.org'),
tile('/17/1/2.png', 'openstreetmap.org'),
tile('/17/1/2.png', 'tile.openstreetmap.org.evil.example'),
tile('/17/1/2.png').replace(scheme: 'http', port: 80),
tile('/17/1/2.png').replace(port: 8443),
Uri.parse('https://kuhy-cloud.duckdns.org/x.json'),
]) {
expect(
SandboxHttpOverrides.allowsTile(other),
isFalse,
reason: '$other',
);
}
});
test('a tile reaches the socket layer, not the sandbox refusal', () async {
final client = SandboxHttpOverrides().createHttpClient(null);
Object outcome = 'connected';
try {
final request = await client.getUrl(tile());
request.abort();
} on SocketException catch (error) {
outcome = error;
}
if (outcome is SocketException) {
expect(outcome.message, isNot(contains('sandbox')));
}
expect(printed.first, contains('allowing OSM tile /17/70123/42650.png'));
client.close(force: true);
});
test('kuhy-cloud and a tile-looking path elsewhere stay refused', () async {
final client = SandboxHttpOverrides().createHttpClient(null);
for (final uri in [
Uri.parse('https://kuhy-cloud.duckdns.org/17/1/2.png'),
Uri.parse('https://kuhy-cloud.duckdns.org/x.json'),
]) {
await expectLater(
() => client.getUrl(uri),
throwsA(isA<SocketException>()),
);
}
expect(printed, hasLength(2));
expect(
printed.first,
contains('refused network connection to kuhy-cloud.duckdns.org'),
);
client.close(force: true);
});
test('the PC poke is unchanged next to the tile exception', () {
SandboxHttpOverrides.pokeHost = '127.0.0.1';
final poke = Uri.parse('http://127.0.0.1:$kPcPokePort$kPcPokePath');
expect(SandboxHttpOverrides.allows(poke), isTrue);
expect(SandboxHttpOverrides.allowsTile(poke), isFalse);
expect(SandboxHttpOverrides.allows(tile()), isFalse);
});
});
}

View File

@ -15,42 +15,49 @@ void main() {
final start = DateTime.utc(2026, 11, 10, 8);
test('the loop is a legal ~4 km track for the filter', () {
final fixes = sandboxLoopFixes(start);
final filter = GpsFilter();
for (final fix in fixes) {
expect(filter.add(fix), FixVerdict.accepted);
}
expect(filter.distanceM, closeTo(kLoopLengthM, 20));
expect(movingSeconds(filter.points), fixes.length * 2 - 2);
expect(fixes.first.time, start);
// A closed loop: the lap ends where it began.
expect(
haversineM(
fixes.first.latitude,
fixes.first.longitude,
fixes.last.latitude,
fixes.last.longitude,
),
lessThan(5),
);
});
for (final sport in RunSport.values) {
test('the ${sport.tcxName} loop is a legal ~4 km track for the filter', () {
final fixes = sandboxLoopFixes(start, sport);
final filter = GpsFilter(sport: sport);
for (final fix in fixes) {
expect(filter.add(fix), FixVerdict.accepted);
}
expect(filter.distanceM, closeTo(kLoopLengthM, 20));
expect(movingSeconds(filter.points, sport), fixes.length * 2 - 2);
expect(fixes.first.time, start);
// A closed loop: the lap ends where it began.
expect(
haversineM(
fixes.first.latitude,
fixes.first.longitude,
fixes.last.latitude,
fixes.last.longitude,
),
lessThan(5),
);
});
}
test('the lap runs at 10 km/h (24 minutes of fixes)', () {
final lap = sandboxLoopFixes(start);
expect(lap.last.time.difference(start), const Duration(minutes: 24));
test('a run laps at 10 km/h (24 minutes of fixes), a walk at 5 km/h', () {
final run = sandboxLoopFixes(start, RunSport.running);
final walk = sandboxLoopFixes(start, RunSport.walking);
expect(run.last.time.difference(start), const Duration(minutes: 24));
expect(walk.last.time.difference(start), const Duration(minutes: 48));
});
test('replay times follow the start, so two replays never share an id', () {
final a = sandboxLoopFixes(start);
final b = sandboxLoopFixes(start.add(const Duration(seconds: 1)));
final a = sandboxLoopFixes(start, RunSport.running);
final b = sandboxLoopFixes(
start.add(const Duration(seconds: 1)),
RunSport.running,
);
expect(RunTrack.idFor(a.first.time), isNot(RunTrack.idFor(b.first.time)));
});
test('the speed-up divides the 2 s fix interval', () async {
for (final (factor, micros) in [(1, 2000000), (10, 200000), (60, 33333)]) {
Sandbox.runReplayFactor = factor;
final source = sandboxRunSource(now: start);
final source = sandboxRunSource(RunSport.running, now: start);
expect(source, isA<ScriptedPositionSource>());
expect(
(source as ScriptedPositionSource).fixDelay,
@ -61,28 +68,22 @@ void main() {
test('the default speed-up replays a whole run in under a minute', () {
expect(Sandbox.runReplayFactor, 60);
final fixes = sandboxLoopFixes(start).length;
final fixes = sandboxLoopFixes(start, RunSport.running).length;
expect(fixes * 2 / Sandbox.runReplayFactor, lessThan(60));
expect(
sandboxLoopFixes(start, RunSport.walking).length * 2 / 60,
lessThan(60),
);
expect(Sandbox.replayFactors, [1, 10, 60]);
});
test('the sandbox replays; the daily build reads the real GPS', () async {
Sandbox.enabled = true;
expect(positionSourceFor(), isA<ScriptedPositionSource>());
expect(positionSourceFor(RunSport.running), isA<ScriptedPositionSource>());
Sandbox.enabled = false;
expect(positionSourceFor(), isA<GeolocatorPositionSource>());
});
test('the idle position is the replay first fix, and only that', () async {
Sandbox.enabled = true;
final source = idlePositionSourceFor(now: start);
final fixes = await source.fixes().toList();
expect(fixes, hasLength(1));
final first = sandboxLoopFixes(start).first;
expect(fixes.single.latitude, first.latitude);
expect(fixes.single.longitude, first.longitude);
expect((await source.requestAccess()).isGranted, isTrue);
Sandbox.enabled = false;
expect(idlePositionSourceFor(), isA<GeolocatorPositionSource>());
expect(
positionSourceFor(RunSport.running),
isA<GeolocatorPositionSource>(),
);
});
}

View File

@ -5,49 +5,16 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:latlong2/latlong.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/pace_target_store.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_map_slot.dart';
import '../fake_run_service.dart';
import '../fake_run_uploader.dart';
import '../run_test_fixtures.dart';
import '../widgets/_run_map_fixtures.dart';
/// An in-memory [PaceTargetStore].
class MemoryPaceStore implements PaceTargetStore {
/// The stored target.
int value = kDefaultPaceTarget;
/// How many times [save] ran.
int saves = 0;
@override
Future<int> load() async => value;
@override
Future<void> save(int seconds) async {
saves++;
value = seconds;
}
}
/// The real map slot over fake tiles, so nothing reaches the network.
Widget fakeTileMap(
BuildContext context,
ValueListenable<List<RunPoint>> points,
ValueListenable<LatLng?> position,
) => RunMapSlot(
points: points,
position: position,
tileProviderOpener: fakeTiles(),
);
/// Everything a test needs to drive and inspect one screen.
class RunHarness {
@ -66,13 +33,12 @@ class RunHarness {
final Completer<void>? saveGate;
final uploader = FakeRunUploader();
final cues = QuietCues();
final paceStore = MemoryPaceStore();
final saved = <RunTrack>[];
final settingsOpened = <int>[];
final navigator = GlobalKey<NavigatorState>();
RunController build() => RunController(
sourceFor: () => source,
sourceFor: (_) => source,
service: service,
cues: cues,
save: (track) async {
@ -89,31 +55,26 @@ class RunHarness {
home: const SizedBox(),
);
/// The screen over [mapBuilder], fake tiles by default; [realMap] leaves
/// the screen's own default map in place.
RunScreen screen({RunMapBuilder? mapBuilder, bool realMap = false}) =>
RunScreen(
controllerFactory: build,
uploader: uploader,
paceStore: paceStore,
mapBuilder: realMap ? null : mapBuilder ?? fakeTileMap,
openSettings: () async {
settingsOpened.add(1);
return true;
},
);
RunScreen screen({
Widget Function(BuildContext, ValueListenable<List<RunPoint>>)? mapBuilder,
}) => RunScreen(
controllerFactory: build,
uploader: uploader,
mapBuilder: mapBuilder,
openSettings: () async {
settingsOpened.add(1);
return true;
},
);
/// Pumps the app with the run screen pushed on top of an empty route.
Future<void> pump(
WidgetTester tester, {
RunMapBuilder? mapBuilder,
bool realMap = false,
Widget Function(BuildContext, ValueListenable<List<RunPoint>>)? mapBuilder,
}) async {
await tester.pumpWidget(app());
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (_) => screen(mapBuilder: mapBuilder, realMap: realMap),
),
MaterialPageRoute<void>(builder: (_) => screen(mapBuilder: mapBuilder)),
);
await tester.pumpAndSettle();
}

View File

@ -1,15 +1,11 @@
// The run icon on the home screen opens the run screen.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:geolocator/geolocator.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/storage_service.dart';
import '../fake_audio_platform.dart';
import '../fake_geolocator.dart';
import '../fake_secure_storage.dart';
import '_home_test_fixtures.dart';
@ -20,17 +16,10 @@ void main() {
});
setUp(() async {
// The run screen reads its last pace target from shared_preferences.
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage();
installFakeAudioPlatform();
// The real run controller asks the real source where the user is.
final original = GeolocatorPlatform.instance;
GeolocatorPlatform.instance = FakeGeolocator();
addTearDown(() => GeolocatorPlatform.instance = original);
});
testWidgets('the run icon opens the run screen and back returns home', (

View File

@ -1,25 +0,0 @@
// Without an injected map builder the run screen shows the real map slot
// (over the disk-cached OSM source).
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/map_tile_cache.dart';
import 'package:workout_app/widgets/run_map.dart';
import '../fake_audio_platform.dart';
import '../fake_path_provider.dart';
import '_run_screen_fixtures.dart';
void main() {
setUp(() {
installFakeAudioPlatform();
resetOsmTileProvider();
final dir = installFakePathProvider();
addTearDown(() => dir.deleteSync(recursive: true));
});
testWidgets('the default map is the run map slot', (tester) async {
final h = RunHarness();
await h.pump(tester, realMap: true);
expect(key('run_map_slot'), findsOneWidget);
expect(find.byType(RunMap), findsOneWidget);
});
}

View File

@ -1,160 +0,0 @@
// Location refused: no map, no start, only the red icon; a grant later (the
// app coming back from settings) brings the screen back.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/widgets/run_map.dart';
import '../fake_audio_platform.dart';
import '_run_screen_fixtures.dart';
void _background(WidgetTester tester) {
for (final state in [
AppLifecycleState.inactive,
AppLifecycleState.hidden,
AppLifecycleState.paused,
]) {
tester.binding.handleAppLifecycleStateChanged(state);
}
}
Future<void> _resume(WidgetTester tester) async {
_background(tester);
for (final state in [
AppLifecycleState.hidden,
AppLifecycleState.inactive,
AppLifecycleState.resumed,
]) {
tester.binding.handleAppLifecycleStateChanged(state);
}
await tester.pumpAndSettle();
}
const _refusals = [
(LocationAccess.denied, 'run_issue_denied'),
(LocationAccess.deniedForever, 'run_issue_deniedForever'),
(LocationAccess.serviceOff, 'run_issue_serviceOff'),
];
void main() {
setUp(installFakeAudioPlatform);
for (final (access, id) in _refusals) {
testWidgets('${access.name}: no map, no start, just the red icon', (
tester,
) async {
final h = RunHarness(access: access);
await h.pump(tester);
expect(find.byType(RunMap), findsNothing);
expect(key('run_map_slot'), findsNothing);
expect(key('run_start'), findsNothing);
expect(key('run_pace_toggle'), findsNothing);
expect(key(id), findsOneWidget);
expect(find.byIcon(Icons.location_disabled), findsOneWidget);
expect(h.service.calls, isEmpty);
});
}
testWidgets('denied once: the icon asks again and can recover', (
tester,
) async {
final h = RunHarness(access: LocationAccess.denied);
await h.pump(tester);
expect(h.source.requests, 1);
await tester.tap(key('run_issue_denied'));
await tester.pumpAndSettle();
expect(h.source.requests, 2);
expect(h.settingsOpened, isEmpty);
expect(key('run_start'), findsNothing);
h.source.access = LocationAccess.granted;
await tester.tap(key('run_issue_denied'));
await tester.pumpAndSettle();
expect(key('run_start'), findsOneWidget);
expect(find.byType(RunMap), findsOneWidget);
expect(find.byIcon(Icons.location_disabled), findsNothing);
});
for (final access in [
LocationAccess.deniedForever,
LocationAccess.serviceOff,
]) {
testWidgets('${access.name}: the icon opens the app settings', (
tester,
) async {
final h = RunHarness(access: access);
await h.pump(tester);
await tester.tap(key('run_issue_${access.name}'));
expect(h.settingsOpened, [1]);
expect(h.source.requests, 1);
});
}
testWidgets('a grant in settings recovers the screen on resume', (
tester,
) async {
final h = RunHarness(access: LocationAccess.deniedForever);
await h.pump(tester);
expect(key('run_start'), findsNothing);
// Still refused: coming back changes nothing and never prompts.
await _resume(tester);
expect(key('run_start'), findsNothing);
expect(key('run_issue_deniedForever'), findsOneWidget);
h.source.access = LocationAccess.granted;
await _resume(tester);
expect(key('run_start'), findsOneWidget);
expect(find.byType(RunMap), findsOneWidget);
expect(find.byIcon(Icons.location_disabled), findsNothing);
// The recheck is silent: only the open-time request ever prompted.
expect(h.source.requests, 1);
expect(h.source.checks, greaterThanOrEqualTo(2));
});
testWidgets('revoking while idle takes the map and start away on resume', (
tester,
) async {
final h = RunHarness();
await h.pump(tester);
expect(key('run_start'), findsOneWidget);
h.source.access = LocationAccess.deniedForever;
await _resume(tester);
expect(key('run_start'), findsNothing);
expect(find.byType(RunMap), findsNothing);
expect(key('run_issue_deniedForever'), findsOneWidget);
});
testWidgets('resuming during a recording never re-checks access', (
tester,
) async {
final h = RunHarness();
await h.pump(tester);
await tapKey(tester, 'run_start');
final before = h.source.checks;
await _resume(tester);
expect(h.source.checks, before);
expect(key('run_pause'), findsOneWidget);
});
testWidgets('a start refused by a switched-off service recovers on resume', (
tester,
) async {
final h = RunHarness();
await h.pump(tester);
// Location goes off between the idle grant and the tap on start.
h.source.access = LocationAccess.serviceOff;
await tapKey(tester, 'run_start');
expect(key('run_start'), findsNothing);
expect(find.byType(RunMap), findsNothing);
expect(key('run_issue_serviceOff'), findsOneWidget);
h.source.access = LocationAccess.granted;
await _resume(tester);
expect(key('run_start'), findsOneWidget);
expect(find.byType(RunMap), findsOneWidget);
expect(find.byIcon(Icons.location_disabled), findsNothing);
});
}

View File

@ -1,102 +0,0 @@
// Before a run the map shows and follows where the user is; those display-only
// fixes never reach the recorded track.
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/widgets/run_map.dart';
import '../fake_audio_platform.dart';
import '../run_test_fixtures.dart';
import '_run_screen_fixtures.dart';
MapCamera _camera(WidgetTester tester) =>
MapCamera.of(tester.element(find.byType(RichAttributionWidget)));
Future<void> _idleFix(
WidgetTester tester,
RunHarness h,
int second,
double northM,
) async {
h.source.controller.add(fixAt(second, northM));
await tester.pump();
await tester.pump();
}
void main() {
setUp(installFakeAudioPlatform);
testWidgets('opening the screen asks for location and shows the map', (
tester,
) async {
final h = RunHarness();
await h.pump(tester);
expect(h.source.requests, 1);
expect(find.byType(RunMap), findsOneWidget);
expect(key('run_start'), findsOneWidget);
});
testWidgets('the idle map is centred on the current fix, with a marker', (
tester,
) async {
final h = RunHarness();
await h.pump(tester);
// Zoomed-out Poland until the first fix arrives.
expect(_camera(tester).zoom, lessThan(8));
await _idleFix(tester, h, 0, 0);
final fix = fixAt(0, 0);
final camera = _camera(tester);
expect(camera.center.latitude, closeTo(fix.latitude, 1e-6));
expect(camera.center.longitude, closeTo(fix.longitude, 1e-6));
expect(camera.zoom, greaterThan(15));
expect(
tester.widget<MarkerLayer>(find.byType(MarkerLayer)).markers,
hasLength(1),
);
expect(find.byType(PolylineLayer), findsNothing);
await _idleFix(tester, h, 2, 40);
expect(
_camera(tester).center.latitude,
closeTo(fixAt(2, 40).latitude, 1e-6),
);
});
testWidgets('recentre jumps to the latest fix with zero run points', (
tester,
) async {
final h = RunHarness();
await h.pump(tester);
await _idleFix(tester, h, 0, 0);
await tester.drag(find.byType(FlutterMap), const Offset(150, 0));
await tester.pump();
final dragged = _camera(tester).center.longitude;
expect(find.byIcon(Icons.my_location), findsOneWidget);
// A newer fix does not drag the camera while the user is looking around.
await _idleFix(tester, h, 2, 40);
expect(_camera(tester).center.longitude, closeTo(dragged, 1e-9));
await tester.tap(find.byIcon(Icons.my_location));
await tester.pump();
final center = _camera(tester).center;
expect(center.latitude, closeTo(fixAt(2, 40).latitude, 1e-6));
expect(center.longitude, closeTo(fixAt(2, 40).longitude, 1e-6));
expect(find.byIcon(Icons.my_location), findsNothing);
});
testWidgets('idle fixes are never recorded into the track', (tester) async {
final h = RunHarness();
await h.pump(tester);
for (var i = 0; i < 4; i++) {
await _idleFix(tester, h, i * 2, i * 6.0);
}
await tapKey(tester, 'run_start');
expect(find.byType(PolylineLayer), findsNothing);
await h.run(tester, 5, from: 10);
await tapKey(tester, 'run_finish');
expect(h.saved.single.points, hasLength(5));
});
}

View File

@ -48,12 +48,6 @@ void main() {
expect(find.byType(Scrollable), findsNothing);
_expectFits(tester);
// With the pace picker open: still nothing scrolls, nothing overflows.
await tapKey(tester, 'run_pace_toggle');
expect(find.byKey(const Key('run_pace_value')), findsOneWidget);
expect(find.byType(Scrollable), findsNothing);
_expectFits(tester);
await tapKey(tester, 'run_start');
await h.run(tester, 400);
_expectFits(tester);
@ -73,12 +67,8 @@ void main() {
addTearDown(tester.platformDispatcher.clearAllTestValues);
final h = RunHarness();
await h.pump(tester);
await tapKey(tester, 'run_pace_toggle');
_expectFits(tester);
await tapKey(tester, 'run_start');
await h.run(tester, 3000);
// Three numbers in the row (distance, average pace, current pace).
expect(find.byKey(const Key('run_pace_now')), findsOneWidget);
_expectFits(tester);
});
}

View File

@ -1,43 +0,0 @@
// One mode: every GPS activity is recorded with the running filter and written
// as a Running TCX. There is no run/walk switch left on the screen.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/tcx_codec.dart';
import '../fake_audio_platform.dart';
import '_run_screen_fixtures.dart';
void main() {
setUp(installFakeAudioPlatform);
testWidgets('no sport toggle and no sport icon anywhere', (tester) async {
final h = RunHarness();
await h.pump(tester);
expect(key('run_sport'), findsNothing);
expect(find.byType(SegmentedButton<RunSport>), findsNothing);
expect(find.byIcon(Icons.directions_walk), findsNothing);
expect(find.byIcon(Icons.directions_run), findsNothing);
await tapKey(tester, 'run_start');
expect(find.byIcon(Icons.directions_walk), findsNothing);
expect(find.byIcon(Icons.directions_run), findsNothing);
});
testWidgets('the saved track is a Running TCX with a _Running file name', (
tester,
) async {
final h = RunHarness();
await h.pump(tester);
await tapKey(tester, 'run_start');
// 3 m/s is 10.8 km/h: over any walking cap, fine for the running filter.
await h.run(tester, 30);
await tapKey(tester, 'run_finish');
final track = h.saved.single;
expect(track.sport, RunSport.running);
expect(track.distanceM, greaterThan(150));
expect(tcxFilename(track), endsWith('_Running.tcx'));
expect(encodeTcx(track), contains('Sport="Running"'));
expect(encodeTcx(track), isNot(contains('Walking')));
});
}

View File

@ -1,117 +0,0 @@
// The optional pace target on the run screen: the picker before the start, the
// coloured current pace while recording, the cues, the notification.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/ui/theme.dart';
import '../fake_audio_platform.dart';
import '_run_screen_fixtures.dart';
String _text(String id) =>
(find.byKey(Key(id)).evaluate().single.widget as Text).data!;
Color? _colour(WidgetTester tester, String id) =>
tester.widget<Text>(key(id)).style?.color;
Future<void> _pickTarget(WidgetTester tester, RunHarness h, int target) async {
h.paceStore.value = target;
await h.pump(tester);
await tapKey(tester, 'run_pace_toggle');
}
void main() {
setUp(installFakeAudioPlatform);
group('picker', () {
testWidgets('off by default: only the pace icon, no numbers', (
tester,
) async {
final h = RunHarness();
await h.pump(tester);
expect(key('run_pace_toggle'), findsOneWidget);
expect(key('run_pace_value'), findsNothing);
expect(key('run_pace_minus'), findsNothing);
});
testWidgets('on: shows the last target and steps it by 0:05', (
tester,
) async {
final h = RunHarness();
h.paceStore.value = 300;
await h.pump(tester);
await tapKey(tester, 'run_pace_toggle');
expect(_text('run_pace_value'), '5:00');
await tester.tap(key('run_pace_plus'));
await tester.pump();
expect(_text('run_pace_value'), '5:05');
await tester.tap(key('run_pace_minus'));
await tester.pump();
await tester.tap(key('run_pace_minus'));
await tester.pump();
expect(_text('run_pace_value'), '4:55');
expect(h.paceStore.value, 295);
await tapKey(tester, 'run_pace_toggle');
expect(key('run_pace_value'), findsNothing);
});
});
group('recording with a target', () {
testWidgets('no target: no second number, no cues', (tester) async {
final h = RunHarness();
await h.pump(tester);
await tapKey(tester, 'run_start');
await h.run(tester, 40);
expect(key('run_pace_now'), findsNothing);
expect(h.cues.paceCues, isEmpty);
});
testWidgets('on pace: green number, silence, average stays big', (
tester,
) async {
final h = RunHarness();
await _pickTarget(tester, h, 335); // 3 m/s is 5:33
await tapKey(tester, 'run_start');
await h.run(tester, 40);
final colors = Theme.of(
tester.element(key('run_pace')),
).extension<AppStatusColors>()!;
expect(_text('run_pace_now'), '5:33');
expect(_colour(tester, 'run_pace_now'), colors.success);
expect(_text('run_pace'), '5:33'); // the run's average
expect(h.cues.paceCues, isEmpty);
});
testWidgets('too slow: red number and one slow cue per 30 s', (
tester,
) async {
final h = RunHarness();
await _pickTarget(tester, h, 300); // wants 5:00, runs 5:33
await tapKey(tester, 'run_start');
final scheme = Theme.of(tester.element(key('run_pace'))).colorScheme;
await h.run(tester, 40); // 78 s
expect(_colour(tester, 'run_pace_now'), scheme.error);
expect(h.cues.paceCues, [PaceCue.tooSlow, PaceCue.tooSlow]);
});
testWidgets('too fast: red number and the other cue', (tester) async {
final h = RunHarness();
await _pickTarget(tester, h, 420); // wants 7:00, runs 5:33
await tapKey(tester, 'run_start');
await h.run(tester, 14); // 26 s: one cue, then throttled
expect(h.cues.paceCues, [PaceCue.tooFast]);
});
testWidgets('the notification carries the current pace as numbers', (
tester,
) async {
final h = RunHarness();
await _pickTarget(tester, h, 335);
await tapKey(tester, 'run_start');
await h.run(tester, 40);
expect(h.service.drawn.last, endsWith('5:35'));
});
});
}

View File

@ -16,6 +16,31 @@ void main() {
setUp(installFakeAudioPlatform);
group('problems are icons', () {
for (final (access, id, fixable) in [
(LocationAccess.denied, 'run_issue_denied', false),
(LocationAccess.deniedForever, 'run_issue_deniedForever', true),
(LocationAccess.serviceOff, 'run_issue_serviceOff', true),
]) {
testWidgets('${access.name}: red icon, start stays available', (
tester,
) async {
final h = RunHarness(access: access);
await h.pump(tester);
await tapKey(tester, 'run_start');
expect(key(id), findsOneWidget);
expect(find.byIcon(Icons.location_disabled), findsOneWidget);
expect(key('run_start'), findsOneWidget);
expect(h.service.calls, isEmpty);
final button = tester.widget<IconButton>(key(id));
expect(button.onPressed != null, fixable);
if (fixable) {
await tester.tap(key(id));
expect(h.settingsOpened, [1]);
}
});
}
testWidgets('a mock fix shows the wrong-location icon', (tester) async {
final h = RunHarness();
await h.pump(tester);
@ -125,7 +150,7 @@ void main() {
List<RunPoint>? seen;
await h.pump(
tester,
mapBuilder: (context, points, _) => ValueListenableBuilder(
mapBuilder: (context, points) => ValueListenableBuilder(
valueListenable: points,
builder: (context, list, _) {
seen = list;

View File

@ -1,63 +0,0 @@
// In the sandbox flavor the idle map sits on the replay's first fix: one dot
// at the loop's start, not the whole lap walked before the run.
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/sandbox/sandbox_run_replay.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/ui/theme.dart';
import '../fake_audio_platform.dart';
import '../fake_run_uploader.dart';
import '_run_screen_fixtures.dart';
MapCamera _camera(WidgetTester tester) =>
MapCamera.of(tester.element(find.byType(RichAttributionWidget)));
void main() {
setUp(() {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
installFakeAudioPlatform();
Sandbox.enabled = true;
// Fast enough that a walking replay would show within the test.
Sandbox.runReplayFactor = 1000000;
});
tearDown(() {
Sandbox.enabled = false;
Sandbox.runReplayFactor = Sandbox.defaultReplayFactor;
});
testWidgets('idle, the map sits on the replay first fix and stays there', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: RunScreen(uploader: FakeRunUploader(), mapBuilder: fakeTileMap),
),
);
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 200)),
);
await tester.pump();
await tester.pump();
final first = sandboxLoopFixes(DateTime.now()).first;
expect(_camera(tester).center.latitude, closeTo(first.latitude, 1e-6));
expect(_camera(tester).center.longitude, closeTo(first.longitude, 1e-6));
expect(find.byKey(const Key('run_start')), findsOneWidget);
// Not walking the lap before the run: a single dot, no route.
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 300)),
);
await tester.pump();
expect(find.byType(PolylineLayer), findsNothing);
expect(_camera(tester).center.latitude, closeTo(first.latitude, 1e-6));
});
}

View File

@ -4,8 +4,6 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/models/run_track.dart';
@ -28,8 +26,6 @@ void main() {
});
setUp(() async {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
StorageService.resetForTesting();
await StorageService.init();
installFakeAudioPlatform();
@ -56,13 +52,9 @@ void main() {
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: RunScreen(uploader: uploader, mapBuilder: fakeTileMap),
home: RunScreen(uploader: uploader),
),
);
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await tester.pump();
List<RunRecord>? runs;
await tester.runAsync(() async {

View File

@ -29,14 +29,14 @@ class _GatedSource extends ManualPositionSource {
void main() {
setUp(installFakeAudioPlatform);
testWidgets('idle: start, zeros and the map slot', (
testWidgets('idle: sport toggle, start, zeros and the map slot', (
tester,
) async {
final h = RunHarness();
await h.pump(tester);
expect(key('run_start'), findsOneWidget);
expect(key('run_sport'), findsNothing);
expect(key('run_sport'), findsOneWidget);
expect(key('run_pause'), findsNothing);
expect(key('run_map_slot'), findsOneWidget);
expect(find.byType(RunMapSlot), findsOneWidget);
@ -47,6 +47,26 @@ void main() {
expect(h.uploader.passes, 1);
});
testWidgets('the sport can be switched until the run starts', (tester) async {
final h = RunHarness();
await h.pump(tester);
await tester.tap(find.byIcon(Icons.directions_walk));
await tester.pumpAndSettle();
expect(
find.descendant(
of: key('run_sport'),
matching: find.byIcon(Icons.directions_walk),
),
findsOneWidget,
);
await tapKey(tester, 'run_start');
expect(find.byIcon(Icons.directions_walk), findsOneWidget);
expect(key('run_sport'), findsNothing);
expect(h.service.starts, [true]);
});
testWidgets('a run shows live numbers and can pause, resume, finish', (
tester,
) async {
@ -137,21 +157,20 @@ void main() {
expect(find.byType(RunScreen), findsNothing);
});
testWidgets('start stays disabled until the access answer lands', (
testWidgets('start is disabled while the permission prompt is open', (
tester,
) async {
final source = _GatedSource();
final h = RunHarness(source: source);
await h.pump(tester);
// The open-time request is still showing its prompt: no start yet, so a
// second request can never race it.
expect(_enabled(tester, 'run_start'), isTrue);
await tester.tap(key('run_start'));
await tester.pumpAndSettle();
expect(_enabled(tester, 'run_start'), isFalse);
source.gate.complete();
await tester.pumpAndSettle();
expect(_enabled(tester, 'run_start'), isTrue);
await tapKey(tester, 'run_start');
expect(key('run_pause'), findsOneWidget);
});

View File

@ -13,16 +13,10 @@ import 'package:workout_app/services/tcx_codec.dart';
const String kFixtureDir = '../../screen_locker/tests/fixtures/run_tcx';
/// The GPS-dropout export: shares the folder for the golden twin, but is not
/// one of the three exports these importer and backup tests count on.
const String kDropoutFixture = 'RunnerUp_2026-11-09-18-00-00_Running.tcx';
/// The three golden exports, by file name.
Map<String, Uint8List> fixtureTcx() => {
for (final f in Directory(kFixtureDir).listSync().whereType<File>())
if (f.path.endsWith('.tcx') &&
f.uri.pathSegments.last != kDropoutFixture)
f.uri.pathSegments.last: f.readAsBytesSync(),
if (f.path.endsWith('.tcx')) f.uri.pathSegments.last: f.readAsBytesSync(),
};
final DufsCredentials kLogin = DufsCredentials(

View File

@ -1,50 +0,0 @@
// The pace cues: two distinct buzz patterns and tones, silent sound switch.
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/pace_band.dart';
import '../fake_audio_platform.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late FakeAudioRecorder audio;
setUp(() => audio = installFakeAudioPlatform());
test('too slow is one long buzz, too fast three short ones', () {
expect(paceCuePattern(PaceCue.tooSlow), [0, 700]);
expect(paceCuePattern(PaceCue.tooFast), [0, 90, 70, 90, 70, 90]);
});
test('both differ from each other and from the kilometre double buzz', () {
const kilometre = [0, 150, 100, 150];
final slow = paceCuePattern(PaceCue.tooSlow);
final fast = paceCuePattern(PaceCue.tooFast);
expect(slow, isNot(fast));
expect(slow, isNot(kilometre));
expect(fast, isNot(kilometre));
});
test('each cue plays its own tone', () async {
await FeedbackCues(AudioPlayer()).paceOff(PaceCue.tooSlow);
await FeedbackCues(AudioPlayer()).paceOff(PaceCue.tooFast);
expect(audio.resumedSources, hasLength(2));
expect(audio.resumedSources.first, contains('pace_slow'));
expect(audio.resumedSources.last, contains('pace_fast'));
expect(paceCueSound(PaceCue.tooSlow), isNot(paceCueSound(PaceCue.tooFast)));
});
test('stays silent when sound is off (the buzz still carries it)', () async {
await (FeedbackCues(
AudioPlayer(),
)..soundOn = false).paceOff(PaceCue.tooFast);
expect(audio.resumedSources, isEmpty);
});
test('a tone that cannot play is logged, not thrown', () async {
audio.failNextPlay = true;
await FeedbackCues(AudioPlayer()).paceOff(PaceCue.tooSlow);
expect(audio.resumedSources, isEmpty);
});
}

View File

@ -1,4 +1,5 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/run_math.dart';
@ -23,13 +24,13 @@ GpsFix _fix(
void main() {
group('rejections', () {
test('mocked fixes are dropped', () {
final f = GpsFilter();
final f = GpsFilter(sport: RunSport.running);
expect(f.add(_fix(0, 0, mocked: true)), FixVerdict.mocked);
expect(f.points, isEmpty);
});
test('accuracy above 25 m, negative or NaN is dropped', () {
final f = GpsFilter();
final f = GpsFilter(sport: RunSport.running);
expect(f.add(_fix(0, 0, accuracy: 25.1)), FixVerdict.inaccurate);
expect(f.add(_fix(0, 0, accuracy: -1)), FixVerdict.inaccurate);
expect(f.add(_fix(0, 0, accuracy: double.nan)), FixVerdict.inaccurate);
@ -37,28 +38,26 @@ void main() {
});
test('same-second and older fixes are out of order', () {
final f = GpsFilter()..add(_fix(10, 0));
final f = GpsFilter(sport: RunSport.running)..add(_fix(10, 0));
expect(f.add(_fix(10, 5, millis: 900)), FixVerdict.outOfOrder);
expect(f.add(_fix(9, 5)), FixVerdict.outOfOrder);
expect(f.points, hasLength(1));
});
test('a jump above the 25 km/h cap is dropped, below it kept', () {
final f = GpsFilter()..add(_fix(0, 0));
test('a jump above the sport cap is dropped, below it kept', () {
final run = GpsFilter(sport: RunSport.running)..add(_fix(0, 0));
// 7.0 m/s > 25 km/h (6.94 m/s)
expect(f.add(_fix(10, 70)), FixVerdict.tooFast);
expect(f.add(_fix(20, 60)), FixVerdict.accepted);
});
expect(run.add(_fix(10, 70)), FixVerdict.tooFast);
expect(run.add(_fix(20, 60)), FixVerdict.accepted);
test('one cap for everything: a 3 m/s stroll or sprint is no jump', () {
// 3 m/s was over the old 8 km/h walking cap; it is a plain run now.
final f = GpsFilter()..add(_fix(0, 0));
expect(f.add(_fix(10, 30)), FixVerdict.accepted);
expect(f.distanceM, closeTo(30, 0.5));
final walk = GpsFilter(sport: RunSport.walking)..add(_fix(0, 0));
// 3 m/s is fine for a run but over the 8 km/h walking cap (2.22 m/s)
expect(walk.add(_fix(10, 30)), FixVerdict.tooFast);
expect(walk.add(_fix(20, 20)), FixVerdict.accepted);
});
test('five consecutive jumps re-anchor without crediting distance', () {
final f = GpsFilter()..add(_fix(0, 0));
final f = GpsFilter(sport: RunSport.walking)..add(_fix(0, 0));
for (var i = 1; i < kMaxConsecutiveJumps; i++) {
expect(f.add(_fix(i * 5, 5000)), FixVerdict.tooFast);
}
@ -69,7 +68,7 @@ void main() {
});
test('an accepted fix resets the jump counter', () {
final f = GpsFilter()..add(_fix(0, 0));
final f = GpsFilter(sport: RunSport.walking)..add(_fix(0, 0));
for (var i = 1; i < kMaxConsecutiveJumps; i++) {
f.add(_fix(i * 5, 5000));
}
@ -80,7 +79,7 @@ void main() {
group('distance credit', () {
test('moving steps accumulate haversine distance', () {
final f = GpsFilter();
final f = GpsFilter(sport: RunSport.running);
for (var i = 0; i < 4; i++) {
f.add(_fix(i * 10, i * 27.0));
}
@ -90,25 +89,26 @@ void main() {
expect(f.points.first.altitudeM, 30);
});
test('standing-still jitter and standing through a gap earn nothing', () {
final f = GpsFilter()
test('standing-still jitter and a long dropout earn no distance', () {
final f = GpsFilter(sport: RunSport.running)
..add(_fix(0, 0))
..add(_fix(10, 2)); // 0.2 m/s: standing
expect(f.distanceM, 0);
f.add(_fix(60, 2)); // 50 s later, same spot: nothing to bridge
f.add(_fix(60, 100)); // 50 s later: unseen motion
expect(f.distanceM, 0);
f.add(_fix(70, 29)); // seen again, moving
f.add(_fix(70, 127)); // seen again, moving
expect(f.distanceM, closeTo(27, 0.2));
expect(f.points, hasLength(4));
});
test('times are truncated to whole UTC seconds', () {
final f = GpsFilter()..add(_fix(3, 0, millis: 750));
final f = GpsFilter(sport: RunSport.running)
..add(_fix(3, 0, millis: 750));
expect(f.points.single.time, DateTime.utc(2026, 11, 9, 12, 0, 3));
});
test('points is a read-only view and distance starts at zero', () {
final f = GpsFilter();
final f = GpsFilter(sport: RunSport.running);
expect(f.distanceM, 0);
f.add(_fix(0, 0));
expect(() => f.points.clear(), throwsUnsupportedError);
@ -117,7 +117,7 @@ void main() {
group('consistency with movingSeconds', () {
test('every credited step is a moving step and vice versa', () {
final f = GpsFilter();
final f = GpsFilter(sport: RunSport.walking);
var north = 0.0;
for (var s = 0; s <= 300; s += 10) {
// walk 1.4 m/s, stand 40-70 s, resume
@ -125,67 +125,13 @@ void main() {
if (!standing) north += 14;
f.add(_fix(s, north));
}
expect(movingSeconds(f.points), 260);
});
});
group('signal dropout (a gap over 30 s while running)', () {
// Mirrors the PC: WALK_MAX_GAP_SECONDS 30, MIN_DROPOUT_SPEED_MPS 1.0,
// MAX_MOVING_SPEED_MPS 25 km/h.
GpsFilter runningTo30m() => GpsFilter()
..add(_fix(0, 0))
..add(_fix(10, 30));
test('at 3 m/s the straight-line distance is bridged', () {
final f = runningTo30m();
expect(f.add(_fix(70, 210)), FixVerdict.accepted); // 60 s, 180 m
expect(f.distanceM, closeTo(210, 0.5));
expect(f.points.last.distanceM, closeTo(210, 0.5));
});
test('just over the dropout floor (1 m/s) is bridged', () {
final f = runningTo30m()..add(_fix(70, 91)); // 60 s, 61 m: 1.02 m/s
expect(f.distanceM, closeTo(91, 0.5));
});
test('0.5 m/s is standing about, not a run: nothing is bridged', () {
final f = runningTo30m();
expect(f.add(_fix(70, 60)), FixVerdict.accepted); // 60 s, 30 m
expect(f.distanceM, closeTo(30, 0.5));
});
test('40 km/h is a GPS jump: rejected, nothing is bridged', () {
final f = runningTo30m();
expect(f.add(_fix(70, 30 + 666)), FixVerdict.tooFast); // 11.1 m/s
expect(f.distanceM, closeTo(30, 0.5));
});
test('31 s is a dropout needing 1 m/s, 30 s still needs only 0.5', () {
final slow = runningTo30m()..add(_fix(41, 50)); // 31 s, 20 m: 0.65 m/s
expect(slow.distanceM, closeTo(30, 0.5));
final ok = runningTo30m()..add(_fix(40, 50)); // 30 s, 20 m: 0.67 m/s
expect(ok.distanceM, closeTo(50, 0.5));
});
test('a user pause with the same geometry bridges nothing', () {
final f = runningTo30m()..breakSegment();
expect(f.add(_fix(70, 210)), FixVerdict.accepted);
expect(f.distanceM, closeTo(30, 0.5));
});
test('moving time and distance agree across the bridged dropout', () {
final f = runningTo30m()
..add(_fix(70, 210))
..add(_fix(80, 240));
expect(f.distanceM, closeTo(240, 0.5));
// 10 s + 60 s dropout + 10 s, as the PC counts it.
expect(movingSeconds(f.points), 80);
expect(movingSeconds(f.points, RunSport.walking), 260);
});
});
group('breakSegment', () {
test('the fix after a pause earns nothing, then crediting resumes', () {
final f = GpsFilter()
final f = GpsFilter(sport: RunSport.walking)
..add(_fix(0, 0))
..add(_fix(10, 14))
..breakSegment();
@ -197,7 +143,7 @@ void main() {
});
test('a pause jump is re-anchored, not rejected as a GPS jump', () {
final f = GpsFilter()
final f = GpsFilter(sport: RunSport.walking)
..add(_fix(0, 0))
..breakSegment();
expect(f.add(_fix(5, 5000)), FixVerdict.accepted);

View File

@ -1,127 +0,0 @@
// The display-only position watch behind the idle map.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/idle_location.dart';
import 'package:workout_app/services/position_source.dart';
import '../run_test_fixtures.dart';
/// A source whose permission answer the test releases by hand.
class _SlowSource extends ManualPositionSource {
final gate = Completer<LocationAccess>();
@override
Future<LocationAccess> requestAccess() => gate.future;
}
void main() {
late ManualPositionSource source;
late List<LocationAccess> heard;
late IdleLocation idle;
IdleLocation build(PositionSource s) => IdleLocation(s, onAccess: heard.add);
setUp(() {
source = ManualPositionSource();
heard = [];
idle = build(source);
});
tearDown(() => idle.dispose());
test('granted: reports it, watches, and follows each fix', () async {
expect(idle.access, isNull);
await idle.open();
expect(heard, [LocationAccess.granted]);
expect(idle.access, LocationAccess.granted);
expect(source.subscriptions, 1);
source.controller.add(fixAt(0, 0));
await pumpEventQueue();
expect(idle.position.value!.latitude, closeTo(fixAt(0, 0).latitude, 1e-9));
source.controller.add(fixAt(2, 30));
await pumpEventQueue();
expect(idle.position.value!.latitude, closeTo(fixAt(2, 30).latitude, 1e-9));
});
test('opening twice keeps a single stream', () async {
await idle.open();
await idle.open();
expect(source.subscriptions, 1);
});
test('refused: reports it, no stream, no position', () async {
source.access = LocationAccess.deniedForever;
await idle.open();
expect(heard, [LocationAccess.deniedForever]);
expect(source.subscriptions, 0);
expect(idle.position.value, isNull);
});
test('recheck never prompts; a grant starts the watch', () async {
source.access = LocationAccess.denied;
await idle.open();
source.access = LocationAccess.granted;
await idle.recheck();
expect(source.requests, 1);
expect(source.checks, 1);
expect(source.subscriptions, 1);
expect(heard.last, LocationAccess.granted);
});
test(
'recheck after a revocation ends the watch and clears the dot',
() async {
await idle.open();
source.controller.add(fixAt(0, 0));
await pumpEventQueue();
expect(source.controller.hasListener, isTrue);
source.access = LocationAccess.deniedForever;
await idle.recheck();
expect(idle.position.value, isNull);
expect(source.controller.hasListener, isFalse);
expect(heard.last, LocationAccess.deniedForever);
},
);
test('stop ends the watch and later rechecks are ignored', () async {
await idle.open();
await idle.stop();
expect(source.controller.hasListener, isFalse);
await idle.recheck();
expect(source.checks, 0);
});
test('open after stop watches again (the retry after a refusal)', () async {
await idle.open();
await idle.stop();
await idle.open();
expect(source.subscriptions, 2);
expect(source.controller.hasListener, isTrue);
});
test('an answer that lands after stop is dropped', () async {
final slow = _SlowSource();
idle = build(slow);
final opening = idle.open();
await idle.stop();
slow.gate.complete(LocationAccess.granted);
await opening;
expect(heard, isEmpty);
expect(slow.subscriptions, 0);
});
test('a stream error is logged, not thrown, and the dot stays', () async {
await idle.open();
source.controller.add(fixAt(0, 0));
await pumpEventQueue();
source.controller.addError(StateError('gps off'));
await pumpEventQueue();
expect(idle.position.value, isNotNull);
source.controller.add(fixAt(2, 6));
await pumpEventQueue();
expect(idle.position.value!.latitude, closeTo(fixAt(2, 6).latitude, 1e-9));
});
}

View File

@ -1,168 +0,0 @@
// The pace band: current pace over the last 30 s, the +-10 s band around the
// target, and the cue throttle. Pure Dart, no recorder.
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/pace_band.dart';
final _t0 = DateTime.utc(2026, 11, 9, 12);
/// Points 2 s apart moving at [mps] for [count] fixes, cumulative distance.
List<RunPoint> _points(double mps, int count, {int startSecond = 0}) => [
for (var i = 0; i < count; i++)
RunPoint(
time: _t0.add(Duration(seconds: startSecond + i * 2)),
latitude: 48,
longitude: 2,
altitudeM: 0,
distanceM: i * 2 * mps,
),
];
void main() {
group('currentPaceSeconds', () {
test('is the pace over the last 30 s of fixes', () {
// 3 m/s is 333.3 s/km.
final pace = currentPaceSeconds(_points(3, 40))!;
expect(pace, closeTo(1000 / 3, 0.01));
});
test('only the trailing 30 s count: a slow start is forgotten', () {
final slow = _points(2, 20); // 40 s at 2 m/s
final last = slow.last;
final fast = [
for (var i = 1; i <= 20; i++)
RunPoint(
time: last.time.add(Duration(seconds: i * 2)),
latitude: 48,
longitude: 2,
altitudeM: 0,
distanceM: last.distanceM + i * 2 * 4.0,
),
];
expect(
currentPaceSeconds([...slow, ...fast])!,
closeTo(250, 0.01), // 4 m/s
);
});
test('warm-up: null until the window spans 20 s', () {
expect(currentPaceSeconds(_points(3, 1)), isNull);
expect(currentPaceSeconds(_points(3, 10)), isNull); // 18 s
expect(currentPaceSeconds(_points(3, 11)), isNotNull); // 20 s
});
test('standing still is no pace (null), not "too slow"', () {
expect(currentPaceSeconds(_points(0.1, 30)), isNull);
});
test('from skips points before a resume', () {
final before = _points(3, 20);
final after = [
for (var i = 0; i < 20; i++)
RunPoint(
time: _t0.add(Duration(seconds: 44 + i * 2)),
latitude: 48,
longitude: 2,
altitudeM: 0,
// A pause adds time but no distance.
distanceM: before.last.distanceM + i * 2 * 3.0,
),
];
final all = [...before, ...after];
final naive = currentPaceSeconds(all);
final resumed = currentPaceSeconds(all, from: before.length);
expect(resumed, closeTo(1000 / 3, 0.01));
// The window is wholly after the pause here, so both agree...
expect(naive, closeTo(1000 / 3, 0.01));
// ...but a window straddling the pause does not.
final straddle = [...before, ...after.take(3)];
expect(
currentPaceSeconds(straddle, from: before.length),
isNull, // 3 points = 4 s, still warming up
);
expect(currentPaceSeconds(straddle)!, greaterThan(400));
});
test('a gap over 30 s leaves a single point: warm-up again', () {
final pts = [..._points(3, 20), ..._points(3, 1, startSecond: 200)];
expect(currentPaceSeconds(pts), isNull);
});
});
group('paceBandOf', () {
test('inside +-10 s inclusive is on pace', () {
expect(paceBandOf(current: 300, target: 300), PaceBand.onPace);
expect(paceBandOf(current: 310, target: 300), PaceBand.onPace);
expect(paceBandOf(current: 290, target: 300), PaceBand.onPace);
});
test('over the band is too slow, under it too fast', () {
expect(paceBandOf(current: 310.01, target: 300), PaceBand.tooSlow);
expect(paceBandOf(current: 289.99, target: 300), PaceBand.tooFast);
});
test('no pace yet means no verdict', () {
expect(paceBandOf(current: null, target: 300), isNull);
});
});
group('PaceCueThrottle', () {
test('silent while on pace or unknown', () {
final throttle = PaceCueThrottle();
expect(throttle.cueFor(PaceBand.onPace, _t0), isNull);
expect(throttle.cueFor(null, _t0), isNull);
});
test('too slow and too fast give distinct cues', () {
expect(PaceCueThrottle().cueFor(PaceBand.tooSlow, _t0), PaceCue.tooSlow);
expect(PaceCueThrottle().cueFor(PaceBand.tooFast, _t0), PaceCue.tooFast);
});
test('at most once per 30 s while off pace', () {
final throttle = PaceCueThrottle();
expect(throttle.cueFor(PaceBand.tooSlow, _t0), PaceCue.tooSlow);
expect(
throttle.cueFor(PaceBand.tooSlow, _t0.add(const Duration(seconds: 29))),
isNull,
);
expect(
throttle.cueFor(PaceBand.tooSlow, _t0.add(const Duration(seconds: 30))),
PaceCue.tooSlow,
);
});
test('flipping from slow to fast inside 30 s is still throttled', () {
final throttle = PaceCueThrottle()..cueFor(PaceBand.tooSlow, _t0);
expect(
throttle.cueFor(PaceBand.tooFast, _t0.add(const Duration(seconds: 10))),
isNull,
);
});
test('returning to the band stays silent and does not reset the gap', () {
final throttle = PaceCueThrottle()..cueFor(PaceBand.tooSlow, _t0);
final at = _t0.add(const Duration(seconds: 12));
expect(throttle.cueFor(PaceBand.onPace, at), isNull);
expect(
throttle.cueFor(PaceBand.tooSlow, at.add(const Duration(seconds: 5))),
isNull,
);
});
test('reset forgets the last cue', () {
final throttle = PaceCueThrottle()
..cueFor(PaceBand.tooSlow, _t0)
..reset();
expect(throttle.cueFor(PaceBand.tooSlow, _t0), PaceCue.tooSlow);
});
});
test('the target range is 3:00..12:00 in 5 s steps', () {
expect(kMinPaceTarget, 180);
expect(kMaxPaceTarget, 720);
expect(kPaceStep, 5);
expect(clampPaceTarget(100), 180);
expect(clampPaceTarget(9999), 720);
expect(clampPaceTarget(303), 305);
});
}

View File

@ -1,34 +0,0 @@
// The last pace target survives a restart (shared_preferences).
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:workout_app/services/pace_target_store.dart';
void main() {
setUp(() {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
});
test('nothing stored yet reads as the default 6:00', () async {
expect(await PrefsPaceTargetStore().load(), kDefaultPaceTarget);
expect(kDefaultPaceTarget, 360);
});
test('saves and reloads the last target', () async {
await PrefsPaceTargetStore().save(295);
expect(await PrefsPaceTargetStore().load(), 295);
});
test('an out-of-range stored value is clamped on load', () async {
await SharedPreferencesAsync().setInt(kPaceTargetKey, 5);
expect(await PrefsPaceTargetStore().load(), 180);
});
test('the default store is usable without an injected instance', () async {
final store = PrefsPaceTargetStore(SharedPreferencesAsync());
await store.save(400);
expect(await store.load(), 400);
});
}

View File

@ -108,18 +108,6 @@ void main() {
);
});
test('checkAccess reads the state and never prompts', () async {
final source = GeolocatorPositionSource();
expect(await source.checkAccess(), LocationAccess.denied);
platform.current = LocationPermission.whileInUse;
expect(await source.checkAccess(), LocationAccess.granted);
platform.current = LocationPermission.deniedForever;
expect(await source.checkAccess(), LocationAccess.deniedForever);
platform.serviceOn = false;
expect(await source.checkAccess(), LocationAccess.serviceOff);
expect(platform.requests, 0);
});
test('fixes maps positions and asks for navigation accuracy', () async {
platform.positions = [_position(), _position(mocked: true)];
final fixes = await GeolocatorPositionSource(
@ -161,7 +149,6 @@ void main() {
access: LocationAccess.deniedForever,
);
expect(await source.requestAccess(), LocationAccess.deniedForever);
expect(await source.checkAccess(), LocationAccess.deniedForever);
expect(await source.fixes().toList(), script);
});

View File

@ -1,131 +0,0 @@
// The controller's idle side (display-only position, blocked state) and the
// pace cue wiring.
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_saver.dart';
import '../fake_audio_platform.dart';
import '../fake_run_service.dart';
import '../run_test_fixtures.dart';
class _CueSpy extends FeedbackCues {
_CueSpy() : super(AudioPlayer());
final paced = <PaceCue>[];
@override
Future<void> load() async {}
@override
Future<void> paceOff(PaceCue cue) async => paced.add(cue);
}
RunController _build(
ManualPositionSource source, {
PositionSource Function()? idleSourceFor,
FeedbackCues? cues,
FakeForegroundRunClient? service,
}) => RunController(
sourceFor: () => source,
idleSourceFor: idleSourceFor,
service: service ?? FakeForegroundRunClient(),
cues: cues ?? _CueSpy(),
save: (_) async => const RunSaveResult(stored: true, reason: 'saved'),
);
void main() {
setUp(installFakeAudioPlatform);
group('idle location', () {
test('watching asks for access and tracks the position', () async {
final source = ManualPositionSource();
final controller = _build(source);
expect(controller.canStart, isFalse);
await controller.watchIdle();
expect(controller.canStart, isTrue);
expect(controller.blocked, isFalse);
source.controller.add(fixAt(0, 0));
await pumpEventQueue();
expect(controller.position.value, isNotNull);
controller.dispose();
});
test('a refusal blocks until a silent recheck finds a grant', () async {
final source = ManualPositionSource(access: LocationAccess.deniedForever);
final controller = _build(source);
await controller.watchIdle();
expect(controller.blocked, isTrue);
expect(controller.canStart, isFalse);
expect(controller.recorder.issue, RunIssue.deniedForever);
source.access = LocationAccess.granted;
await controller.recheckAccess();
expect(controller.blocked, isFalse);
expect(controller.canStart, isTrue);
expect(source.requests, 1);
controller.dispose();
});
test(
'starting ends the idle watch; a recording is not rechecked',
() async {
final source = ManualPositionSource();
final controller = _build(source);
await controller.watchIdle();
await controller.start();
source.controller.add(fixAt(0, 0));
await pumpEventQueue();
// Only the recorder listens now, and the display dot did not move.
expect(controller.position.value, isNull);
final checks = source.checks;
await controller.recheckAccess();
expect(source.checks, checks);
controller.dispose();
},
);
test('a separate idle source feeds the idle map only', () async {
final run = ManualPositionSource();
final idle = ManualPositionSource();
final controller = _build(run, idleSourceFor: () => idle);
await controller.watchIdle();
expect(idle.requests, 1);
expect(run.requests, 0);
controller.dispose();
});
});
test('pace cues reach the cue player and the notification', () async {
final source = ManualPositionSource();
final service = FakeForegroundRunClient();
final cues = _CueSpy();
final controller = _build(source, cues: cues, service: service);
controller.recorder.setPaceTarget(300);
await controller.start();
for (var i = 0; i < 12; i++) {
source.controller.add(fixAt(i * 2, i * 6.0));
}
await pumpEventQueue();
expect(cues.paced, [PaceCue.tooSlow]);
expect(service.drawn.last, endsWith('5:35'));
controller.dispose();
});
test('without a target the notification carries no current pace', () async {
final source = ManualPositionSource();
final service = FakeForegroundRunClient();
final controller = _build(source, service: service);
await controller.start();
for (var i = 0; i < 12; i++) {
source.controller.add(fixAt(i * 2, i * 6.0));
}
await pumpEventQueue();
expect(service.drawn.last.split(' '), hasLength(2));
controller.dispose();
});
}

View File

@ -40,7 +40,7 @@ void main() {
FakeForegroundRunClient service, {
Future<RunSaveResult> Function(RunTrack)? save,
}) => RunController(
sourceFor: () => source,
sourceFor: (_) => source,
service: service,
cues: FeedbackCues(AudioPlayer()),
save:

View File

@ -1,79 +0,0 @@
@TestOn('vm')
library;
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/run_math.dart';
import 'package:workout_app/services/tcx_codec.dart';
import '../run_test_fixtures.dart';
/// A run with a GPS dropout, written by the app's own filter and TCX writer.
///
/// 30 min at 3 m/s, a fix every 20 s, except that the signal is gone between
/// second 600 and 720. The PC credits a dropout that moved at 1 m/s or more
/// (`MIN_DROPOUT_SPEED_MPS`), so the cumulative `DistanceMeters` must jump
/// 360 m across it. The Python twin, `screen_locker/tests/test_run_tcx_golden.py`,
/// feeds the SAME checked-in file to the real verifier. Regenerate it with
/// `UPDATE_GOLDEN=1 flutter test test/services/run_dropout_tcx_test.dart`.
const String _dir = '../../screen_locker/tests/fixtures/run_tcx';
const String _file = 'RunnerUp_2026-11-09-18-00-00_Running.tcx';
RunTrack _recordedRun() {
final filter = GpsFilter();
for (var s = 0; s <= 1800; s += 20) {
if (s > 600 && s < 720) continue; // the dropout
final fix = fixAt(s, s * 3.0);
filter.add(
GpsFix(
time: DateTime.utc(2026, 11, 9, 17).add(Duration(seconds: s)),
latitude: fix.latitude,
longitude: fix.longitude,
altitudeM: 30,
accuracyM: 5,
),
);
}
final points = filter.points;
return RunTrack.started(
sport: RunSport.running,
startedAt: points.first.time,
points: points,
totalSeconds: movingSeconds(points),
distanceM: filter.distanceM,
);
}
void main() {
final track = _recordedRun();
test('cumulative DistanceMeters jumps across the dropout', () {
final back = decodeTcx(encodeTcx(track), fileName: _file);
final before = back.points.firstWhere(
(p) => p.time.minute == 10 && p.time.second == 0,
);
final after = back.points.firstWhere(
(p) => p.time.minute == 12 && p.time.second == 0,
);
expect(before.distanceM, closeTo(1800, 0.5));
expect(after.distanceM - before.distanceM, closeTo(360, 0.5));
});
test('lap distance and moving time count the dropout', () {
expect(track.distanceM, closeTo(5400, 1));
expect(track.totalSeconds, 1800);
});
test('encodes to exactly the checked-in file the PC test reads', () {
final encoded = encodeTcx(track);
final file = File('$_dir/$_file');
if (Platform.environment['UPDATE_GOLDEN'] == '1') {
file.writeAsStringSync(encoded);
}
expect(file.readAsStringSync(), encoded);
expect(tcxFilename(track, utcOffset: const Duration(minutes: 60)), _file);
});
}

View File

@ -28,10 +28,4 @@ void main() {
expect(formatRunDay(when.toUtc()), '03.11');
expect(formatFullDate(when.toUtc()), '2026-11-03 07:05');
});
test('formatPaceSeconds is m:ss', () {
expect(formatPaceSeconds(335), '5:35');
expect(formatPaceSeconds(720), '12:00');
expect(formatPaceSeconds(65), '1:05');
});
}

View File

@ -30,9 +30,10 @@ void main() {
});
});
group('kRunningMaxSpeedMps', () {
test('the one jump cap is 25 km/h', () {
expect(kRunningMaxSpeedMps, closeTo(25 / 3.6, 1e-9));
group('maxSpeedMps', () {
test('caps are 25 km/h for a run and 8 km/h for a walk', () {
expect(maxSpeedMps(RunSport.running), closeTo(25 / 3.6, 1e-9));
expect(maxSpeedMps(RunSport.walking), closeTo(8 / 3.6, 1e-9));
});
});
@ -50,17 +51,9 @@ void main() {
expect(isMovingStep(_p(10, 0), _p(5, 10), cap), isFalse);
});
test('30 s exactly needs 0.5 m/s, a longer dropout needs 1 m/s', () {
test('a gap over 30 s earns nothing, 30 s exactly does', () {
expect(isMovingStep(_p(0, 0), _p(30, 40), cap), isTrue);
expect(isMovingStep(_p(0, 0), _p(30, 16), cap), isTrue);
// 31 s at 0.65 m/s: a pause-like stand, not a bridged dropout.
expect(isMovingStep(_p(0, 0), _p(31, 20), cap), isFalse);
// 60 s at 1 m/s and at 3 m/s: bridged dropouts.
expect(isMovingStep(_p(0, 0), _p(60, 60), cap), isTrue);
expect(isMovingStep(_p(0, 0), _p(60, 180), cap), isTrue);
// A dropout faster than the cap or with no distance (pause) is not.
expect(isMovingStep(_p(0, 0), _p(60, 400), cap), isFalse);
expect(isMovingStep(_p(0, 0), _p(60, 0), cap), isFalse);
expect(isMovingStep(_p(0, 0), _p(31, 40), cap), isFalse);
});
test('movingSeconds sums only the moving steps', () {
@ -68,12 +61,11 @@ void main() {
_p(0, 0),
_p(10, 13), // moving, 10 s
_p(20, 13), // standing, 0 distance
_p(55, 23), // 35 s gap at 0.29 m/s, not credited
_p(65, 36), // moving, 10 s
_p(125, 216), // 60 s dropout at 3 m/s, bridged
_p(55, 60), // 35 s gap, not credited
_p(65, 73), // moving, 10 s
];
expect(movingSeconds(points), 80);
expect(movingSeconds(const []), 0);
expect(movingSeconds(points, RunSport.walking), 20);
expect(movingSeconds(const [], RunSport.running), 0);
});
});
}

View File

@ -13,17 +13,4 @@ void main() {
expect(copy.title, '0.00');
expect(copy.body, '0:00 -:--');
});
test('a pace target adds the current pace, to the nearest 5 s', () {
final copy = runNotificationCopy(
metres: 3524,
movingSeconds: 723,
currentPace: 333.3,
);
expect(copy.body, '12:03 3:25 5:35');
expect(
runNotificationCopy(metres: 1, movingSeconds: 1, currentPace: 332.4).body,
endsWith('5:30'),
);
});
}

View File

@ -1,108 +0,0 @@
// The recorder's side of the pace target: the current pace, the band, the cues
// (throttled on fix time) and the reset around a pause.
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/run_recorder.dart';
import '../run_test_fixtures.dart';
void main() {
late ManualPositionSource source;
late List<PaceCue> cues;
late RunRecorder recorder;
setUp(() {
source = ManualPositionSource();
cues = [];
recorder = RunRecorder(sourceFor: () => source, onPaceCue: cues.add);
});
tearDown(() => recorder.dispose());
Future<void> feed(int count, {int from = 0, double mps = 3}) async {
for (var i = 0; i < count; i++) {
final s = from + i * 2;
source.controller.add(fixAt(s, s * mps));
}
await pumpEventQueue();
}
test(
'no target: a pace is tracked but there is no band and no cue',
() async {
await recorder.start();
await feed(30);
expect(recorder.coach.pace, closeTo(1000 / 3, 0.01));
expect(recorder.coach.target, isNull);
expect(recorder.coach.band, isNull);
expect(cues, isEmpty);
},
);
test('warm-up: no band until 20 s of fixes', () async {
recorder.setPaceTarget(300);
await recorder.start();
await feed(5);
expect(recorder.coach.pace, isNull);
expect(recorder.coach.band, isNull);
expect(cues, isEmpty);
});
test('too slow cues once, then every 30 s of fix time', () async {
recorder.setPaceTarget(300);
await recorder.start();
await feed(11); // t = 20 s
expect(recorder.coach.band, PaceBand.tooSlow);
expect(cues, [PaceCue.tooSlow]);
await feed(14, from: 22); // up to t = 48 s
expect(cues, hasLength(1));
await feed(2, from: 50); // t = 52 s, 32 s after the first
expect(cues, [PaceCue.tooSlow, PaceCue.tooSlow]);
});
test('too fast uses the other cue; on pace is silent', () async {
recorder.setPaceTarget(420);
await recorder.start();
await feed(15);
expect(cues, [PaceCue.tooFast]);
cues.clear();
recorder.setPaceTarget(335); // within +-10 of 5:33
await feed(5, from: 30);
expect(recorder.coach.band, PaceBand.onPace);
expect(cues, isEmpty);
});
test('clearing the target drops the band', () async {
recorder.setPaceTarget(300);
await recorder.start();
await feed(15);
recorder.setPaceTarget(null);
expect(recorder.coach.band, isNull);
expect(recorder.coach.target, isNull);
});
test('a pause does not read as too slow when the run resumes', () async {
recorder.setPaceTarget(335);
await recorder.start();
await feed(15);
recorder.pause();
recorder.resume();
// 12 s later, same speed: the stretch standing still is not in the window.
await feed(8, from: 42);
expect(recorder.coach.pace, isNull); // warming up again
await feed(8, from: 58);
expect(recorder.coach.band, PaceBand.onPace);
expect(cues, isEmpty);
});
test('a new target forgets the last cue so it can speak at once', () async {
recorder.setPaceTarget(300);
await recorder.start();
await feed(12);
expect(cues, hasLength(1));
recorder.setPaceTarget(420);
await feed(1, from: 24);
expect(cues, [PaceCue.tooSlow, PaceCue.tooFast]);
});
}

View File

@ -6,7 +6,7 @@ import 'package:workout_app/services/run_recorder.dart';
import '../run_test_fixtures.dart';
RunRecorder _recorder(ManualPositionSource source, {List<int>? km}) =>
RunRecorder(sourceFor: () => source, onKilometre: km?.add);
RunRecorder(sourceFor: (_) => source, onKilometre: km?.add);
void main() {
group('start', () {
@ -56,52 +56,20 @@ void main() {
recorder.dispose();
});
test('every recording is a run, whatever the speed', () async {
final source = ManualPositionSource();
final recorder = _recorder(source);
await recorder.start();
// 6.5 m/s (23 km/h) is over any walking cap, under the 25 km/h one.
for (var i = 0; i < 6; i++) {
source.controller.add(fixAt(i * 2, i * 13.0));
}
await pumpEventQueue();
final track = await recorder.finish();
expect(track!.sport, RunSport.running);
expect(recorder.distanceM, closeTo(65, 1));
recorder.dispose();
});
});
group('noteAccess', () {
test('a refusal while idle becomes the issue, a grant clears it', () {
final recorder = _recorder(ManualPositionSource());
recorder.noteAccess(LocationAccess.deniedForever);
expect(recorder.issue, RunIssue.deniedForever);
expect(recorder.issue.isAccess, isTrue);
recorder.noteAccess(LocationAccess.granted);
expect(recorder.issue, RunIssue.none);
// A grant with nothing to clear leaves other issues alone.
recorder.noteAccess(LocationAccess.granted);
expect(recorder.issue, RunIssue.none);
recorder.dispose();
});
test('is ignored once a recording has begun', () async {
final recorder = _recorder(ManualPositionSource());
await recorder.start();
recorder.noteAccess(LocationAccess.denied);
expect(recorder.issue, RunIssue.none);
recorder.dispose();
});
test('every refusal maps to its issue', () {
expect(RunIssue.forAccess(LocationAccess.denied), RunIssue.denied);
expect(
RunIssue.forAccess(LocationAccess.serviceOff),
RunIssue.serviceOff,
test('the sport is chosen while idle only, and picks the source', () async {
final seen = <RunSport>[];
final recorder = RunRecorder(
sourceFor: (sport) {
seen.add(sport);
return ManualPositionSource();
},
);
expect(RunIssue.none.isAccess, isFalse);
expect(RunIssue.tooShort.isAccess, isFalse);
expect(recorder.selectSport(RunSport.walking), isTrue);
await recorder.start();
expect(recorder.selectSport(RunSport.running), isFalse);
expect(recorder.sport, RunSport.walking);
expect(seen, [RunSport.walking]);
recorder.dispose();
});
});

View File

@ -1,21 +1,19 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/position_source_scripted.dart';
import 'package:workout_app/services/run_recorder.dart';
import '../run_test_fixtures.dart';
RunRecorder _recorder(ManualPositionSource source, {List<int>? km}) =>
RunRecorder(sourceFor: () => source, onKilometre: km?.add);
RunRecorder(sourceFor: (_) => source, onKilometre: km?.add);
void main() {
group('a scripted run', () {
test('records points, moving time and distance, then finishes', () async {
final kms = <int>[];
final recorder = RunRecorder(
sourceFor: () => ScriptedPositionSource(straightRun(340)),
sourceFor: (_) => ScriptedPositionSource(straightRun(340)),
onKilometre: kms.add,
);
expect(await recorder.start(), isTrue);
@ -43,7 +41,7 @@ void main() {
'a stream that ends early is logged, the run is still savable',
() async {
final recorder = RunRecorder(
sourceFor: () => ScriptedPositionSource(straightRun(5)),
sourceFor: (_) => ScriptedPositionSource(straightRun(5)),
);
await recorder.start();
await pumpEventQueue();
@ -53,34 +51,6 @@ void main() {
},
);
test('the sandbox trace labels distance in metres, not km', () async {
TestWidgetsFlutterBinding.ensureInitialized();
final printed = <String>[];
debugPrint = (message, {wrapWidth}) => printed.add(message ?? '');
Sandbox.enabled = true;
addTearDown(() {
debugPrint = debugPrintThrottled;
Sandbox.enabled = false;
});
final recorder = RunRecorder(
sourceFor: () => ScriptedPositionSource(straightRun(340)),
);
await recorder.start();
await pumpEventQueue();
await recorder.finish();
final lines = printed.where(
(l) => l.contains('run stream ended') || l.contains('run finished'),
);
expect(lines, hasLength(2));
expect(
lines.first,
startsWith('WorkoutSandbox: run stream ended {m: 20'),
);
expect(lines.last, startsWith('WorkoutSandbox: run finished {m: 20'));
expect(lines.join(), isNot(contains('km:')));
recorder.dispose();
});
test('a stream closing after finish is ignored', () async {
final source = ManualPositionSource();
final recorder = _recorder(source);
@ -184,43 +154,6 @@ void main() {
recorder.dispose();
});
test(
'a signal dropout is bridged, a pause of the same length is not',
() async {
Future<RunRecorder> run({required bool paused}) async {
final source = ManualPositionSource();
final recorder = _recorder(source);
await recorder.start();
source.controller
..add(fixAt(0, 0))
..add(fixAt(2, 6));
await pumpEventQueue();
if (paused) recorder.pause();
// 58 s later and 174 m further: 3 m/s, as if the signal dropped out.
if (paused) recorder.resume();
source.controller
..add(fixAt(60, 180))
..add(fixAt(62, 186));
await pumpEventQueue();
return recorder;
}
final dropout = await run(paused: false);
expect(dropout.distanceM, closeTo(186, 0.5));
expect(dropout.seconds, 62);
final track = (await dropout.finish())!;
expect(track.distanceM, closeTo(186, 0.5));
expect(track.totalSeconds, 62);
expect(track.points.last.distanceM, closeTo(186, 0.5));
final pause = await run(paused: true);
expect(pause.distanceM, closeTo(12, 0.5));
expect(pause.seconds, 4);
dropout.dispose();
pause.dispose();
},
);
test(
'finish works from paused; pause and resume elsewhere are no-ops',
() async {

View File

@ -1,129 +0,0 @@
// The pace target rides in the /sdcard backup and comes back on a restore.
@TestOn('vm')
library;
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:shared_preferences_platform_interface/types.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/pace_target_store.dart';
import 'package:workout_app/services/storage_service.dart';
import '../widgets/_run_map_fixtures.dart' show capturingDebugPrint;
import 'storage_service_runs_fixtures.dart';
/// A preferences platform that can be neither read nor written.
base class _BrokenPrefs extends InMemorySharedPreferencesAsync {
_BrokenPrefs() : super.empty();
@override
Future<int?> getInt(String key, SharedPreferencesOptions options) =>
throw StateError('prefs unavailable');
@override
Future<bool> setInt(
String key,
int value,
SharedPreferencesOptions options,
) => throw StateError('prefs unavailable');
}
void _freshPrefs() => SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
/// Writes a backup (a write triggers one) and returns it once it is on disk.
Future<Map<String, dynamic>> _backup() async {
await svc.setLastWorkoutType('A');
for (var i = 0; i < 150; i++) {
final backup = await BackupService.instance.readBackup();
if (backup != null && (backup['settings'] as List).isNotEmpty) {
return backup;
}
await Future<void>.delayed(const Duration(milliseconds: 20));
}
fail('backup.json never written');
}
/// A reinstall: new DB, preferences holding [stale] (null: nothing), restore.
Future<void> _reinstall({int? stale}) async {
await freshInstall();
_freshPrefs();
if (stale != null) await PrefsPaceTargetStore().save(stale);
await svc.restoreFromBackupIfNeeded();
}
void main() {
useRunsTransferSandbox();
setUp(_freshPrefs);
test('a set target round-trips through backup and restore', () async {
await PrefsPaceTargetStore().save(295);
expect((await _backup())['pace_target'], 295);
await _reinstall(stale: 400);
expect(await PrefsPaceTargetStore().stored(), 295);
});
test('"off" round-trips and replaces a stale target', () async {
final backup = await _backup();
expect(backup.containsKey('pace_target'), isTrue);
expect(backup['pace_target'], isNull);
await _reinstall(stale: 400);
expect(await PrefsPaceTargetStore().stored(), isNull);
expect(await PrefsPaceTargetStore().load(), kDefaultPaceTarget);
});
test('an older backup without the field restores as off', () async {
await BackupService.instance.export({
'exercise_state': <Object>[],
'workout_history': <Object>[],
'settings': <Object>[],
});
await _reinstall(stale: 400);
expect(await PrefsPaceTargetStore().stored(), isNull);
});
test('a target that is not a number restores as off, loudly', () async {
await BackupService.instance.export({'pace_target': 'fast'});
final lines = await capturingDebugPrint(() => _reinstall(stale: 400));
expect(await PrefsPaceTargetStore().stored(), isNull);
expect(lines.where((l) => l.contains('not a number')), hasLength(1));
});
test('an out-of-range target is clamped on restore', () async {
await BackupService.instance.export({'pace_target': 60});
await _reinstall();
expect(await PrefsPaceTargetStore().stored(), kMinPaceTarget);
});
test('unreadable preferences leave the field out and say so', () async {
SharedPreferencesAsyncPlatform.instance = _BrokenPrefs();
late Map<String, dynamic> backup;
final lines = await capturingDebugPrint(
() async => backup = await _backup(),
);
expect(backup.containsKey('pace_target'), isFalse);
expect(lines.where((l) => l.contains('NOT in this backup')), hasLength(1));
});
test('unwritable preferences do not stop the rest of the restore', () async {
await BackupService.instance.export({
'settings': [
{'key': 'last_workout_type', 'value': 'B', 'updated_at': 1},
],
'pace_target': 295,
});
await freshInstall();
SharedPreferencesAsyncPlatform.instance = _BrokenPrefs();
final lines = await capturingDebugPrint(svc.restoreFromBackupIfNeeded);
expect(await svc.getNextWorkoutType(), 'A'); // last was B: restored
expect(lines.where((l) => l.contains('NOT restored')), hasLength(1));
});
}

View File

@ -64,7 +64,7 @@ void main() {
});
test('stored moving time equals the app-side moving-time rule', () {
expect(movingSeconds(track.points), track.totalSeconds);
expect(movingSeconds(track.points, track.sport), track.totalSeconds);
});
test('the checked-in file decodes back to the same track', () {

View File

@ -1,125 +0,0 @@
// RunMap.live with a current-position listenable: the idle map before a run.
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:latlong2/latlong.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/widgets/run_map.dart';
import '_run_map_fixtures.dart';
const _here = LatLng(50.06, 19.94);
const _there = LatLng(50.07, 19.95);
Future<void> _pump(WidgetTester tester, Widget map) async {
tester.view.physicalSize = const Size(400, 600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(themed(map));
await tester.pump();
await tester.pump();
}
MapCamera _camera(WidgetTester tester) =>
MapCamera.of(tester.element(find.byType(RichAttributionWidget)));
Widget _map(
ValueNotifier<List<RunPoint>> points,
ValueNotifier<LatLng?> position,
) => RunMap.live(
pointsListenable: points,
positionListenable: position,
tileProviderOpener: fakeTiles(),
);
void main() {
late ValueNotifier<List<RunPoint>> points;
late ValueNotifier<LatLng?> position;
setUp(() {
points = ValueNotifier(const []);
position = ValueNotifier(null);
});
tearDown(() {
points.dispose();
position.dispose();
});
testWidgets('no fix yet: the zoomed-out fallback, no marker', (tester) async {
await _pump(tester, _map(points, position));
expect(_camera(tester).zoom, lessThan(8));
expect(find.byType(MarkerLayer), findsNothing);
});
testWidgets('a fix before the map is built starts centred on it', (
tester,
) async {
position.value = _here;
await _pump(tester, _map(points, position));
expect(_camera(tester).center.latitude, closeTo(_here.latitude, 1e-6));
expect(_camera(tester).zoom, greaterThan(15));
expect(
tester.widget<MarkerLayer>(find.byType(MarkerLayer)).markers,
hasLength(1),
);
});
testWidgets('a later fix moves the camera and the marker', (tester) async {
await _pump(tester, _map(points, position));
position.value = _here;
await tester.pump();
expect(_camera(tester).center.longitude, closeTo(_here.longitude, 1e-6));
position.value = _there;
await tester.pump();
expect(_camera(tester).center.latitude, closeTo(_there.latitude, 1e-6));
expect(
tester.widget<MarkerLayer>(find.byType(MarkerLayer)).markers.single.point,
_there,
);
});
testWidgets('recentre jumps to the position with zero run points', (
tester,
) async {
position.value = _here;
await _pump(tester, _map(points, position));
await tester.drag(find.byType(FlutterMap), const Offset(120, 0));
await tester.pump();
expect(find.byIcon(Icons.my_location), findsOneWidget);
expect(
_camera(tester).center.longitude,
isNot(closeTo(_here.longitude, 1e-4)),
);
await tester.tap(find.byIcon(Icons.my_location));
await tester.pump();
expect(_camera(tester).center.latitude, closeTo(_here.latitude, 1e-6));
expect(_camera(tester).center.longitude, closeTo(_here.longitude, 1e-6));
});
testWidgets('once the run has points they win over the position', (
tester,
) async {
position.value = _here;
await _pump(tester, _map(points, position));
final track = buildTrack(count: 4);
points.value = track.points;
await tester.pump();
final last = track.points.last;
expect(_camera(tester).center.latitude, closeTo(last.latitude, 1e-6));
// The route's own start and live markers; no extra position marker.
expect(
tester.widget<MarkerLayer>(find.byType(MarkerLayer)).markers,
hasLength(2),
);
});
testWidgets('detail mode ignores any position', (tester) async {
await _pump(
tester,
RunMap.route(points: const [], tileProviderOpener: fakeTiles()),
);
expect(find.byType(MarkerLayer), findsNothing);
});
}

View File

@ -1,116 +0,0 @@
// The pace picker: a pace icon, and when on, - m:ss + in 0:05 steps. No
// Scrollable, so it fits the no-scroll run screen.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_pace_picker.dart';
Future<List<int>> _pump(
WidgetTester tester, {
required bool on,
int seconds = 360,
}) async {
final picked = <int>[];
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => RunPacePicker(
on: on,
seconds: seconds,
onToggle: () => picked.add(-1),
onChanged: (v) {
picked.add(v);
setState(() => seconds = v);
},
),
),
),
),
);
return picked;
}
void main() {
testWidgets('off: the icon only, and no scrollable', (tester) async {
await _pump(tester, on: false);
expect(find.byKey(const Key('run_pace_toggle')), findsOneWidget);
expect(find.byKey(const Key('run_pace_value')), findsNothing);
expect(find.byType(Scrollable), findsNothing);
});
testWidgets('the toggle reports a tap', (tester) async {
final picked = await _pump(tester, on: false);
await tester.tap(find.byKey(const Key('run_pace_toggle')));
expect(picked, [-1]);
});
testWidgets('on: m:ss between minus and plus, 0:05 per tap', (tester) async {
final picked = await _pump(tester, on: true);
expect(find.text('6:00'), findsOneWidget);
expect(find.byType(Scrollable), findsNothing);
for (final id in ['run_pace_plus', 'run_pace_plus', 'run_pace_minus']) {
await tester.tap(find.byKey(Key(id)));
await tester.pump();
}
expect(picked, [365, 370, 365]);
});
testWidgets('holding a button repeats, and stops on release', (tester) async {
final picked = await _pump(tester, on: true);
final gesture = await tester.startGesture(
tester.getCenter(find.byKey(const Key('run_pace_plus'))),
);
await tester.pump(kLongPressTimeout + const Duration(milliseconds: 10));
for (var i = 0; i < 5; i++) {
await tester.pump(kPaceRepeatEvery);
}
await gesture.up();
await tester.pump();
final steps = picked.length;
expect(steps, greaterThan(3));
await tester.pump(const Duration(seconds: 2));
expect(picked, hasLength(steps));
expect(picked, orderedEquals([...picked]..sort()));
});
testWidgets('a cancelled touch stops the repeat too', (tester) async {
final picked = await _pump(tester, on: true);
final gesture = await tester.startGesture(
tester.getCenter(find.byKey(const Key('run_pace_minus'))),
);
await tester.pump(kLongPressTimeout + const Duration(milliseconds: 10));
await gesture.cancel();
final steps = picked.length;
await tester.pump(const Duration(seconds: 2));
expect(picked, hasLength(steps));
});
testWidgets('a hold stops by itself at the end of the range', (tester) async {
final picked = await _pump(tester, on: true, seconds: 710);
final gesture = await tester.startGesture(
tester.getCenter(find.byKey(const Key('run_pace_plus'))),
);
await tester.pump(kLongPressTimeout + const Duration(milliseconds: 10));
for (var i = 0; i < 20; i++) {
await tester.pump(kPaceRepeatEvery);
}
await gesture.up();
await tester.pump(const Duration(seconds: 1));
expect(picked, [715, 720]);
expect(find.text('12:00'), findsOneWidget);
});
testWidgets('clamps at 3:00 and 12:00', (tester) async {
final low = await _pump(tester, on: true, seconds: kMinPaceTarget);
await tester.tap(find.byKey(const Key('run_pace_minus')));
expect(low, isEmpty);
final high = await _pump(tester, on: true, seconds: kMaxPaceTarget);
await tester.tap(find.byKey(const Key('run_pace_plus')));
expect(high, isEmpty);
expect(find.text('12:00'), findsOneWidget);
});
}

View File

@ -1,95 +0,0 @@
"""Render the two pace-cue tones with the standard library only.
Falling tone (``pace_slow.wav``): speed up. Rising tone (``pace_fast.wav``):
ease off. Each is two soft sine notes with a fast attack and a linear fade so
nothing clicks. They sit apart in pitch and direction, so they can be told
apart with the screen off and the phone in a pocket (the vibration pattern is
the second channel).
Usage: ``render_pace_tones.py OUT_DIR`` writes both files into OUT_DIR and
adds their entries (recipe, frame count, SHA-256) to OUT_DIR/MANIFEST.json,
leaving the other entries (the finish chime's) as they are. Standard library
only, so there is no toolkit to pin and no ``.sh`` wrapper.
"""
from __future__ import annotations
import hashlib
import json
import math
from pathlib import Path
import struct
import sys
import wave
SAMPLE_RATE = 44100
PEAK = 0.6
ATTACK_SECONDS = 0.01
# (frequency in Hz, seconds) per note.
SLOW_NOTES = ((494.0, 0.22), (370.0, 0.34))
FAST_NOTES = ((880.0, 0.11), (1319.0, 0.17))
ARG_COUNT = 2
def _note(freq: float, seconds: float) -> list[float]:
"""One sine note with an attack ramp and a linear fade to zero."""
count = int(SAMPLE_RATE * seconds)
attack = int(SAMPLE_RATE * ATTACK_SECONDS)
samples = []
for i in range(count):
gain = min(1.0, i / attack) * (1 - i / count)
samples.append(PEAK * gain * math.sin(2 * math.pi * freq * i / SAMPLE_RATE))
return samples
def render(path: Path, notes: tuple[tuple[float, float], ...]) -> dict[str, object]:
"""Write ``notes`` back to back as a 16-bit mono WAV; return its manifest entry."""
samples = [s for freq, seconds in notes for s in _note(freq, seconds)]
with wave.Wave_write(str(path)) as out:
out.setnchannels(1)
out.setsampwidth(2)
out.setframerate(SAMPLE_RATE)
out.writeframes(b"".join(struct.pack("<h", int(s * 32767)) for s in samples))
return {
"file": path.name,
"frames": len(samples),
"recipe": {
"attack_seconds": ATTACK_SECONDS,
"notes": [list(note) for note in notes],
"peak": PEAK,
"sample_rate": SAMPLE_RATE,
},
"sample_rate": SAMPLE_RATE,
"seconds": round(len(samples) / SAMPLE_RATE, 2),
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
}
def update_manifest(path: Path, entries: dict[str, dict[str, object]]) -> None:
"""Merge ``entries`` into the JSON manifest at ``path``, keeping the rest."""
manifest: dict[str, object] = (
json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
)
manifest.update(entries)
path.write_text(
json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
def main(argv: list[str]) -> int:
"""Render both tones into the directory named by ``argv[1]``."""
if len(argv) != ARG_COUNT:
sys.stderr.write("usage: render_pace_tones.py OUT_DIR\n")
return 2
out = Path(argv[1])
out.mkdir(parents=True, exist_ok=True)
entries = {
"pace_slow.wav": render(out / "pace_slow.wav", SLOW_NOTES),
"pace_fast.wav": render(out / "pace_fast.wav", FAST_NOTES),
}
update_manifest(out / "MANIFEST.json", entries)
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))

View File

@ -16,7 +16,7 @@
},
"dependencies": {
"@kuhyx/web-ui": "github:kuhyx/utils#web_ui-v0.5.0&path:/web_ui",
"astro": "7.4.8"
"astro": "7.4.7"
},
"devDependencies": {
"@astrojs/check": "0.9.12",

View File

@ -168,10 +168,10 @@ importers:
dependencies:
'@kuhyx/web-ui':
specifier: github:kuhyx/utils#web_ui-v0.5.0&path:/web_ui
version: https://codeload.github.com/kuhyx/utils/tar.gz/decf5824e609b099f9455be93c4d09b4c1fd6cae#path:/web_ui(astro@7.4.8(@types/node@26.6.6)(yaml@2.9.1))
version: https://codeload.github.com/kuhyx/utils/tar.gz/decf5824e609b099f9455be93c4d09b4c1fd6cae#path:/web_ui(astro@7.4.7(@types/node@26.6.6)(yaml@2.9.1))
astro:
specifier: 7.4.8
version: 7.4.8(@types/node@26.6.6)(yaml@2.9.1)
specifier: 7.4.7
version: 7.4.7(@types/node@26.6.6)(yaml@2.9.1)
devDependencies:
'@astrojs/check':
specifier: 0.9.12
@ -220,7 +220,7 @@ importers:
version: 8.72.1(eslint@10.14.0)(typescript@6.0.3)
vitest:
specifier: 5.1.0
version: 5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.0)(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))
version: 5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.0)(vite@8.3.5(@types/node@26.6.6)(yaml@2.9.1))
packages:
@ -470,18 +470,27 @@ packages:
'@emnapi/core@1.11.3':
resolution: {integrity: sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==}
'@emnapi/core@2.0.0-beta.2':
resolution: {integrity: sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==}
'@emnapi/runtime@1.11.1':
resolution: {integrity: sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==}
'@emnapi/runtime@1.11.3':
resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}
'@emnapi/runtime@2.0.0-beta.2':
resolution: {integrity: sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==}
'@emnapi/wasi-threads@1.2.2':
resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==}
'@emnapi/wasi-threads@1.2.3':
resolution: {integrity: sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==}
'@emnapi/wasi-threads@2.2.0':
resolution: {integrity: sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==}
'@eslint-community/eslint-utils@4.10.1':
resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
@ -755,105 +764,209 @@ packages:
'@oslojs/encoding@1.1.0':
resolution: {integrity: sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ==}
'@oxc-project/types@0.156.0':
resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
'@oxc-project/types@0.154.0':
resolution: {integrity: sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==}
'@oxc-project/types@0.157.0':
resolution: {integrity: sha512-95iTox1qdt6WGWce3xwNOVayByOfLaYAq+qGPpub6NWbBh9sv0GG3+zyfh9ZBCO/jVu5A0EWI+qQI7g6fevjxg==}
'@pkgr/core@0.3.6':
resolution: {integrity: sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==}
engines: {node: ^14.18.0 || >=16.0.0}
'@rolldown/binding-android-arm-eabi@1.2.18':
resolution: {integrity: sha512-ubTG+4KlidvioxjOFdsdEa2F6JVGZb8m2ByJUqQ7fYzUeT1cEn194POcsQ10PKH4p//q0YQn4SB3YpSuzcA1Yg==}
'@rolldown/binding-android-arm-eabi@1.2.14':
resolution: {integrity: sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [android]
'@rolldown/binding-android-arm64@1.2.18':
resolution: {integrity: sha512-2Xa1t/JeFGTZn5TbzgPppcCftF8sCVnTNvrIvoSdcZhoFzAuVy1L3xxQUQ4sfWDtwVzg1u6Yi1R3SlJugRNV2Q==}
'@rolldown/binding-android-arm-eabi@1.3.0':
resolution: {integrity: sha512-zjq+pUSE36RJG9nJXqrRfMCOxekzVhlaYMtFELHaOcRH4UqTnkWhbTbEixKEawsb0ZTVMRbn8RLYcuU4DYk8qg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [android]
'@rolldown/binding-android-arm64@1.2.14':
resolution: {integrity: sha512-QiVxHofl6A8lQU7WAtOUY4QMVZXohxwz7WJJoeh8NBEUyKfIkMRKhYyq8az/1RypNiIXzNTtiS6KwHz0erxYRQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
'@rolldown/binding-darwin-arm64@1.2.18':
resolution: {integrity: sha512-iUzw9HshVvrWci9gVXjxWS7/M/IcLvNo67vu2c/w9zKBz4hIvPRixdUpIW/iCfhldLaq9ER2hecsI9UY5z0/yA==}
'@rolldown/binding-android-arm64@1.3.0':
resolution: {integrity: sha512-HdnCiSmMGgEILGVLU1o4dcOblLGj8sMnqEFrDY/S7KRti1nTQHAqGGs2AniPspbK90AFS3pM23K/R0J3hPQXYQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
'@rolldown/binding-darwin-arm64@1.2.14':
resolution: {integrity: sha512-lTQOzHuBIooh3jIr5XINQkjPGEuGy+Dsy0meXDr6Sjty0b99kYgGh4uBC/8mJX1T0kC8d6S0aPP1Y+bHkh6aBw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
'@rolldown/binding-darwin-x64@1.2.18':
resolution: {integrity: sha512-XuDHFzbFEtZl0QGJi92+fmG67tfnp1iZ9VOeDkwasGyTq2VG3/5PnJnvAr+MTzFh/rNScJ3VhN+XpZyyGsN7Jw==}
'@rolldown/binding-darwin-arm64@1.3.0':
resolution: {integrity: sha512-TkQ2JGC8/9UxoCeH5dSJj1gxuFhzw200QTJJd2YNPRXznSSM4XvpKV2Cs+RM2BcM8sa6xa4rmXNuiJ64+1993g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
'@rolldown/binding-darwin-x64@1.2.14':
resolution: {integrity: sha512-hyMKEGatjmBYCs/Q4sbIcL/GqpFEqsX3wc+HYVQ/85A4rxc1o7rPm4DUI4GV4k/h0ITddwFSGpqQunI14GXjTA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
'@rolldown/binding-freebsd-x64@1.2.18':
resolution: {integrity: sha512-MM8opLfsLK15oEXDz6iBc0t3ahu+ew9jsAmha+ovZ33hSwYgqo7YmpRITqFTfW7xA71BLEQ3jJdTsaCmhB1c9w==}
'@rolldown/binding-darwin-x64@1.3.0':
resolution: {integrity: sha512-Gr+iZW50RJZo4BPUazaDh/Azx7W0Rl04sy2MkXD+H4RkxzUX5hIrjaVw1BK+XHsccKExQAmCy6DhvRLlUzaYUg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
'@rolldown/binding-freebsd-x64@1.2.14':
resolution: {integrity: sha512-u371GbXoVXrEgP20PwzoGNOdAOqAMhzo19JzzY+V4YmmnC+DTOoqdbMu+O+54emM59Mik/UdrtWgcuEDKWRPKA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
'@rolldown/binding-linux-arm-gnueabihf@1.2.18':
resolution: {integrity: sha512-J6EoCWiy5RnFQzHrKyHXXevZ9lukQfGpnchX/zG/k/WC2nc9O9XyS1JgA8kI9VxMFggMbCPjpv7LcikriXfehw==}
'@rolldown/binding-freebsd-x64@1.3.0':
resolution: {integrity: sha512-RwAtx8peSqUoBf8pxE0L62xKXBNnA3BtdFV+07t13t0TQoASCtV9tnU67aKKMRZSiD06SU07chB5B8fWFdW3gQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
'@rolldown/binding-linux-arm-gnueabihf@1.2.14':
resolution: {integrity: sha512-BqwKsdZQf6EqVWr8fv2MrDYzAvOZ7+NYFSJESRGs87fkseEhs0TU9TXgRJTkZoRRkxTizyEg1LKUXfU3/78uqg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
'@rolldown/binding-linux-arm64-gnu@1.2.18':
resolution: {integrity: sha512-HIkFuLF7CdDeki+1aCZLLbLq0hk/PHntb+z4/YCTo47JbksTD6jJEELIz92tYROmDmvMrNqUMqBi71BkJLDR+A==}
'@rolldown/binding-linux-arm-gnueabihf@1.3.0':
resolution: {integrity: sha512-ow8fq6kYaIx75D0EVT5GeF4DcawcEYYXJ2CvEaOzyygW1jtVDQU/9o5YYidctHBRDUgPzGaTNB6n/VMTmd1ymw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
'@rolldown/binding-linux-arm64-gnu@1.2.14':
resolution: {integrity: sha512-SD9kY8M009x/7s57Z1dgUVlP5+uYBgKQK0Tkr1WIWngrtUJmRCW1RJFMY7QDla2khXhmg2i5Io7MUjcmZNZ/KQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-arm64-musl@1.2.18':
resolution: {integrity: sha512-4oqWItLLYt7IceOnElCct8T2ek5p7PmD7LN04TRJRXGo5f3HtKTgGH6PhYRFK4C2ICkq/LMUU0BVPvvlAKhm8g==}
'@rolldown/binding-linux-arm64-gnu@1.3.0':
resolution: {integrity: sha512-PLOWuiz+rdqSgiLgN7bxvy6DjXLj8gnJxzRS243LNnLi96VeyB7VFsC3eblcKv3Xwd3jQqJfbCWRhLijTIZyvQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-arm64-musl@1.2.14':
resolution: {integrity: sha512-BJ2CL19M6uuWesMgnqJzgxoI+N+eV7b0A9O9vLV42y+gitC41fNa8KElau1tHVzuLWX5GzEuxMPhAO0tQXQMkg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/binding-linux-ppc64-gnu@1.2.18':
resolution: {integrity: sha512-+AkRly5SrCEgnPhGRfub7pucASYEC2fTsxZg7VCcnozpA2+Wn/gCYy1t7LuJS67/xyJu/7noYBJncDUkbwgw2A==}
'@rolldown/binding-linux-arm64-musl@1.3.0':
resolution: {integrity: sha512-CQ/k85cc342j5SnZ/gT9p132NXZRGTgLRhfItdYqUg+jpvL5HYFve0GB+zQDCYGwDjtDWIoqKSOitkmZMZc/tw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/binding-linux-ppc64-gnu@1.2.14':
resolution: {integrity: sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-s390x-gnu@1.2.18':
resolution: {integrity: sha512-Ttg1r9vVykMnQrE/GwYO9icKtXiuiMfRe/w74xJkeoVuvhRG+WtT6LEMOf58Yl63yd77lhHzO8Y55R8CC3XALA==}
'@rolldown/binding-linux-ppc64-gnu@1.3.0':
resolution: {integrity: sha512-wk+ZG7xDP2px3cQRFoNoNp52/w1O5hTTtciHxuastreMOp8isYUTCpcG/rEYnSQBI+nycN+B9d9pBGua+qvV7w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-s390x-gnu@1.2.14':
resolution: {integrity: sha512-V/h8ePq1fKDrmtFMz6xcCN3DKvuvMRrwwD1q0PkBeeo4DpK64biaKvqWGVxqCeYKqeRk7gE7/iKPxLCn08O97A==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-x64-gnu@1.2.18':
resolution: {integrity: sha512-xX1Tt4o5jUMma0vJsXp5eRZA9nOuyigb2dKJMMzZRmzMxLYGE9PaKKSqHPzPvSQgM8ZOEacSTQwDQcwWfh0xmQ==}
'@rolldown/binding-linux-s390x-gnu@1.3.0':
resolution: {integrity: sha512-sEgyZt72Rj7V5q6OZ7A4U2I5v4EMGEv3Fp5QmoncmKbUMTrGmpyH7MwENfERGbfUYjxdBmktw4JJLys5I1aQNQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-x64-gnu@1.2.14':
resolution: {integrity: sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-x64-musl@1.2.18':
resolution: {integrity: sha512-4VVlGI5K2kociZlW3lSN8VjG3TW5yQIlAcfCdBXMgGjJxZll15Fa4ocRHXHvIVVnwlibCw/NQajJrNDiqqpiiw==}
'@rolldown/binding-linux-x64-gnu@1.3.0':
resolution: {integrity: sha512-PvL0BoBUwVugK1pFd+zyVk1L9F6ucmQ7oF2dpy8zKPHNlbW2zrU9Jst3fWYfG7z3owjxqhwAvi5G4o0AikrJMw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-x64-musl@1.2.14':
resolution: {integrity: sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@rolldown/binding-openharmony-arm64@1.2.18':
resolution: {integrity: sha512-PApTsgH1jLYuyy3tSCz9De82Gq5qXwi7vImVZhEzTgX1C4150Cp5M2ZfL3pLvbCvbEHL0oJeC6pd6podtv8Y5w==}
'@rolldown/binding-linux-x64-musl@1.3.0':
resolution: {integrity: sha512-5N4DdzAmLtnyuh027H6ViC99BeoA4T0RwKS6qUrl6zY70AKRsNDrnEZeWnqrKmDRFxXmv8zf9yhF2DxN/SfyGQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@rolldown/binding-openharmony-arm64@1.2.14':
resolution: {integrity: sha512-qyr5XiNGxm2ytx17vvtcJ9nXn6v1gENETi503bJx3OGwZ1tSonj7BosxbMa/xeAfSl5iS9X6KjEWYXLu6v1L7Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
'@rolldown/binding-win32-arm64-msvc@1.2.18':
resolution: {integrity: sha512-J2XjWjx/SP+4x0H4r6dz3Vzb5WVkg7re40Do9K7HJ3sK2/xcmZrWwakXlSwaMvOkvruLJCD4CL/3wqsIR/thgg==}
'@rolldown/binding-openharmony-arm64@1.3.0':
resolution: {integrity: sha512-Tz+2b+yF5eVRGX3DWebn2JIvZkNYI1gkafI+nF2fau2zeQDOpBAS8w1PxHi4ke//NIOE6+2DNYyq1veIjzAXqQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
'@rolldown/binding-wasm32-wasi@1.3.0':
resolution: {integrity: sha512-ntK6OFor3nQtS1TenZP5wX59oPpkKEmour3AipGHB32u+Z8QXxjVdG+7vNSvgerRWIj6vjg4XpKu42slb0vlXQ==}
engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}
cpu: [wasm32]
'@rolldown/binding-win32-arm64-msvc@1.2.14':
resolution: {integrity: sha512-oA4o5o0S2yB199YyYXDzKUv1Z56Rc+mgOjwm7Z/vJ9Z8igiDPYvoOuDyo6g7AK/ZaF09nPhDKVnGBcYHO11GXA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
'@rolldown/binding-win32-x64-msvc@1.2.18':
resolution: {integrity: sha512-XwRJxRQvkuEtS0hIIt29QrqPJ+JzMJSNYHJw4ae/mc6uEarfRG1ceyg4HmmWiBdL/YCb6g7N5BLbSvmRJRYZHw==}
'@rolldown/binding-win32-arm64-msvc@1.3.0':
resolution: {integrity: sha512-ldH38lBlOpS+b4fbSG9euQjhYXLE18PIz5hyvf6gvFfyVLodRE/Tsu4jV8UmPqjjce6lotmUUwscxPuer4lczQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
'@rolldown/binding-win32-x64-msvc@1.2.14':
resolution: {integrity: sha512-9mE94bf2GZUaR/fUSXCMpBoWkctu421Mi0ORpm4zqfbkjKep7RxzPFa5etcGs5h+2KApoWBOA/hAJa/7saGgEQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
'@rolldown/binding-win32-x64-msvc@1.3.0':
resolution: {integrity: sha512-HglhUzUPuXNTGFt5ZwJalSEvavhFSl+nxpQM9urkzkt+2oGI1ZSwgyytk9aGw15/0kk1TCHPc57nv3DdiG8/yQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
@ -861,32 +974,32 @@ packages:
'@rolldown/pluginutils@1.0.1':
resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
'@shikijs/core@4.6.0':
resolution: {integrity: sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw==}
'@shikijs/core@4.5.0':
resolution: {integrity: sha512-6CIgwq+bt2JZ3OSjb/nBkkwEf/CfpHcbam+Mg5Pllco7HAGRQ2/EFhZrrJtbyNTgKwknfVS+llsXGygiDGwJWw==}
engines: {node: '>=20'}
'@shikijs/engine-javascript@4.6.0':
resolution: {integrity: sha512-K0oqxFoL+kEMdz89mHLFO15Tsbv3kFZ6WR1cXZKMvLSc+oqaM00A6pyga1qSeXB22dP0tTiSApRcGBaKWsEccg==}
'@shikijs/engine-javascript@4.5.0':
resolution: {integrity: sha512-Ed6UdEj84LyYkwnxM5CvSMWAD+id9ExTYri0/+x41U9zrgNifPSS9lZm0JqBP0VfYI8yr8tY5nbNq9+p9R0kFA==}
engines: {node: '>=20'}
'@shikijs/engine-oniguruma@4.6.0':
resolution: {integrity: sha512-aggd6Q7SuJOXNnsUbfG2XesxBJKBMAw/PDTUo9PyRjMaaJJ2dNrI+q0C+25ARXAK9yLHAlwxc9oRT2u68YKZ7w==}
'@shikijs/engine-oniguruma@4.5.0':
resolution: {integrity: sha512-dKVmbJecVdB9recl8a/CU4jdpNXyjJQrIcesIkpS70s5HS02ohpnCSpMUbotPnEUzbAcLQ+S4hwZYbkBBiTcJw==}
engines: {node: '>=20'}
'@shikijs/langs@4.6.0':
resolution: {integrity: sha512-1yMEX3oCVV54LUq/ovfpRkDQoYDkcvjSWFFa/YLUDMiSoRzMi2uxLJYbv41ahT8Lu9lFMaa7hecd3Q39trqUyg==}
'@shikijs/langs@4.5.0':
resolution: {integrity: sha512-wwBTqwduXSz0X4v9Qa2EWeFaYJEw1clCncWjoRNQRbVDu3SPRTRWucnouYapKj3b8Q+sk/41Vbc4B5c8nuYzLA==}
engines: {node: '>=20'}
'@shikijs/primitive@4.6.0':
resolution: {integrity: sha512-c54+TQEo9ToqgfL/AU8FpjnV09+GA9Oa7M5ROkkXteZfp5XzpAJGXjjvZQFQioJOwm/w/6Z3lIzQstAkl8coag==}
'@shikijs/primitive@4.5.0':
resolution: {integrity: sha512-UM7ShlA8oz0OWxLLO8BmO9Ip6fVqdkt8yF0EH7nOCqHfrx1eEAzF0ZUVK7L+I8NEgeu1PEWSRlxaiPPeCb4iDg==}
engines: {node: '>=20'}
'@shikijs/themes@4.6.0':
resolution: {integrity: sha512-qHAVAs80RiGD+IRuH9G+JPDOEc9A/kHsng4EzCUCwB9bLzW6Z0y9WETh2YyCcADJBmfrIaJ1Jp7KBNP6FHkgtQ==}
'@shikijs/themes@4.5.0':
resolution: {integrity: sha512-zGb87H3UBbpuI4yoh5UguB1XbU+2BDU3kflM7UfZ+Cy2hWo9lBtqjSVK20gmLY6ukYl040hAypGXMgud9vul8Q==}
engines: {node: '>=20'}
'@shikijs/types@4.6.0':
resolution: {integrity: sha512-+ENG1adsKt/X7cRYw1Nl7BEpBmPOjmQ7bR/eGmHuMlT8gtOFf3KEi5l31DJYyAWhW6Y6bjP1plU7FmaxWGENFw==}
'@shikijs/types@4.5.0':
resolution: {integrity: sha512-drtPrtD8N0DENyD2cyt6Ajy+IWsiCLgMxODwLTpvH1UsN6a9jf90tNTPjqwHvA+0Lzu9e0txk8DjfqH1p9UJRw==}
engines: {node: '>=20'}
'@shikijs/vscode-textmate@10.1.0':
@ -1156,8 +1269,8 @@ packages:
resolution: {integrity: sha512-WavQUarfgwSbpCq4xsdcIBdX5KArfI2d6DD8EIloJIMthnB1508iNpx4C77EhUyMd03LpEt8HAPzwF/cG0V39g==}
engines: {node: ^22.22.3 || ^24.16.0 || >=26.3.0}
astro@7.4.8:
resolution: {integrity: sha512-xBcOeUvOQGPDKeHiIRJCKNZStf+TyPEJ2kHrUBKpVEyEdhhPfHd0T9GP8NVvaA3I7aKPn6SGy8xEcvWPym4GsA==}
astro@7.4.7:
resolution: {integrity: sha512-fH54IOaCkZY1paEjygKn8CPfuJ3w8ns7PourcPML5AouJkQuTBqBQ2RbbIbBhutZbg2qn5se6Yl9DYybzqjC0Q==}
engines: {node: '>=22.23.4', npm: '>=9.6.5', pnpm: '>=7.1.0'}
hasBin: true
peerDependencies:
@ -1236,8 +1349,8 @@ packages:
cookie-es@1.2.3:
resolution: {integrity: sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw==}
cookie@2.0.2:
resolution: {integrity: sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==}
cookie@2.0.1:
resolution: {integrity: sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==}
engines: {node: '>=22'}
cross-spawn@7.0.6:
@ -1776,10 +1889,6 @@ packages:
resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==}
engines: {node: 18 || 20 || >=22}
mri@1.2.0:
resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==}
engines: {node: '>=4'}
mrmime@2.0.1:
resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==}
engines: {node: '>=10'}
@ -1893,10 +2002,6 @@ packages:
resolution: {integrity: sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==}
engines: {node: ^10 || ^12 || >=14}
postcss@8.5.32:
resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
engines: {node: ^10 || ^12 || >=14}
prelude-ls@1.2.1:
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
engines: {node: '>= 0.8.0'}
@ -1968,8 +2073,13 @@ packages:
retext-smartypants@6.2.0:
resolution: {integrity: sha512-kk0jOU7+zGv//kfjXEBjdIryL1Acl4i9XNkHxtM7Tm5lFiCog576fjNC9hjoR7LTKQ0DsPWy09JummSsH1uqfQ==}
rolldown@1.2.18:
resolution: {integrity: sha512-C1uuT3UR60SShuCaPQFAAZyefJCWZlAKB02BV3BuPE2Rs4fevRQltEKoFO2tV5W9/eJhU5RieV6vJj3euulfNQ==}
rolldown@1.2.14:
resolution: {integrity: sha512-eTBTTqMR6uHKLgcUqpJP8ntzDI6V4LYA8negAMBEI7gkgVvOdrx6VsvS2Ym+83KhOPdLCHWJu0w7UQFJZhHKNw==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
rolldown@1.3.0:
resolution: {integrity: sha512-7j1jdVlzWzbRat9EDMsB/QmyMcc6hOO0vbcma8LGjBTmKlpS5Hem+5fpntc/HoRV5tLrG+Qo6I1ZHV/ZuL5S8g==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
@ -2006,8 +2116,8 @@ packages:
resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}
engines: {node: '>=8'}
shiki@4.6.0:
resolution: {integrity: sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA==}
shiki@4.5.0:
resolution: {integrity: sha512-OcRW72ngQvc+MSVWBRIovC/BTW589iUE/Vxav7VeM4RcY9MUjqB+IR6ILG1k9nuW6LiG/nct9uma4/MBtnZbmQ==}
engines: {node: '>=20'}
sisteransi@1.0.5:
@ -2145,6 +2255,10 @@ packages:
undici-types@8.9.0:
resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==}
undici@8.12.1:
resolution: {integrity: sha512-usz3OVQBeh1LxNn0DzU0voLXMgn5CU/WUdpBsY6Ti5afNao+vTkmn4H/NxoXolc10cOqe2+YIG0Hspq2rsl64w==}
engines: {node: '>=22.19.0'}
undici@8.12.4:
resolution: {integrity: sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==}
engines: {node: '>=22.19.0'}
@ -2248,8 +2362,8 @@ packages:
vfile@6.0.3:
resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}
vite@8.3.7:
resolution: {integrity: sha512-oxh0dMxrayBr33ScJvvBJ2HBQ2jc1TBrXKR2NyL/MJ9WPuX19mN2DXWUmywKdyw5RFVQBo8hmtb2FMC0LHrnng==}
vite@8.3.5:
resolution: {integrity: sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
@ -2612,7 +2726,7 @@ snapshots:
'@types/mdast': 4.0.4
picomatch: 4.0.7
retext-smartypants: 6.2.0
shiki: 4.6.0
shiki: 4.5.0
smol-toml: 1.9.1
unified: 11.0.5
yaml: 2.9.1
@ -2786,6 +2900,12 @@ snapshots:
'@emnapi/wasi-threads': 1.2.3
tslib: 2.9.1
'@emnapi/core@2.0.0-beta.2':
dependencies:
'@emnapi/wasi-threads': 2.2.0
tslib: 2.9.1
optional: true
'@emnapi/runtime@1.11.1':
dependencies:
tslib: 2.9.1
@ -2795,6 +2915,11 @@ snapshots:
dependencies:
tslib: 2.9.1
'@emnapi/runtime@2.0.0-beta.2':
dependencies:
tslib: 2.9.1
optional: true
'@emnapi/wasi-threads@1.2.2':
dependencies:
tslib: 2.9.1
@ -2804,6 +2929,11 @@ snapshots:
dependencies:
tslib: 2.9.1
'@emnapi/wasi-threads@2.2.0':
dependencies:
tslib: 2.9.1
optional: true
'@eslint-community/eslint-utils@4.10.1(eslint@10.14.0)':
dependencies:
eslint: 10.14.0
@ -2980,9 +3110,9 @@ snapshots:
'@keyv/serialize@1.1.1': {}
'@kuhyx/web-ui@https://codeload.github.com/kuhyx/utils/tar.gz/decf5824e609b099f9455be93c4d09b4c1fd6cae#path:/web_ui(astro@7.4.8(@types/node@26.6.6)(yaml@2.9.1))':
'@kuhyx/web-ui@https://codeload.github.com/kuhyx/utils/tar.gz/decf5824e609b099f9455be93c4d09b4c1fd6cae#path:/web_ui(astro@7.4.7(@types/node@26.6.6)(yaml@2.9.1))':
dependencies:
astro: 7.4.8(@types/node@26.6.6)(yaml@2.9.1)
astro: 7.4.7(@types/node@26.6.6)(yaml@2.9.1)
'@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)':
dependencies:
@ -3004,93 +3134,154 @@ snapshots:
'@tybys/wasm-util': 0.10.4
optional: true
'@napi-rs/wasm-runtime@1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)':
dependencies:
'@emnapi/core': 2.0.0-beta.2
'@emnapi/runtime': 2.0.0-beta.2
'@tybys/wasm-util': 0.10.4
optional: true
'@oslojs/encoding@1.1.0': {}
'@oxc-project/types@0.156.0': {}
'@oxc-project/types@0.154.0': {}
'@oxc-project/types@0.157.0': {}
'@pkgr/core@0.3.6': {}
'@rolldown/binding-android-arm-eabi@1.2.18':
'@rolldown/binding-android-arm-eabi@1.2.14':
optional: true
'@rolldown/binding-android-arm64@1.2.18':
'@rolldown/binding-android-arm-eabi@1.3.0':
optional: true
'@rolldown/binding-darwin-arm64@1.2.18':
'@rolldown/binding-android-arm64@1.2.14':
optional: true
'@rolldown/binding-darwin-x64@1.2.18':
'@rolldown/binding-android-arm64@1.3.0':
optional: true
'@rolldown/binding-freebsd-x64@1.2.18':
'@rolldown/binding-darwin-arm64@1.2.14':
optional: true
'@rolldown/binding-linux-arm-gnueabihf@1.2.18':
'@rolldown/binding-darwin-arm64@1.3.0':
optional: true
'@rolldown/binding-linux-arm64-gnu@1.2.18':
'@rolldown/binding-darwin-x64@1.2.14':
optional: true
'@rolldown/binding-linux-arm64-musl@1.2.18':
'@rolldown/binding-darwin-x64@1.3.0':
optional: true
'@rolldown/binding-linux-ppc64-gnu@1.2.18':
'@rolldown/binding-freebsd-x64@1.2.14':
optional: true
'@rolldown/binding-linux-s390x-gnu@1.2.18':
'@rolldown/binding-freebsd-x64@1.3.0':
optional: true
'@rolldown/binding-linux-x64-gnu@1.2.18':
'@rolldown/binding-linux-arm-gnueabihf@1.2.14':
optional: true
'@rolldown/binding-linux-x64-musl@1.2.18':
'@rolldown/binding-linux-arm-gnueabihf@1.3.0':
optional: true
'@rolldown/binding-openharmony-arm64@1.2.18':
'@rolldown/binding-linux-arm64-gnu@1.2.14':
optional: true
'@rolldown/binding-win32-arm64-msvc@1.2.18':
'@rolldown/binding-linux-arm64-gnu@1.3.0':
optional: true
'@rolldown/binding-win32-x64-msvc@1.2.18':
'@rolldown/binding-linux-arm64-musl@1.2.14':
optional: true
'@rolldown/binding-linux-arm64-musl@1.3.0':
optional: true
'@rolldown/binding-linux-ppc64-gnu@1.2.14':
optional: true
'@rolldown/binding-linux-ppc64-gnu@1.3.0':
optional: true
'@rolldown/binding-linux-s390x-gnu@1.2.14':
optional: true
'@rolldown/binding-linux-s390x-gnu@1.3.0':
optional: true
'@rolldown/binding-linux-x64-gnu@1.2.14':
optional: true
'@rolldown/binding-linux-x64-gnu@1.3.0':
optional: true
'@rolldown/binding-linux-x64-musl@1.2.14':
optional: true
'@rolldown/binding-linux-x64-musl@1.3.0':
optional: true
'@rolldown/binding-openharmony-arm64@1.2.14':
optional: true
'@rolldown/binding-openharmony-arm64@1.3.0':
optional: true
'@rolldown/binding-wasm32-wasi@1.3.0':
dependencies:
'@emnapi/core': 2.0.0-beta.2
'@emnapi/runtime': 2.0.0-beta.2
'@napi-rs/wasm-runtime': 1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)
optional: true
'@rolldown/binding-win32-arm64-msvc@1.2.14':
optional: true
'@rolldown/binding-win32-arm64-msvc@1.3.0':
optional: true
'@rolldown/binding-win32-x64-msvc@1.2.14':
optional: true
'@rolldown/binding-win32-x64-msvc@1.3.0':
optional: true
'@rolldown/pluginutils@1.0.1': {}
'@shikijs/core@4.6.0':
'@shikijs/core@4.5.0':
dependencies:
'@shikijs/primitive': 4.6.0
'@shikijs/types': 4.6.0
'@shikijs/primitive': 4.5.0
'@shikijs/types': 4.5.0
'@shikijs/vscode-textmate': 10.1.0
'@types/hast': 3.0.5
hast-util-to-html: 9.0.6
'@shikijs/engine-javascript@4.6.0':
'@shikijs/engine-javascript@4.5.0':
dependencies:
'@shikijs/types': 4.6.0
'@shikijs/types': 4.5.0
'@shikijs/vscode-textmate': 10.1.0
oniguruma-to-es: 4.3.6
'@shikijs/engine-oniguruma@4.6.0':
'@shikijs/engine-oniguruma@4.5.0':
dependencies:
'@shikijs/types': 4.6.0
'@shikijs/types': 4.5.0
'@shikijs/vscode-textmate': 10.1.0
'@shikijs/langs@4.6.0':
'@shikijs/langs@4.5.0':
dependencies:
'@shikijs/types': 4.6.0
'@shikijs/types': 4.5.0
'@shikijs/primitive@4.6.0':
'@shikijs/primitive@4.5.0':
dependencies:
'@shikijs/types': 4.6.0
'@shikijs/types': 4.5.0
'@shikijs/vscode-textmate': 10.1.0
'@types/hast': 3.0.5
'@shikijs/themes@4.6.0':
'@shikijs/themes@4.5.0':
dependencies:
'@shikijs/types': 4.6.0
'@shikijs/types': 4.5.0
'@shikijs/types@4.6.0':
'@shikijs/types@4.5.0':
dependencies:
'@shikijs/vscode-textmate': 10.1.0
'@types/hast': 3.0.5
@ -3118,7 +3309,7 @@ snapshots:
picocolors: 1.1.1
redent: 3.0.0
optionalDependencies:
vitest: 5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.0)(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))
vitest: 5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.0)(vite@8.3.5(@types/node@26.6.6)(yaml@2.9.1))
'@testing-library/user-event@14.6.8(@testing-library/dom@10.4.2)':
dependencies:
@ -3268,7 +3459,7 @@ snapshots:
obug: 3.0.0
std-env: 4.3.0
tinyrainbow: 3.2.0
vitest: 5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.0)(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))
vitest: 5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.0)(vite@8.3.5(@types/node@26.6.6)(yaml@2.9.1))
'@vitest/istanbul-lib-coverage@2.1.0': {}
@ -3276,14 +3467,14 @@ snapshots:
dependencies:
'@vitest/istanbul-lib-coverage': 2.1.0
'@vitest/mocker@5.1.0(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))':
'@vitest/mocker@5.1.0(vite@8.3.5(@types/node@26.6.6)(yaml@2.9.1))':
dependencies:
'@jridgewell/trace-mapping': 0.3.31
'@vitest/spy': 5.1.0
estree-walker: 3.0.3
magic-string: 1.4.3
optionalDependencies:
vite: 8.3.7(@types/node@26.6.6)(yaml@2.9.1)
vite: 8.3.5(@types/node@26.6.6)(yaml@2.9.1)
'@vitest/spy@5.1.0': {}
@ -3417,7 +3608,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
astro@7.4.8(@types/node@26.6.6)(yaml@2.9.1):
astro@7.4.7(@types/node@26.6.6)(yaml@2.9.1):
dependencies:
'@astrojs/compiler-rs': 0.5.2
'@astrojs/internal-helpers': 0.13.1
@ -3432,7 +3623,7 @@ snapshots:
ci-info: 4.4.0
clsx: 2.1.1
common-ancestor-path: 2.0.0
cookie: 2.0.2
cookie: 2.0.1
devalue: 6.0.3
diff: 9.0.0
dset: 3.1.4
@ -3446,7 +3637,6 @@ snapshots:
jsonc-parser: 3.3.1
magic-string: 1.4.5
magicast: 0.5.5
mri: 1.2.0
mrmime: 2.0.1
neotraverse: 1.0.1
obug: 3.0.0
@ -3455,8 +3645,8 @@ snapshots:
package-manager-detector: 1.9.0
piccolore: 0.1.3
picomatch: 4.0.7
rolldown: 1.2.18
shiki: 4.6.0
rolldown: 1.3.0
shiki: 4.5.0
smol-toml: 1.9.1
svgo: 4.1.0
tinyclip: 1.0.3
@ -3467,9 +3657,10 @@ snapshots:
unifont: 1.0.3
unstorage: 1.17.6
verkit: 0.5.0
vite: 8.3.7(@types/node@26.6.6)(yaml@2.9.1)
vitefu: 1.1.3(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))
vite: 8.3.5(@types/node@26.6.6)(yaml@2.9.1)
vitefu: 1.1.3(vite@8.3.5(@types/node@26.6.6)(yaml@2.9.1))
xxhash-wasm: 1.1.0
yargs-parser: 22.0.0
zod: 4.6.7
optionalDependencies:
sharp: 0.35.5(@types/node@26.6.6)
@ -3564,7 +3755,7 @@ snapshots:
cookie-es@1.2.3: {}
cookie@2.0.2: {}
cookie@2.0.1: {}
cross-spawn@7.0.6:
dependencies:
@ -4079,8 +4270,6 @@ snapshots:
dependencies:
brace-expansion: 5.0.12
mri@1.2.0: {}
mrmime@2.0.1: {}
ms@2.1.3: {}
@ -4181,12 +4370,6 @@ snapshots:
picocolors: 1.1.1
source-map-js: 1.2.2
postcss@8.5.32:
dependencies:
nanoid: 3.3.20
picocolors: 1.1.1
source-map-js: 1.2.2
prelude-ls@1.2.1: {}
prettier@3.9.10: {}
@ -4244,26 +4427,48 @@ snapshots:
nlcst-to-string: 4.0.0
unist-util-visit: 5.2.0
rolldown@1.2.18:
rolldown@1.2.14:
dependencies:
'@oxc-project/types': 0.156.0
'@oxc-project/types': 0.154.0
'@rolldown/pluginutils': 1.0.1
optionalDependencies:
'@rolldown/binding-android-arm-eabi': 1.2.18
'@rolldown/binding-android-arm64': 1.2.18
'@rolldown/binding-darwin-arm64': 1.2.18
'@rolldown/binding-darwin-x64': 1.2.18
'@rolldown/binding-freebsd-x64': 1.2.18
'@rolldown/binding-linux-arm-gnueabihf': 1.2.18
'@rolldown/binding-linux-arm64-gnu': 1.2.18
'@rolldown/binding-linux-arm64-musl': 1.2.18
'@rolldown/binding-linux-ppc64-gnu': 1.2.18
'@rolldown/binding-linux-s390x-gnu': 1.2.18
'@rolldown/binding-linux-x64-gnu': 1.2.18
'@rolldown/binding-linux-x64-musl': 1.2.18
'@rolldown/binding-openharmony-arm64': 1.2.18
'@rolldown/binding-win32-arm64-msvc': 1.2.18
'@rolldown/binding-win32-x64-msvc': 1.2.18
'@rolldown/binding-android-arm-eabi': 1.2.14
'@rolldown/binding-android-arm64': 1.2.14
'@rolldown/binding-darwin-arm64': 1.2.14
'@rolldown/binding-darwin-x64': 1.2.14
'@rolldown/binding-freebsd-x64': 1.2.14
'@rolldown/binding-linux-arm-gnueabihf': 1.2.14
'@rolldown/binding-linux-arm64-gnu': 1.2.14
'@rolldown/binding-linux-arm64-musl': 1.2.14
'@rolldown/binding-linux-ppc64-gnu': 1.2.14
'@rolldown/binding-linux-s390x-gnu': 1.2.14
'@rolldown/binding-linux-x64-gnu': 1.2.14
'@rolldown/binding-linux-x64-musl': 1.2.14
'@rolldown/binding-openharmony-arm64': 1.2.14
'@rolldown/binding-win32-arm64-msvc': 1.2.14
'@rolldown/binding-win32-x64-msvc': 1.2.14
rolldown@1.3.0:
dependencies:
'@oxc-project/types': 0.157.0
'@rolldown/pluginutils': 1.0.1
optionalDependencies:
'@rolldown/binding-android-arm-eabi': 1.3.0
'@rolldown/binding-android-arm64': 1.3.0
'@rolldown/binding-darwin-arm64': 1.3.0
'@rolldown/binding-darwin-x64': 1.3.0
'@rolldown/binding-freebsd-x64': 1.3.0
'@rolldown/binding-linux-arm-gnueabihf': 1.3.0
'@rolldown/binding-linux-arm64-gnu': 1.3.0
'@rolldown/binding-linux-arm64-musl': 1.3.0
'@rolldown/binding-linux-ppc64-gnu': 1.3.0
'@rolldown/binding-linux-s390x-gnu': 1.3.0
'@rolldown/binding-linux-x64-gnu': 1.3.0
'@rolldown/binding-linux-x64-musl': 1.3.0
'@rolldown/binding-openharmony-arm64': 1.3.0
'@rolldown/binding-wasm32-wasi': 1.3.0
'@rolldown/binding-win32-arm64-msvc': 1.3.0
'@rolldown/binding-win32-x64-msvc': 1.3.0
satteri@0.11.6:
dependencies:
@ -4332,14 +4537,14 @@ snapshots:
shebang-regex@3.0.0: {}
shiki@4.6.0:
shiki@4.5.0:
dependencies:
'@shikijs/core': 4.6.0
'@shikijs/engine-javascript': 4.6.0
'@shikijs/engine-oniguruma': 4.6.0
'@shikijs/langs': 4.6.0
'@shikijs/themes': 4.6.0
'@shikijs/types': 4.6.0
'@shikijs/core': 4.5.0
'@shikijs/engine-javascript': 4.5.0
'@shikijs/engine-oniguruma': 4.5.0
'@shikijs/langs': 4.5.0
'@shikijs/themes': 4.5.0
'@shikijs/types': 4.5.0
'@shikijs/vscode-textmate': 10.1.0
'@types/hast': 3.0.5
@ -4463,6 +4668,8 @@ snapshots:
undici-types@8.9.0: {}
undici@8.12.1: {}
undici@8.12.4: {}
unified@11.0.5:
@ -4480,7 +4687,7 @@ snapshots:
css-tree: 3.2.1
fnv1a-64: 0.1.2
std-env: 4.3.0
undici: 8.12.4
undici: 8.12.1
unist-util-is@6.0.1:
dependencies:
@ -4534,26 +4741,26 @@ snapshots:
'@types/unist': 3.0.3
vfile-message: 4.0.3
vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1):
vite@8.3.5(@types/node@26.6.6)(yaml@2.9.1):
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.7
postcss: 8.5.32
rolldown: 1.2.18
postcss: 8.5.30
rolldown: 1.2.14
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 26.6.6
fsevents: 2.3.3
yaml: 2.9.1
vitefu@1.1.3(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1)):
vitefu@1.1.3(vite@8.3.5(@types/node@26.6.6)(yaml@2.9.1)):
optionalDependencies:
vite: 8.3.7(@types/node@26.6.6)(yaml@2.9.1)
vite: 8.3.5(@types/node@26.6.6)(yaml@2.9.1)
vitest@5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.0)(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1)):
vitest@5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.0)(vite@8.3.5(@types/node@26.6.6)(yaml@2.9.1)):
dependencies:
'@types/chai': 5.2.3
'@vitest/mocker': 5.1.0(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))
'@vitest/mocker': 5.1.0(vite@8.3.5(@types/node@26.6.6)(yaml@2.9.1))
chai: 6.3.0
es-module-lexer: 2.3.2
expect-type: 1.4.0
@ -4564,7 +4771,7 @@ snapshots:
tinybench: 6.2.2
tinyexec: 1.3.1
tinyglobby: 0.2.17
vite: 8.3.7(@types/node@26.6.6)(yaml@2.9.1)
vite: 8.3.5(@types/node@26.6.6)(yaml@2.9.1)
why-is-node-running: 3.2.1
optionalDependencies:
'@types/node': 26.6.6