Compare commits

..

10 Commits

Author SHA1 Message Date
c4cc39759a Cover the lock-mode flag, and mark the one branch Linux cannot reach
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
The Flutter coverage gate blocked the push on 8 lines, all from the desktop
target's commit. Seven of them are one branch: didChangeAppLifecycleState
returns on its first line under Platform.isLinux, and the suite runs on Linux,
so the switch below it is unreachable from any test this repo can run.
Covering it would mean threading a platform seam through the nine
Platform.isLinux checks in this app for test reachability alone, so it is
marked instead -- the same treatment, and the same shape, as
storage_service_schema's platform edge.

The eighth was just untested: parseLockMode is a pure function, and it now has
the cases that matter, including the flag arriving next to --demo-escape.
main_lifecycle_test covers the observer's initState/dispose either way.

408 tests, 2759/2759 lines.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 13:06:49 +02:00
2f95c6cb69 Stop the history tests reading the developer's own Firebase account
14 tests failed with a RemoteSyncError from listDirectory, and the cause was
not in the screen they were testing. The sync guard short-circuits on "no
backend configured", but it asks that question two ways: the sync token AND
whether a Firebase account exists. The tests faked the token into secure
storage and stopped there, so on a machine holding a cached refresh token the
real factory answered yes, the guard opened, and the fetch escaped to the
network -- where flutter_test blocks HttpClient.

That went unnoticed until the Linux desktop target landed, because the desktop
build is what authenticates from the shared refresh token: the same tests pass
on the commit before it, on this machine, this minute.

So the fixture now pins firebaseFactory to "no account" by default, which is
what the faked token was already trying to express, and HistoryScreen takes it
as a tests-only seam next to the httpClient one it already had. The two direct
constructions in workout_sync_read_test.dart are pinned the same way.

402 Flutter tests pass and flutter analyze is clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 13:01:18 +02:00
c05dc9c224 Make disarming survive the install scripts, not just systemd
Masking the units is not enough on its own. install.sh and install_systemd.sh
both COPY unit files into ~/.config/systemd/user, which silently overwrites
systemd's /dev/null mask symlinks and re-arms enforcement -- so a mask alone
loses to anyone running the obvious install command by reflex.

The marker file is the second step: while it exists, no path may install units
or enable timers, and clearing it is an explicit --rearm. --status stays usable
while disarmed but says so loudly, because "armed: no" on its own reads like a
bug rather than a deliberate state.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 12:54:13 +02:00
4d1d2ea64d Put the demo's escape hatch inside the app, the only place it can be received
Both previous escapes were unreachable, for the same underlying reason stated
two different ways. A Tk key binding cannot fire, because once the workout app
takes its seat grab X delivers every keystroke to that app alone. And "run
touch from another terminal" cannot be done, because the app covers the screen
with an override-redirect fullscreen window -- there is no other terminal to
reach. An escape has to be handled INSIDE the grab, by the app itself, or it
is not an escape.

So --demo-escape arms a key handler in the runner: Ctrl+Shift+Q ungrabs the
seat and closes the window. The grab, the override-redirect window and the
handoff are all unchanged, so the demo exercises the real locking mechanism
rather than a softened copy of it, and the hatch is the one deliberate way
out.

The handler ungrabs before closing. Destroying a window that still holds the
seat can leave the pointer and keyboard grabbed with nothing left to release
them, which needs exactly the reboot this hatch exists to prevent.

Not Escape, which the Dart side already binds for in-app navigation; shadowing
it would change the behaviour under test.

Verified in both directions against the real debug bundle, each under its own
Xvfb display: with the flag, the app exits on Ctrl+Shift+Q while holding the
grab and the lock takes the screen back; without it, the identical keystroke
does nothing and the app keeps the screen. A test asserts the production path
never passes the flag.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 12:41:07 +02:00
c3424059b2 Make the demo escapable, and stop claiming the blocking was deliberate
The demo promised three escapes and delivered none: the only way out was a
hard reboot. Two independent causes, and only one of them was demo-only.

launch_workout_app blocks until the app exits. Called straight from a Tk
button that froze the event loop, so the Escape binding and the close button
could not fire -- measured: zero handlers ran during the block, and the events
were never delivered, not merely delivered late. WorkoutSession drives the
same phases through `after` instead, on the main thread, so grab_release and
grab_input stay where Tk requires them and the loop keeps pumping (199 ticks
during a run that previously managed none).

The second cause survives a healthy event loop. The Flutter app takes its own
gdk_seat_grab with GDK_SEAT_CAPABILITY_ALL and never releases it, so while it
is up X delivers the keyboard to it and no binding of ours can fire. Correct
for production, fatal for a demo, and no flag turns it off -- so the demo's
escape is a file the app cannot intercept: touch ~/.cache/stop-workout-demo.

The previous commit's rationale for the blocking was wrong and is corrected
here rather than left to mislead. It claimed pumping Tk would let the recovery
watchdog steal the screen mid-workout; in fact release() stops the watchdog
first and stop() cancels its timers outright, so there were never any ticks to
race with. The blocking was incidental, which is why removing it costs the
production handoff nothing.

Verified with the real debug bundle under Xvfb: with the app up and holding
its seat grab, the event loop is alive, the escape file terminates it, and the
lock takes the grab back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 12:33:07 +02:00
f65cb150aa Add a hand-testable demo of the workout handoff, with the escapes left open
Trying the handoff by hand on the production lock means a global grab and VT
switching disabled -- if the Flutter app wedges, there is no way out. This
builds the same handoff against a demo-mode lock instead: grab="local", VT
switching enabled, an Escape binding and a close button, so three independent
escapes survive a hung app.

Verified end to end under Xvfb with the real debug bundle: the grab is
released, the app maps and prints WORKOUT_LOCK: ready, and closing it returns
the grab to the lock window with the status line updated.

Says in its own docstring what a green run here does NOT prove: under a local
grab gatelock's watchdog early-returns and never re-takes the grab, so the
1000ms steal-back that makes _recovery.stop() load-bearing in production is
not exercised by this script.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 12:17:11 +02:00
a8b34befb5 Lend the lock screen's grab to the workout app, without unlocking it
The locker cannot close() to let the app take over: close() also restores VT
switching, which would hand the user Ctrl+Alt+F2 and an exit from the very
obligation the lock exists to enforce. Only the grab moves; the Tk window
stays mapped underneath, so the screen is still covered if the app dies.

The watchdog has to be stopped for the duration, and measuring it is what
makes that non-negotiable. gatelock's recovery loop re-takes any grab it
finds missing every 1000ms -- by design, so that pulling a cable is not an
escape -- and holds_grab() is `grab_current() is not None`, which is False
once another X client holds it. Verified on a private Xvfb display: a naked
release is stolen back within ~1.5s, while stopping the loop first lets the
app keep the screen and the locker take it back cleanly afterwards.

The same harness confirms the ordering the handshake depends on: while the
locker holds the global grab a second X client cannot even finish connecting
(4s, no output at all), so there is no window in which the screen is
uncovered. It only gets through after the release.

Reaching into lock._recovery earns an SLF001 waiver rather than a public
pause on LockWindow: gatelock's _recovery.py carries a monotonicity proof
that no transition ever decreases the grab, and a public lend_grab() would
be exactly that transition. The waiver is documented where the other four
SLF001 waivers in this repo already live.

start_workout blocks the Tk loop for the whole workout, which is deliberate
-- pumping Tk underneath is what would let a tick steal the screen mid-set.
The docstring names the cost: a monitor hotplug is not handled until the app
exits and grab_input() re-covers every live output.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 12:08:40 +02:00
006ef037f2 Supervise the workout app as the lock surface, on a deadline that holds
The supervisor hands the X grab to the Flutter app only once the app has
printed WORKOUT_LOCK: ready, so the screen is covered continuously and a
window that never started is never handed the machine.

Enforcing that handshake needs a timeout that actually fires. readline() on
a pipe blocks until a newline arrives, so polling the clock around it cannot
bound the wait: against a real subprocess a 2s deadline took 30s, and the
hang was then misreported as "exited before signalling ready" -- the wrong
diagnostic for the wrong failure. The wait is now select-based and reads
whatever bytes are available, since a half-written line would otherwise
block inside readline() past the deadline just as surely. Reads accumulate
before matching, because a chunk boundary can fall inside the marker and
dropping it would strand a healthy app at the lock screen.

Verified against real pipes, not fakes: a silent app and a partial line both
time out on schedule, the ready line is still detected, and a marker split
across two reads is reassembled.

Split into _workout_ready for the 250-line cap. The grab handoff and the
process hooks are injected as frozen dataclasses so both directions must be
supplied at the call site and a test that fakes the process also fakes the
wait.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 11:52:02 +02:00
a48bd1334a Credit StrongLifts sessions from the headless sync, as pc_workout_verified
`sync_now()` -- what workout-sync.timer runs every 15 minutes -- only ever
ingested MANUAL records. The session reader `pull_synced_workout()` was
reachable only from `_verify_phone_workout`, i.e. the interactive lock/status
UI, so a finished session earned nothing until a lock screen happened to open.

That was survivable while the phone was the only device recording sessions:
the same lock screen that demanded the workout also verified it. The Linux
build finishes sessions with no lock screen involved at all, so the credit
would simply never arrive.

`pull_all_session_records()` is the session counterpart to the existing
`pull_all_manual_records()` -- `pull_synced_workout` returns only the single
newest session for the live unlock check, which cannot backfill a week.

New type `pc_workout_verified` rather than reusing `phone_verified`: it is
machine-checked in exactly the same way (same WorkoutSession payload, same
set/rep and duration validation), but there is no phone involved, and writing
"phone_verified" into an HMAC-signed log would make the log lie about its own
provenance.

Ingestion re-derives the verdict instead of trusting the record's `succeeded`
flag -- the record arrives over the network and this is the thing handing out
unlock credit. Every rejection logs at WARNING with an actionable reason, per
the repo's no-silent-failures rule.

One real leak fixed along the way: formatting the duration with `.0f` rounded
34m59s up to "35 min", which is precisely the hidden accept bar -- the message
would have told the user the real threshold while rejecting them at it. It now
truncates, so the advertised 40 stays the only number shown.

Verified against live data: ingests the 4 real synced sessions, and a second
run ingests 0 (the write chokepoint dedups by workout_id), so the repeating
timer cannot double-credit. Suite green at 100% branch coverage, 1046 tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 11:26:20 +02:00
186bfcabc4 Run the workout app on Linux, and let it hold the screen lock
The phone is lost, so no workout can be recorded and enforcement has been
disarmed since 2026-08-21. This gives the PC a first-class way to do the
workout, reusing the existing app rather than reimplementing the progression
rules a second time -- two implementations would guarantee the divergence the
"same weights everywhere" requirement forbids.

Storage: sqflite has no Linux plugin, so main() installs sqflite_common_ffi's
factory, which runs the same schema and migrations against the same SQL. It
was already a dev dependency driving the test suite; this only promotes it.

Auth: the account password in ~/.config/crdt-sync no longer authenticates
(verified: HTTP 400 INVALID_LOGIN_CREDENTIALS). The PC fleet has been running
on the cached refresh token all along, so the desktop credential store reads
that same 0600 file -- the Dart and Python credential JSON keys are already
identical -- and passes null instead of the stale password. This also avoids
google_sign_in, which ships no Linux implementation.

Lock mode: --lock-mode makes the window the lock surface. There is no Dart API
for this, so the runner sets override-redirect and takes an exclusive
gdk_seat_grab. Two details cost a debugging cycle each and are commented in
place: override-redirect must be set BEFORE the first map, or the window stays
mapped and never repaints; and gtk_window_fullscreen() only ASKS the window
manager, which cannot see an override-redirect window -- so the geometry is
set from the monitor directly, otherwise a strip of live desktop is left
uncovered at the edge of a larger screen.

The grab is acquired by retry rather than by asking the supervisor to release
first: the Python locker keeps its grab while this window maps on top, so the
screen is covered continuously instead of exposing the desktop for the whole
of Flutter's cold start.

Verified against the live data: pulls all 7 exercises from Firebase (Bench
17.5x12, RDL 27.5x8, Row 25x6, Situp 10x31 -- the real weights, not factory
defaults), leaves the remote progression byte-identical, and mints its own
device id rather than reusing the phone's. A Tk client is refused the grab
while the lock holds it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 11:18:48 +02:00
49 changed files with 3043 additions and 177 deletions

22
arm.sh
View File

@ -23,6 +23,9 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
readonly USER_UNIT_DIR="$HOME/.config/systemd/user"
# shellcheck source=scripts/disarm_guard.sh
source "$SCRIPT_DIR/scripts/disarm_guard.sh"
# Units that must be on disk for enforcement to be schedulable.
readonly UNITS=(
"workout-locker.service"
@ -41,11 +44,13 @@ readonly TIMERS=(
SKIP_TODAY=0
STATUS_ONLY=0
REARM=0
usage() {
echo "Usage: $(basename "$0") [--skip-today] [--status]"
echo "Usage: $(basename "$0") [--skip-today] [--status] [--rearm]"
echo " --skip-today Arm the locker but exempt today (no lock until tomorrow)"
echo " --status Report whether enforcement is armed; change nothing"
echo " --rearm Clear the disarm marker + unmask units, then arm"
exit 0
}
@ -62,10 +67,21 @@ add_skip_for_today() {
main() {
if ((STATUS_ONLY)); then
# --status changes nothing, so it stays usable while disarmed - but it
# must say so loudly, or "armed: no" reads like a bug instead of intent.
if report_disarmed; then
return
fi
verify_armed
return
fi
if ((REARM)); then
clear_disarm_marker
else
refuse_if_disarmed
fi
echo "Installing units into $USER_UNIT_DIR"
mkdir -p "$USER_UNIT_DIR"
for unit in "${UNITS[@]}"; do
@ -103,6 +119,10 @@ while [[ $# -gt 0 ]]; do
STATUS_ONLY=1
shift
;;
--rearm)
REARM=1
shift
;;
-h | --help)
usage
;;

View File

@ -87,6 +87,12 @@ else
fi
# 3. systemd units ------------------------------------------------------------
# This step installs *and enables* every unit in the repo, which would clobber
# the systemd mask symlinks. Respect the disarm marker; ./arm.sh --rearm undoes.
# shellcheck source=scripts/disarm_guard.sh
source "$SCRIPT_DIR/scripts/disarm_guard.sh"
refuse_if_disarmed
echo "[3/4] Installing systemd user units..."
mkdir -p "$SYSTEMD_USER_DIR"
shopt -s nullglob

View File

@ -14,6 +14,12 @@ LOCKER_TIMER_NAME="workout-locker.timer"
SYNC_SERVICE_NAME="workout-sync.service"
SYNC_TIMER_NAME="workout-sync.timer"
# shellcheck source=scripts/disarm_guard.sh
source "$SCRIPT_DIR/scripts/disarm_guard.sh"
# Installing units here would overwrite the systemd mask symlinks, so this
# path has to respect the disarm marker too. Re-arm via: ./arm.sh --rearm
refuse_if_disarmed
# Check if service is already installed
if [ -f "$USER_SERVICE_DIR/$SERVICE_NAME" ]; then
echo "Screen locker systemd service is already installed."

View File

@ -90,6 +90,16 @@ unfixable = []
# -truth reuse status_view.py above is exempted for — and _make_bare_verifier
# imports ScreenLocker inside the function to avoid an import cycle.
"screen_locker/_status_view_verify.py" = ["PLC0415", "SLF001"]
# _workout_handoff.py must pause gatelock's recovery watchdog while the Flutter
# app holds the screen. The loop re-takes any grab it finds missing every
# 1000ms -- by design, so that pulling a cable is not an escape -- and
# holds_grab() is `grab_current() is not None`, which is False once another X
# client holds it. Left running it would steal the screen back from the workout
# app within a second. gatelock exposes no public pause (only close(), which
# also restores VT switching and would hand the user Ctrl+Alt+F2), and adding
# one there would contradict _recovery.py's monotonicity proof that no
# transition ever decreases the grab.
"screen_locker/_workout_handoff.py" = ["SLF001"]
# explain_lock_decision takes one arg per real file path + sick history, and
# returns early per lock-decision-chain stage (see module docstring) — both
# are the deliberate design, not something to collapse into a config object.

View File

@ -0,0 +1,130 @@
"""Ingesting synced StrongLifts sessions into ``log.json``.
The manual-workout half of sync (``_manual_sync``) has always run headlessly
from ``workout-sync.timer``. Sessions did not: ``pull_synced_workout`` was
reachable only from the interactive verification flow, so a finished session
sat in Firebase uncredited until the locker next opened a window. That was
survivable while the phone was the only device recording sessions -- the same
lock screen that asked for the workout also verified it -- but the Linux build
finishes sessions with no lock screen involved at all.
Mirrors :mod:`screen_locker._manual_sync`: reconstruct, re-validate on the PC,
then HMAC-sign and append under the session's own date. Never trusts the
record's own claim that it succeeded.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from screen_locker._constants import (
MIN_WORKOUT_DURATION_MINUTES,
WORKOUT_DURATION_ACCEPT_MINUTES,
)
from screen_locker._log_mixin import write_signed_entry
from screen_locker._weekly_check import PC_WORKOUT_TYPE
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Mapping
from pathlib import Path
from screen_locker._log_mixin import RecordResult
OnIngestedCallback = Callable[[dict, "list[dict]"], None]
_logger = logging.getLogger(__name__)
def validate_session(payload: Mapping[str, object]) -> tuple[bool, str]:
"""Check a synced session payload is a real, long-enough workout.
Deliberately re-runs the same content checks
``PhoneVerificationMixin._validate_json_content`` applies, rather than
trusting ``succeeded``: a record arrives over the network and the PC is
the thing handing out unlock credit, so it re-derives the verdict.
Returns ``(ok, reason)``; ``reason`` always reads like a sentence so a
rejected session says why instead of silently not counting.
"""
exercises = payload.get("exercises")
if not isinstance(exercises, list) or not exercises:
return False, "no exercises in the session payload"
raw_duration = payload.get("duration_seconds", 0)
if not isinstance(raw_duration, (int, float)):
return False, f"duration_seconds is not a number: {raw_duration!r}"
duration_min = raw_duration / 60.0
# Accept bar carries the hidden leeway; the message advertises the round
# number only (see _constants.py).
if duration_min < WORKOUT_DURATION_ACCEPT_MINUTES:
# Truncate rather than round: 34m59s rounds UP to "35 min", which is
# exactly the hidden accept bar and would tell the user the real
# threshold while rejecting them at it. The advertised number stays
# MIN_WORKOUT_DURATION_MINUTES (see _constants.py).
return False, (
f"only {int(duration_min)} min logged, "
f"need at least {MIN_WORKOUT_DURATION_MINUTES} min"
)
return True, f"{duration_min:.0f} min"
def build_session_entry(payload: Mapping[str, object], detail: str) -> dict[str, str]:
"""Build the ``workout_data`` for a verified synced session."""
flag = "all succeeded" if payload.get("succeeded") else "partial"
workout_type = payload.get("workout_type", "?")
return {
"type": PC_WORKOUT_TYPE,
"source": f"StrongLifts workout {workout_type} ({detail}, {flag})",
"duration_minutes": f"{float(payload.get('duration_seconds', 0)) / 60.0:.1f}",
"sync_record_id": str(payload.get("start_time", "")),
}
def ingest_session_records(
log_file: Path,
records: Iterable[tuple[str, Mapping[str, object]]],
*,
on_ingested: OnIngestedCallback | None = None,
) -> list[str]:
"""Ingest synced StrongLifts sessions into ``log.json``.
For each ``(record_id, payload)``: re-validate on the PC, then HMAC-sign
and APPEND under the session's own ``date`` so the weekly count places it
in the right ISO week. Idempotent -- the write chokepoint dedups by
``workout_id`` -- so re-syncing the same session every 15 minutes is a
no-op rather than repeated credit.
``on_ingested(entry, prior_entries)`` fires for each newly-appended
session so the caller applies the identical live-workout reward.
Returns the record ids actually ingested.
"""
ingested: list[str] = []
for record_id, payload in records:
date = payload.get("date")
if not isinstance(date, str) or not date:
_logger.warning(
"Skipping synced session %s: no usable date field (%r), so it "
"cannot be filed in a week and will never count.",
record_id,
date,
)
continue
ok, detail = validate_session(payload)
if not ok:
_logger.warning(
"Skipping synced session %s dated %s: %s — it does NOT count "
"toward the weekly minimum.",
record_id,
date,
detail,
)
continue
entry = build_session_entry(payload, detail)
result: RecordResult = write_signed_entry(log_file, date, entry)
if not result.appended:
continue
ingested.append(record_id)
if on_ingested is not None:
on_ingested(entry, result.prior_entries)
return ingested

View File

@ -14,11 +14,15 @@ from screen_locker._constants import EXTRA_BENEFITS_FILE
from screen_locker._extra_benefits import weekly_shutdown_bonus_hours
from screen_locker._manual_push import push_pc_workouts
from screen_locker._manual_sync import ingest_manual_records
from screen_locker._session_sync import ingest_session_records
from screen_locker._weekly_check import (
WEEKLY_WORKOUT_MINIMUM,
count_weekly_workouts,
)
from screen_locker._workout_sync import pull_all_manual_records
from screen_locker._workout_sync import (
pull_all_manual_records,
pull_all_session_records,
)
__all__ = ["SyncMixin"]
@ -43,6 +47,7 @@ class SyncMixin:
Repeating it every 15 minutes closes that gap.
"""
self._ingest_synced_manual_workouts()
self._ingest_synced_sessions()
self._auto_fill_week_runnerup_bonus()
def _ingest_synced_manual_workouts(self) -> None:
@ -64,6 +69,27 @@ class SyncMixin:
_logger.info("Ingested synced manual workout: %s", record_id)
self.workout_data = {}
def _ingest_synced_sessions(self) -> None:
"""Ingest StrongLifts sessions other devices (or this PC) finished.
The desktop build of workout_app writes a session to its own device
log and nothing else; without this the record would only ever be seen
by the interactive verification flow, so a workout finished on the PC
earned nothing until a lock screen happened to open.
Each newly-ingested session earns the identical reward a live-logged
workout would, and re-running is a no-op (the write chokepoint dedups
by workout_id).
"""
ingested = ingest_session_records(
self.log_file,
pull_all_session_records(),
on_ingested=self._credit_ingested_manual_workout,
)
for record_id in ingested:
_logger.info("Ingested synced StrongLifts session: %s", record_id)
self.workout_data = {}
def _credit_ingested_manual_workout(
self, entry: dict[str, str], prior_entries: list[dict]
) -> None:

View File

@ -27,11 +27,19 @@ WEEKLY_WORKOUT_MINIMUM: int = 5
# Python weekday(): Mon=0, Tue=1, Wed=2, Thu=3, Fri=4, Sat=5, Sun=6
_RELAXED_WEEKDAYS: frozenset[int] = frozenset({1, 2, 3}) # Tue, Wed, Thu
# A StrongLifts session performed on the PC itself (the Linux build of
# workout_app). Machine-checked exactly like ``phone_verified`` -- same
# WorkoutSession payload, same set/rep validation -- but named separately
# because there is no phone involved: writing "phone_verified" into an
# HMAC-signed log for a workout done on the desktop would make the log lie
# about its own provenance.
PC_WORKOUT_TYPE: str = "pc_workout_verified"
# VERIFIED workouts are machine-checked (a real StrongLifts session or a real
# RunnerUp run). They count toward the weekly total INDIVIDUALLY — multiple
# per day are allowed — because they can't be faked.
VERIFIED_WORKOUT_TYPES: frozenset[str] = frozenset(
{"phone_verified", "runnerup_verified"},
{"phone_verified", "runnerup_verified", PC_WORKOUT_TYPE},
)
# The single self-reported type. It counts toward the weekly total
# INDIVIDUALLY, same as a verified workout — the manual-workout rate budget

View File

@ -0,0 +1,207 @@
"""Launching the desktop workout app as the lock surface.
The phone is gone, so the workout has to be doable on the PC — but handing the
user a normal desktop window while the lock screen is up would mean unlocking
the machine to earn the unlock. Instead the Flutter app becomes the lock: it
takes the same override-redirect fullscreen window and the same exclusive X
grab the Tk locker holds, with no way out but finishing or resetting.
Two X clients cannot hold the grab at once (verified: the second gets
``grab failed: another application has grab``), so the two windows hand it
over in a fixed order:
1. Tk keeps the grab and launches the app.
2. The app maps fullscreen ON TOP and starts retrying the grab, failing while
Tk still holds it, and prints ``WORKOUT_LOCK: ready``.
3. Only then does Tk release — so the screen is covered continuously rather
than exposing the desktop for the whole of Flutter's cold start.
Releasing the *grab* is deliberate: ``gatelock``'s ``close()`` also restores
VT switching, so tearing the Tk window down here would re-enable
Ctrl+Alt+F2 and hand the user an exit. The Tk process stays alive as the
supervisor and re-takes the grab if the app dies.
"""
from __future__ import annotations
from dataclasses import dataclass
import logging
from pathlib import Path
import subprocess
from typing import TYPE_CHECKING
from screen_locker._workout_ready import (
READY_MARKER,
await_ready,
default_selector,
)
if TYPE_CHECKING:
from screen_locker._workout_ready import _Selector
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from typing import IO, Protocol
class _Child(Protocol):
"""The half of ``subprocess.Popen`` this module actually drives."""
stdout: IO[str] | None
returncode: int | None
def terminate(self) -> None: ...
def wait(self) -> int: ...
class _Spawner(Protocol):
"""``subprocess.Popen``, narrowed to the one call shape used here."""
def __call__(
self,
args: Sequence[str],
*,
stdout: int,
stderr: int,
text: bool,
bufsize: int,
) -> _Child: ...
__all__ = [
"READY_MARKER",
"GrabHandoff",
"ProcessHooks",
"WorkoutAppResult",
"launch_workout_app",
"workout_app_binary",
]
_logger = logging.getLogger(__name__)
# Where `flutter build linux` puts the bundle, relative to the repo root.
_BUNDLE = Path("stronglift_replacement/workout_app/build/linux/x64")
_BINARY_NAME = "workout_app"
# A cold Flutter start opens the DB and pulls progression (bounded at 20s in
# the app's own main()), so the ready line can legitimately take a while.
READY_TIMEOUT_SECONDS = 60.0
@dataclass(frozen=True)
class GrabHandoff:
"""The two halves of passing the screen to the app and taking it back.
Injected so the handoff is testable without an X server, and so it is
obvious at the call site that *both* directions must be provided.
"""
release: Callable[[], None]
reacquire: Callable[[], None]
@dataclass(frozen=True)
class ProcessHooks:
"""How the supervisor spawns the app and waits on its output.
One seam because they are always substituted together: a test that fakes
the process must fake the wait too.
"""
popen: _Spawner = subprocess.Popen
selector: _Selector = default_selector
# Arms an in-app key handler that drops the grab and quits. Only the demo
# harness sets it: inside the app's own seat grab is the only place an
# escape can be received, because X delivers keystrokes nowhere else.
demo_escape: bool = False
class WorkoutAppResult:
"""Outcome of one supervised workout-app run.
Carries a human-readable ``reason`` so a failed launch says what happened
instead of silently dropping the user back to the lock screen.
"""
def __init__(self, *, launched: bool, reason: str) -> None:
self.launched = launched
self.reason = reason
def __repr__(self) -> str:
return f"WorkoutAppResult(launched={self.launched}, reason={self.reason!r})"
def workout_app_binary(repo_root: Path | None = None) -> Path | None:
"""Return the built desktop app, or None when it has not been built.
Prefers the release bundle and falls back to debug, so a machine that has
only ever run ``flutter build linux --debug`` still works.
"""
root = (
repo_root if repo_root is not None else Path(__file__).resolve().parent.parent
)
for flavour in ("release", "debug"):
candidate = root / _BUNDLE / flavour / "bundle" / _BINARY_NAME
if candidate.exists():
return candidate
_logger.error(
"The desktop workout app is not built at %s (release or debug) — the "
"lock screen cannot offer a PC workout. Build it with: "
"cd stronglift_replacement/workout_app && flutter build linux --release",
root / _BUNDLE,
)
return None
def launch_workout_app(
handoff: GrabHandoff,
*,
binary: Path | None = None,
resolve_binary: Callable[[], Path | None] = workout_app_binary,
hooks: ProcessHooks | None = None,
ready_timeout: float = READY_TIMEOUT_SECONDS,
) -> WorkoutAppResult:
"""Run the workout app as the lock surface, then restore the Tk grab.
Blocks until the app exits; the caller re-evaluates compliance afterwards
(a finished workout reaches ``log.json`` through the normal sync path, not
through this function's return value).
"""
io = hooks if hooks is not None else ProcessHooks()
app = binary if binary is not None else resolve_binary()
if app is None:
return WorkoutAppResult(
launched=False,
reason="the desktop workout app is not built; run flutter build linux",
)
child = io.popen(
[str(app), "--lock-mode"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
ready, why = await_ready(child, ready_timeout, io.selector)
if not ready:
# Never release the grab to a window that may not be up: that is the
# one failure mode that leaves the machine unlocked.
child.terminate()
return WorkoutAppResult(
launched=False,
reason=(
f"{why} — keeping the lock screen up rather than releasing the "
"screen to a window that may not have started"
),
)
handoff.release()
try:
child.wait()
finally:
# Unconditional: however the app exited, this machine must not be
# left with nothing holding the screen.
handoff.reacquire()
return WorkoutAppResult(
launched=True,
reason=f"the workout app exited with code {child.returncode}",
)

View File

@ -14,7 +14,11 @@ import logging
from typing import TYPE_CHECKING
from screen_locker import _sick_tracker
from screen_locker._weekly_check import COUNTED_WORKOUT_TYPES, count_weekly_workouts
from screen_locker._weekly_check import (
COUNTED_WORKOUT_TYPES,
PC_WORKOUT_TYPE,
count_weekly_workouts,
)
if TYPE_CHECKING:
from pathlib import Path
@ -62,6 +66,7 @@ class WorkoutCreditMixin:
if self.workout_data.get("type") not in (
"phone_verified",
"runnerup_verified",
PC_WORKOUT_TYPE,
"manual_workout",
):
return None

View File

@ -0,0 +1,83 @@
"""Handing the lock screen to the workout app, and taking it back.
The Tk locker cannot simply ``close()`` to let the app take over: ``close()``
also restores VT switching, which would hand the user Ctrl+Alt+F2 and an exit
from the very obligation the lock exists to enforce. Only the *grab* moves.
The recovery watchdog has to be stopped for the duration, and that is the part
that is easy to get wrong. It is built never to release -- it re-takes a grab
it finds missing, deliberately, so that pulling a cable is not an escape. Left
running it would treat the Flutter app exactly like an intruder and steal the
screen back within one verify tick, mid-workout. So the order is: stop the
watchdog, release the grab, run the app, re-take the grab, restart the
watchdog. The Tk window itself stays mapped underneath the whole time, which
is what keeps the screen covered if the app dies.
"""
from __future__ import annotations
import contextlib
import logging
import tkinter as tk
from typing import TYPE_CHECKING
from screen_locker._workout_app import GrabHandoff, launch_workout_app
if TYPE_CHECKING:
from gatelock import LockWindow
__all__ = ["lock_grab_handoff", "start_workout"]
_logger = logging.getLogger(__name__)
def lock_grab_handoff(lock: LockWindow) -> GrabHandoff:
"""Build the release/reacquire pair for a live lock window.
Neither direction touches VT switching or the arbiter claim: this is a
loan of the grab, not a teardown.
"""
def release() -> None:
# Stop first: a watchdog tick between the release and the app's own
# grab would take the screen straight back off it.
lock._recovery.stop()
with contextlib.suppress(tk.TclError):
lock.root.grab_release()
_logger.warning(
"Released the X grab to the workout app; the lock window stays "
"mapped and VT switching stays disabled."
)
def reacquire() -> None:
# Unconditional and idempotent: whatever happened to the app, this
# machine must not be left with nothing holding the screen.
lock.grab_input()
_logger.warning("Re-took the X grab from the workout app.")
return GrabHandoff(release=release, reacquire=reacquire)
def start_workout(lock: LockWindow) -> str:
"""Run the workout app as the lock surface; return a status for the UI.
Never raises: this is wired to a button on a screen the user cannot leave,
so a failure has to come back as a message rather than a traceback that
would leave the grab in an unknown state.
Blocks until the app exits, so it is only safe for a caller with no event
loop to starve. Behind a Tk button use :class:`WorkoutSession` instead:
blocking there freezes the loop, which makes every binding on the lock --
including the escapes -- inert until the app exits.
An earlier version of this docstring claimed the blocking was deliberate,
to stop the recovery watchdog ticking mid-workout. That was wrong:
``release`` stops the watchdog first, and ``stop()`` cancels its timers
outright, so there are no ticks to race with either way.
"""
result = launch_workout_app(lock_grab_handoff(lock))
if not result.launched:
_logger.error("Could not start the PC workout: %s", result.reason)
return f"Could not start the workout: {result.reason}"
_logger.warning("The workout app finished: %s", result.reason)
return "Workout app closed — checking whether it counted…"

View File

@ -0,0 +1,107 @@
"""Waiting for the workout app's ready line on a pipe that may stall.
Split from ``_workout_app`` for the 250-line cap: this is the whole of the
"is the app up yet?" protocol, and it is the part with the sharp edges.
``readline()`` on a pipe blocks until a newline arrives, so polling the clock
around it cannot enforce a timeout -- an app that starts and prints nothing,
or leaves half a line in the buffer, would hold the lock screen forever and
then be misreported as having exited. Everything here exists to make the
deadline real.
"""
from __future__ import annotations
import logging
import select
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Sequence
from typing import IO, Protocol
_Streams = Sequence[IO[str]]
class _Selector(Protocol):
"""``select.select``, narrowed to the readable-wait used here."""
def __call__(
self, rlist: _Streams, wlist: _Streams, xlist: _Streams, timeout: float
) -> tuple[list[IO[str]], list[IO[str]], list[IO[str]]]: ...
class _HasStdout(Protocol):
"""The half of the child process this module reads from."""
stdout: IO[str] | None
__all__ = ["READY_MARKER", "await_ready", "default_selector"]
_logger = logging.getLogger(__name__)
# Printed by linux/runner/my_application.cc once the window is mapped and the
# grab retry loop is running. The supervisor waits for this before releasing.
READY_MARKER = "WORKOUT_LOCK: ready"
default_selector = select.select
def _read_available(stream: IO[str]) -> str:
"""Read whatever the pipe currently holds, without waiting for a newline.
``select`` has already said the stream is readable. Text streams wrap a
binary buffer whose ``read1`` returns the available bytes immediately;
``readline`` would instead block until a newline, which is what let a
half-written line outlive the deadline. Fakes with no ``buffer`` fall back
to a line, which never blocks for them.
"""
buffer = getattr(stream, "buffer", None)
if buffer is None:
return stream.readline()
return buffer.read1().decode("utf-8", "replace")
def await_ready(
child: _HasStdout, timeout: float, selector: _Selector = default_selector
) -> tuple[bool, str]:
"""Wait for the app's ready line, or for it to die first.
Returns ``(ready, why)``; ``why`` distinguishes a crash from a hang, which
need different fixes (a broken build vs. a slow first sync).
The wait is ``select``-based, and reads whatever is available rather than
whole lines, because ``readline()`` on a real pipe blocks until a newline
arrives. Polling the clock around a blocking read cannot enforce a
timeout, so an app that started and printed nothing -- or left a half
written line in the pipe -- would hold the lock screen forever and then be
misreported as having exited.
"""
deadline = time.monotonic() + timeout
seen = ""
while (remaining := deadline - time.monotonic()) > 0:
if child.stdout is None:
return _not_ready("the workout app exited before signalling ready")
readable, _, _ = selector([child.stdout], [], [], remaining)
if not readable:
break
chunk = _read_available(child.stdout)
if not chunk:
# Nothing left to read AND the pipe is at EOF: the app is gone.
return _not_ready("the workout app exited before signalling ready")
# Accumulated, not matched per read: a chunk boundary can fall inside
# the marker, and dropping it would strand a healthy app at the lock.
seen += chunk
if READY_MARKER in seen:
return True, "ready"
reason = f"the workout app never signalled ready within {timeout:.0f}s"
_logger.error("%s (expected %r on stdout).", reason, READY_MARKER)
return False, reason
def _not_ready(reason: str) -> tuple[bool, str]:
"""Log a failed start loudly, so a dead app never fails silently."""
_logger.error(
"%s — the lock screen stays up and the workout was NOT started.", reason
)
return False, reason

View File

@ -0,0 +1,168 @@
"""Running the workout app without freezing the lock's event loop.
``launch_workout_app`` blocks until the app exits, which is fine for a
headless caller but wrong behind a Tk button: while it blocks, the event loop
is not running, so key bindings and buttons on the lock itself are inert. In
the demo lock -- whose whole promise is that Escape always works -- that
turned a "safe" screen into one that needed a hard reboot to leave.
So the phases are driven by ``after`` instead, on the main thread. Every Tk
call (``grab_release``, ``grab_input``) stays there, which a worker thread
could not guarantee, and the loop keeps pumping the entire time the app is up.
This does not weaken the production handoff. The grab is still released only
after the ready line, and the recovery watchdog is still stopped first -- and
because ``stop()`` cancels its timers outright, there are no ticks to race
with while the app runs.
"""
from __future__ import annotations
import logging
import subprocess
from typing import TYPE_CHECKING
from screen_locker._workout_app import ProcessHooks, workout_app_binary
from screen_locker._workout_ready import READY_MARKER
if TYPE_CHECKING:
from collections.abc import Callable
from pathlib import Path
from typing import IO, Protocol
from screen_locker._workout_app import GrabHandoff
class _Child(Protocol):
"""The half of ``subprocess.Popen`` this module drives."""
stdout: IO[str] | None
returncode: int | None
def poll(self) -> int | None: ...
def terminate(self) -> None: ...
__all__ = ["WorkoutSession"]
_logger = logging.getLogger(__name__)
# How often to look at the app while it runs. Short enough that the lock comes
# back promptly when the app exits, long enough not to spin the event loop.
_POLL_MS = 100
# 600 polls x 100ms = 60s, matching the blocking supervisor's own deadline.
_READY_TIMEOUT_POLLS = 600
class WorkoutSession:
"""One supervised run of the workout app, driven by the Tk event loop.
``on_status`` is called with a human-readable line at each transition, so a
failure is visible on the lock screen rather than only in the journal.
"""
def __init__(
self,
handoff: GrabHandoff,
*,
after: Callable[[int, Callable[[], None]], object],
on_status: Callable[[str], None],
binary: Path | None = None,
hooks: ProcessHooks | None = None,
) -> None:
self._handoff = handoff
self._after = after
self._on_status = on_status
self._binary = binary
self._hooks = hooks if hooks is not None else ProcessHooks()
self._remaining = _READY_TIMEOUT_POLLS
self._child: _Child | None = None
self._seen = ""
self._released = False
def start(self) -> None:
"""Spawn the app; the rest happens on later event-loop turns."""
app = self._binary if self._binary is not None else workout_app_binary()
if app is None:
self._fail("the desktop workout app is not built; run flutter build linux")
return
argv = [str(app), "--lock-mode"]
if self._hooks.demo_escape:
argv.append("--demo-escape")
self._child = self._hooks.popen(
argv,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
self._on_status("Starting the workout app…")
self._after(_POLL_MS, self._await_ready)
def _await_ready(self) -> None:
"""Watch for the ready line without ever blocking the loop."""
child = self._child
stdout = getattr(child, "stdout", None)
if stdout is None:
self._fail("the workout app exited before signalling ready")
return
# Zero timeout: ask what is there right now and return to the loop.
readable, _, _ = self._hooks.selector([stdout], [], [], 0)
if readable:
chunk = _read_available(stdout)
if not chunk:
self._fail("the workout app exited before signalling ready")
return
self._seen += chunk
if READY_MARKER in self._seen:
self._release_and_watch()
return
self._remaining -= 1
if self._remaining <= 0:
# Never release to a window that may not be up.
child.terminate()
self._fail("the workout app never signalled ready in time")
return
self._after(_POLL_MS, self._await_ready)
def _release_and_watch(self) -> None:
self._handoff.release()
self._released = True
self._on_status("The workout app has the screen.")
self._after(_POLL_MS, self._watch_until_exit)
def _watch_until_exit(self) -> None:
if self._child.poll() is None:
self._after(_POLL_MS, self._watch_until_exit)
return
self.finish()
def finish(self) -> None:
"""Take the screen back. Idempotent, so an early abort is safe."""
if self._released:
self._released = False
self._handoff.reacquire()
code = getattr(self._child, "returncode", None)
_logger.warning("The workout app exited with code %s.", code)
self._on_status("Workout app closed — checking whether it counted…")
def abort(self) -> None:
"""Kill the app and restore the lock, whatever phase we are in."""
child = self._child
if child is not None and child.poll() is None:
child.terminate()
_logger.warning("Workout app terminated by an explicit abort.")
self.finish()
def _fail(self, reason: str) -> None:
_logger.error("Could not run the PC workout: %s", reason)
self._on_status(f"Could not start the workout: {reason}")
def _read_available(stream: IO[str]) -> str:
"""Read what the pipe holds now; see ``_workout_ready`` for the why."""
buffer = getattr(stream, "buffer", None)
if buffer is None:
return stream.readline()
return buffer.read1().decode("utf-8", "replace")

View File

@ -52,6 +52,7 @@ __all__ = [
"_records_matching",
"_session_records",
"pull_all_manual_records",
"pull_all_session_records",
"pull_synced_workout",
"read_sync_token",
"remote_client",
@ -198,6 +199,30 @@ def pull_synced_workout() -> tuple[dict | None, str | None]:
return payload, None
def pull_all_session_records() -> list[tuple[str, dict]]:
"""Return all synced StrongLifts sessions across every device log.
The session counterpart to :func:`pull_all_manual_records`, and the reason
a workout finished on the PC reaches ``log.json`` without a lock screen
being open: ``pull_synced_workout`` returns only the single newest session
for the live unlock check, which cannot backfill a week.
Best-effort in the same way -- an unconfigured token or a corrupt device
log yields fewer records rather than raising.
"""
client = sync_client()
if client is None:
_logger.warning(
"No sync client (neither a GitHub token nor a Firebase config) — "
"synced StrongLifts sessions cannot be pulled, so a workout done "
"on another device will NOT count toward the weekly minimum.",
)
return []
merged = _merge_device_records(client, _session_records, "sessions")
return [(rid, payload) for rid, (payload, _hlc) in merged.items()]
def pull_all_manual_records() -> list[tuple[str, dict]]:
"""Return all synced manual-workout records across every device log.

View File

@ -131,3 +131,68 @@ class TestIngestSyncedManualWorkouts:
locker._credit_ingested_manual_workout(entry, prior)
assert locker.workout_data == entry
apply_credit.assert_called_once_with(prior)
class TestIngestSyncedSessions:
"""Tests for _ingest_synced_sessions (StrongLifts-session wiring).
The headless ``--sync-only`` path had no session ingest at all, so a
workout finished on the PC earned nothing until a lock screen opened.
"""
def test_logs_each_ingested_session(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
"""Logs each ingested session."""
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker._sync_mixin.pull_all_session_records",
return_value=[("2026-08-21T10:39:24", {})],
),
patch(
"screen_locker._sync_mixin.ingest_session_records",
return_value=["2026-08-21T10:39:24"],
) as ingest,
):
locker._ingest_synced_sessions()
ingest.assert_called_once()
def test_no_sessions_ingests_nothing(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
"""No sessions ingests nothing."""
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker._sync_mixin.pull_all_session_records",
return_value=[],
),
patch(
"screen_locker._sync_mixin.ingest_session_records",
return_value=[],
),
):
locker._ingest_synced_sessions()
def test_credits_a_session_like_a_live_workout(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
"""A synced session earns the same reward a live workout would."""
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker._sync_mixin.pull_all_session_records",
return_value=[],
),
patch(
"screen_locker._sync_mixin.ingest_session_records",
return_value=[],
) as ingest,
):
locker._ingest_synced_sessions()
assert (
ingest.call_args.kwargs["on_ingested"]
== locker._credit_ingested_manual_workout
)
assert locker.workout_data == {}

View File

@ -0,0 +1,177 @@
"""Tests for ingesting synced StrongLifts sessions into log.json."""
from __future__ import annotations
from datetime import datetime, timezone
from typing import TYPE_CHECKING
from unittest.mock import patch
from screen_locker._session_sync import (
build_session_entry,
ingest_session_records,
validate_session,
)
from screen_locker._weekly_check import PC_WORKOUT_TYPE, count_weekly_workouts
from screen_locker._workout_sync import pull_all_session_records
if TYPE_CHECKING:
from pathlib import Path
_DATE = "2026-08-21"
# The ISO week _DATE falls in, for count_weekly_workouts.
_TODAY = datetime(2026, 8, 21, tzinfo=timezone.utc)
def _session(**overrides: object) -> dict:
"""A session payload shaped like the app's WorkoutSession.toJson()."""
payload: dict = {
"workout_type": "B",
"date": _DATE,
"start_time": f"{_DATE}T10:39:24.531831",
"duration_seconds": 6474,
"succeeded": True,
"exercises": [{"name": "Dumbbell Row", "succeeded": True}],
}
payload.update(overrides)
return payload
class TestValidateSession:
"""The PC re-derives the verdict rather than trusting the record."""
def test_accepts_a_long_enough_session(self) -> None:
ok, detail = validate_session(_session())
assert ok
assert "108 min" in detail
def test_rejects_a_session_with_no_exercises(self) -> None:
ok, detail = validate_session(_session(exercises=[]))
assert not ok
assert "no exercises" in detail
def test_rejects_a_non_list_exercises_field(self) -> None:
ok, detail = validate_session(_session(exercises="Dumbbell Row"))
assert not ok
assert "no exercises" in detail
def test_rejects_a_short_session(self) -> None:
ok, detail = validate_session(_session(duration_seconds=10 * 60))
assert not ok
assert "10 min" in detail
def test_rejects_a_non_numeric_duration(self) -> None:
ok, detail = validate_session(_session(duration_seconds="lots"))
assert not ok
assert "not a number" in detail
def test_accepts_exactly_the_hidden_accept_threshold(self) -> None:
"""35 min passes; the message still advertises the round 40."""
ok, _ = validate_session(_session(duration_seconds=35 * 60))
assert ok
def test_rejects_just_below_the_accept_threshold(self) -> None:
ok, detail = validate_session(_session(duration_seconds=34 * 60 + 59))
assert not ok
# The real bar (35) must never leak into a user-visible string.
assert "35" not in detail
assert "40 min" in detail
class TestBuildSessionEntry:
"""The entry names the PC as the source, never the phone."""
def test_marks_the_workout_as_pc_verified(self) -> None:
entry = build_session_entry(_session(), "108 min")
assert entry["type"] == PC_WORKOUT_TYPE
assert entry["type"] != "phone_verified"
def test_describes_the_workout_and_its_outcome(self) -> None:
entry = build_session_entry(_session(), "108 min")
assert "workout B" in entry["source"]
assert "all succeeded" in entry["source"]
def test_reports_a_partial_workout_as_partial(self) -> None:
entry = build_session_entry(_session(succeeded=False), "107 min")
assert "partial" in entry["source"]
def test_carries_the_duration_and_record_id(self) -> None:
entry = build_session_entry(_session(), "108 min")
assert entry["duration_minutes"] == "107.9"
assert entry["sync_record_id"] == f"{_DATE}T10:39:24.531831"
class TestIngestSessionRecords:
"""Ingestion is idempotent and credits only real workouts."""
def test_appends_a_verified_session_under_its_own_date(
self, tmp_path: Path
) -> None:
log = tmp_path / "log.json"
ingested = ingest_session_records(log, [("r1", _session())])
assert ingested == ["r1"]
assert count_weekly_workouts(log, today=_TODAY) == 1
def test_is_idempotent_across_repeated_syncs(self, tmp_path: Path) -> None:
"""The 15-minute timer re-sees every record; it must not re-credit."""
log = tmp_path / "log.json"
records = [("r1", _session())]
assert ingest_session_records(log, records) == ["r1"]
assert ingest_session_records(log, records) == []
assert count_weekly_workouts(log, today=_TODAY) == 1
def test_skips_a_session_with_no_date(self, tmp_path: Path) -> None:
payload = _session()
del payload["date"]
assert ingest_session_records(tmp_path / "log.json", [("r1", payload)]) == []
def test_skips_a_session_whose_date_is_not_a_string(self, tmp_path: Path) -> None:
assert (
ingest_session_records(tmp_path / "log.json", [("r1", _session(date=7))])
== []
)
def test_skips_a_session_that_fails_validation(self, tmp_path: Path) -> None:
log = tmp_path / "log.json"
short = _session(duration_seconds=60)
assert ingest_session_records(log, [("r1", short)]) == []
assert count_weekly_workouts(log, today=_TODAY) == 0
def test_calls_back_for_each_newly_ingested_session(self, tmp_path: Path) -> None:
seen: list[tuple[dict, list]] = []
ingest_session_records(
tmp_path / "log.json",
[("r1", _session())],
on_ingested=lambda entry, prior: seen.append((entry, prior)),
)
assert len(seen) == 1
assert seen[0][0]["type"] == PC_WORKOUT_TYPE
assert seen[0][1] == []
def test_does_not_call_back_for_a_duplicate(self, tmp_path: Path) -> None:
log = tmp_path / "log.json"
records = [("r1", _session())]
ingest_session_records(log, records)
seen: list[dict] = []
ingest_session_records(
log, records, on_ingested=lambda entry, _prior: seen.append(entry)
)
assert seen == []
class TestPullAllSessionRecords:
"""Sessions come from every device log, or from none at all."""
def test_returns_nothing_without_a_sync_client(self) -> None:
with patch("screen_locker._workout_sync.sync_client", return_value=None):
assert pull_all_session_records() == []
def test_returns_the_merged_records(self) -> None:
merged = {"r1": (_session(), object())}
with (
patch("screen_locker._workout_sync.sync_client", return_value=object()),
patch(
"screen_locker._workout_sync._merge_device_records",
return_value=merged,
),
):
assert pull_all_session_records() == [("r1", _session())]

View File

@ -0,0 +1,229 @@
"""Tests for supervising the desktop workout app as the lock surface.
The invariant every test here defends: the X grab is released ONLY once the
app has signalled that its own fullscreen window is up. Releasing it to an app
that never started would leave the machine unlocked with the obligation unmet.
"""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from screen_locker._workout_app import (
READY_MARKER,
GrabHandoff,
ProcessHooks,
WorkoutAppResult,
launch_workout_app,
workout_app_binary,
)
if TYPE_CHECKING:
from collections.abc import Sequence
class _FakeStdout:
"""A pipe that yields fixed lines, then EOF."""
def __init__(self, lines: Sequence[str]) -> None:
self._it = iter(lines)
def readline(self) -> str:
return next(self._it, "")
class _FakeChild:
"""A stand-in for the Flutter process."""
def __init__(self, lines: Sequence[str], *, returncode: int = 0) -> None:
self.stdout = _FakeStdout(lines)
self.returncode = returncode
self.terminated = False
self.waited = False
def terminate(self) -> None:
self.terminated = True
def wait(self) -> int:
self.waited = True
return self.returncode
class _Recorder:
"""Records grab release/reacquire in call order."""
def __init__(self) -> None:
self.calls: list[str] = []
def release(self) -> None:
self.calls.append("release")
def reacquire(self) -> None:
self.calls.append("reacquire")
def _always_readable(
rlist: object, _w: object, _x: object, _t: float
) -> tuple[object, list[object], list[object]]:
"""Stand in for select(): the fake pipe is always ready to read."""
return rlist, [], []
def _run(
lines: Sequence[str],
recorder: _Recorder,
*,
child: _FakeChild | None = None,
**kwargs: object,
) -> object:
kid = child if child is not None else _FakeChild(lines)
return launch_workout_app(
GrabHandoff(release=recorder.release, reacquire=recorder.reacquire),
binary=Path("/nonexistent/workout_app"),
hooks=ProcessHooks(popen=lambda *_a, **_k: kid, selector=_always_readable),
**kwargs,
)
class TestLaunchWorkoutApp:
"""The handoff, and every way it can fail safely."""
def test_releases_the_grab_once_the_app_is_ready(self) -> None:
recorder = _Recorder()
result = _run([f"{READY_MARKER}\n"], recorder)
assert result.launched
assert recorder.calls == ["release", "reacquire"]
def test_tolerates_output_before_the_ready_line(self) -> None:
"""Flutter prints Mesa/Impeller noise before anything of ours."""
recorder = _Recorder()
result = _run(["MESA-EGL: warning\n", f"{READY_MARKER}\n"], recorder)
assert result.launched
assert "release" in recorder.calls
def test_never_releases_when_the_app_dies_before_ready(self) -> None:
"""The invariant: a dead app must not be handed the screen."""
recorder = _Recorder()
result = _run([], recorder)
assert not result.launched
assert "release" not in recorder.calls
assert "exited before signalling ready" in result.reason
def test_terminates_an_app_that_never_signals_ready(self) -> None:
recorder = _Recorder()
child = _FakeChild([])
_run([], recorder, child=child)
assert child.terminated
def test_reports_a_hang_differently_from_a_crash(self) -> None:
"""A slow first sync and a broken build need different fixes."""
recorder = _Recorder()
# Never EOFs and never readies: readline keeps returning noise.
child = _FakeChild(["noise\n"] * 10_000)
result = _run([], recorder, child=child, ready_timeout=0.0)
assert not result.launched
assert "never signalled ready" in result.reason
assert "release" not in recorder.calls
def test_times_out_on_an_app_that_starts_but_prints_nothing(self) -> None:
"""The regression: a silent live app must not hold the lock forever.
``readline()`` on a real pipe blocks, so the timeout can only be
enforced by waiting on the pipe rather than polling the clock.
"""
recorder = _Recorder()
child = _FakeChild([])
def _never_readable(
_r: object, _w: object, _x: object, _t: float
) -> tuple[list[object], list[object], list[object]]:
return [], [], []
result = launch_workout_app(
GrabHandoff(release=recorder.release, reacquire=recorder.reacquire),
binary=Path("/nonexistent/workout_app"),
hooks=ProcessHooks(popen=lambda *_a, **_k: child, selector=_never_readable),
ready_timeout=5.0,
)
assert not result.launched
assert "never signalled ready" in result.reason
assert "release" not in recorder.calls
assert child.terminated
def test_reacquires_the_grab_even_when_the_app_crashes(self) -> None:
"""However the app exits, something must hold the screen after."""
recorder = _Recorder()
child = _FakeChild([f"{READY_MARKER}\n"], returncode=-15)
result = _run([], recorder, child=child)
assert recorder.calls == ["release", "reacquire"]
assert "-15" in result.reason
def test_waits_for_the_app_to_exit(self) -> None:
recorder = _Recorder()
child = _FakeChild([f"{READY_MARKER}\n"])
_run([], recorder, child=child)
assert child.waited
def test_treats_a_missing_stdout_pipe_as_a_dead_app(self) -> None:
"""No pipe means no ready line can ever arrive -- never release."""
recorder = _Recorder()
child = _FakeChild([])
child.stdout = None
result = _run([], recorder, child=child)
assert not result.launched
assert "release" not in recorder.calls
assert child.terminated
def test_says_so_when_the_app_is_not_built(self) -> None:
recorder = _Recorder()
result = launch_workout_app(
GrabHandoff(release=recorder.release, reacquire=recorder.reacquire),
resolve_binary=lambda: None,
hooks=ProcessHooks(
popen=lambda *_a, **_k: _FakeChild([]), selector=_always_readable
),
)
assert not result.launched
assert "not built" in result.reason
assert recorder.calls == []
class TestWorkoutAppBinary:
"""Locating the built bundle."""
def test_returns_none_when_nothing_is_built(self, tmp_path: Path) -> None:
assert workout_app_binary(tmp_path) is None
def test_defaults_to_the_real_repo_root(self) -> None:
"""The no-argument call is what the lock screen actually uses."""
found = workout_app_binary()
assert found is None or found.name == "workout_app"
def test_prefers_release_over_debug(self, tmp_path: Path) -> None:
base = tmp_path / "stronglift_replacement/workout_app/build/linux/x64"
for flavour in ("debug", "release"):
binary = base / flavour / "bundle" / "workout_app"
binary.parent.mkdir(parents=True)
binary.touch()
assert workout_app_binary(tmp_path).parent.parent.name == "release"
def test_falls_back_to_debug(self, tmp_path: Path) -> None:
binary = (
tmp_path
/ "stronglift_replacement/workout_app/build/linux/x64/debug/bundle"
/ "workout_app"
)
binary.parent.mkdir(parents=True)
binary.touch()
assert workout_app_binary(tmp_path) == binary
class TestWorkoutAppResult:
"""The result carries a reason a human can act on."""
def test_repr_shows_the_outcome_and_reason(self) -> None:
"""Logged on failure paths, so it must name why, not just False."""
result = WorkoutAppResult(launched=False, reason="not built")
assert "launched=False" in repr(result)
assert "not built" in repr(result)

View File

@ -0,0 +1,114 @@
"""Tests for lending the lock screen's grab to the workout app.
The invariant: the grab moves, nothing else does. VT switching stays disabled
and the arbiter claim stays held, because ``close()`` would undo both and hand
the user Ctrl+Alt+F2 out of the obligation the lock exists to enforce.
"""
from __future__ import annotations
import tkinter as tk
from screen_locker._workout_handoff import lock_grab_handoff, start_workout
class _FakeRecovery:
"""Stands in for gatelock's watchdog, which re-grabs every 1000ms."""
def __init__(self) -> None:
self.running = True
self.events: list[str] = []
def stop(self) -> None:
self.running = False
self.events.append("stop")
class _FakeLock:
"""A lock window that records the order of grab operations."""
def __init__(self, *, release_raises: bool = False) -> None:
self._recovery = _FakeRecovery()
self.events: list[str] = []
self.closed = False
self._release_raises = release_raises
outer = self
class _Root:
def grab_release(self) -> None:
outer.events.append("grab_release")
if outer._release_raises:
msg = "no grab to release"
raise tk.TclError(msg)
self.root = _Root()
def grab_input(self) -> None:
self.events.append("grab_input")
self._recovery.running = True
def close(self) -> None:
self.closed = True
class TestLockGrabHandoff:
"""Releasing and re-taking, in the only safe order."""
def test_stops_the_watchdog_before_releasing(self) -> None:
"""A tick between release and the app's own grab would steal it back."""
lock = _FakeLock()
lock_grab_handoff(lock).release()
assert lock._recovery.events == ["stop"]
assert lock.events == ["grab_release"]
assert not lock._recovery.running
def test_reacquire_restores_the_grab_and_the_watchdog(self) -> None:
handoff = lock_grab_handoff(lock := _FakeLock())
handoff.release()
handoff.reacquire()
assert lock.events == ["grab_release", "grab_input"]
assert lock._recovery.running
def test_never_closes_the_lock_window(self) -> None:
"""close() also restores VT switching -- that is the escape hatch."""
handoff = lock_grab_handoff(lock := _FakeLock())
handoff.release()
handoff.reacquire()
assert not lock.closed
def test_tolerates_having_no_grab_to_release(self) -> None:
"""Tk raises when releasing a grab we do not hold; not fatal."""
handoff = lock_grab_handoff(lock := _FakeLock(release_raises=True))
handoff.release()
handoff.reacquire()
assert lock.events == ["grab_release", "grab_input"]
class TestStartWorkout:
"""The button handler never raises onto a screen with no way out."""
def test_reports_a_failed_launch_as_a_message(self, monkeypatch: object) -> None:
from screen_locker import _workout_handoff
class _Result:
launched = False
reason = "not built"
monkeypatch.setattr(
_workout_handoff, "launch_workout_app", lambda _h: _Result()
)
message = start_workout(_FakeLock())
assert "Could not start the workout" in message
assert "not built" in message
def test_reports_a_finished_run(self, monkeypatch: object) -> None:
from screen_locker import _workout_handoff
class _Result:
launched = True
reason = "exited with code 0"
monkeypatch.setattr(
_workout_handoff, "launch_workout_app", lambda _h: _Result()
)
assert "checking whether it counted" in start_workout(_FakeLock())

View File

@ -0,0 +1,54 @@
"""Tests for waiting on the workout app's ready line.
These use REAL pipes wherever the behaviour under test is what a blocking
file descriptor does -- the partial-line hang that motivated this module is
invisible to a fake whose ``readline`` returns instantly.
"""
from __future__ import annotations
import io
import os
from screen_locker._workout_ready import READY_MARKER, _read_available, await_ready
class TestReadAvailable:
"""Reading a pipe that may hold a partial line.
These use REAL pipes: the whole point of the code under test is what
``readline`` does to a blocking file descriptor, which a fake cannot show.
"""
def test_reads_a_partial_line_without_waiting_for_a_newline(self) -> None:
"""The regression: ``readline`` would block here until the deadline."""
read_fd, write_fd = os.pipe()
with os.fdopen(read_fd, "r") as reader, os.fdopen(write_fd, "w") as writer:
writer.write("WORKOUT_")
writer.flush()
assert _read_available(reader) == "WORKOUT_"
def test_falls_back_to_readline_without_a_binary_buffer(self) -> None:
"""Plain text objects have no ``.buffer``; a line never blocks there."""
assert _read_available(io.StringIO("one\ntwo\n")) == "one\n"
def test_reassembles_a_marker_split_across_reads(self) -> None:
"""A chunk boundary inside the marker must not strand a healthy app."""
read_fd, write_fd = os.pipe()
with os.fdopen(read_fd, "r") as reader, os.fdopen(write_fd, "w") as writer:
writer.write(f"noise\n{READY_MARKER[:8]}")
writer.flush()
class _Child:
stdout = reader
def _feed(
_r: object, _w: object, _x: object, _t: float
) -> tuple[list[object], list[object], list[object]]:
writer.write(f"{READY_MARKER[8:]}\n")
writer.flush()
return [reader], [], []
ready, why = await_ready(_Child(), 5.0, _feed)
assert ready
assert why == "ready"

View File

@ -0,0 +1,238 @@
"""Tests for running the workout app without freezing the lock's event loop.
The invariant these defend: no phase blocks. Every wait is an ``after``
callback, because a blocked event loop makes the lock's own escapes inert --
which is what once forced a hard reboot out of a "safe" demo.
"""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from screen_locker._workout_app import GrabHandoff, ProcessHooks
from screen_locker._workout_ready import READY_MARKER
from screen_locker._workout_session import WorkoutSession
if TYPE_CHECKING:
from collections.abc import Callable
class _FakeAfter:
"""A drainable stand-in for ``root.after``."""
def __init__(self) -> None:
self.queue: list[Callable[[], None]] = []
def __call__(self, _ms: int, callback: Callable[[], None]) -> object:
self.queue.append(callback)
return object()
def drain(self, limit: int = 5000) -> None:
for _ in range(limit):
if not self.queue:
return
self.queue.pop(0)()
class _FakeStdout:
def __init__(self, chunks: list[str]) -> None:
self._chunks = chunks
def readline(self) -> str:
return self._chunks.pop(0) if self._chunks else ""
class _FakeChild:
def __init__(self, chunks: list[str], *, exits_after: int = 1) -> None:
self.stdout = _FakeStdout(chunks)
self.returncode: int | None = None
self.terminated = False
self._polls = 0
self._exits_after = exits_after
def poll(self) -> int | None:
self._polls += 1
if self._polls >= self._exits_after:
self.returncode = 0
return 0
return None
def terminate(self) -> None:
self.terminated = True
self.returncode = -15
def _session(child: _FakeChild, after: _FakeAfter, calls: list[str]):
return WorkoutSession(
GrabHandoff(
release=lambda: calls.append("release"),
reacquire=lambda: calls.append("reacquire"),
),
after=after,
on_status=lambda text: calls.append(f"status:{text[:20]}"),
binary=Path("/nonexistent/workout_app"),
hooks=ProcessHooks(
popen=lambda *_a, **_k: child,
selector=lambda r, _w, _x, _t: (r, [], []),
),
)
class TestWorkoutSession:
"""Each phase hands control back to the event loop."""
def test_releases_the_grab_only_after_the_ready_line(self) -> None:
after, calls = _FakeAfter(), []
child = _FakeChild([f"{READY_MARKER}\n"], exits_after=2)
_session(child, after, calls).start()
assert "release" not in calls # nothing released synchronously
after.drain()
assert "release" in calls
assert calls.index("release") < calls.index("reacquire")
def test_never_releases_when_the_app_dies_before_ready(self) -> None:
after, calls = _FakeAfter(), []
_session(_FakeChild([]), after, calls).start()
after.drain()
assert "release" not in calls
def test_reacquires_when_the_app_exits(self) -> None:
after, calls = _FakeAfter(), []
child = _FakeChild([f"{READY_MARKER}\n"], exits_after=3)
_session(child, after, calls).start()
after.drain()
assert calls[-2] == "reacquire"
assert "Workout app closed" in calls[-1]
def test_abort_terminates_the_app_and_restores_the_lock(self) -> None:
"""The escape hatch: usable at any point, from outside X."""
after, calls = _FakeAfter(), []
child = _FakeChild([f"{READY_MARKER}\n"], exits_after=99)
session = _session(child, after, calls)
session.start()
for _ in range(3):
if after.queue:
after.queue.pop(0)()
session.abort()
assert child.terminated
assert "reacquire" in calls
def test_abort_before_release_does_not_reacquire(self) -> None:
"""Nothing was lent, so there is nothing to take back."""
after, calls = _FakeAfter(), []
session = _session(_FakeChild([], exits_after=99), after, calls)
session.start()
session.abort()
assert "reacquire" not in calls
def test_times_out_without_ever_blocking(self) -> None:
after, calls = _FakeAfter(), []
child = _FakeChild(["noise\n"] * 10, exits_after=99)
session = _session(child, after, calls)
session._remaining = 3
session.start()
after.drain()
assert child.terminated
assert "release" not in calls
def test_says_so_when_the_app_is_not_built(self) -> None:
after, calls = _FakeAfter(), []
session = WorkoutSession(
GrabHandoff(release=lambda: None, reacquire=lambda: None),
after=after,
on_status=calls.append,
hooks=ProcessHooks(popen=lambda *_a, **_k: None),
)
# Force the unbuilt case regardless of what this machine has built.
session._binary = None
monkey = "screen_locker._workout_session.workout_app_binary"
import unittest.mock
with unittest.mock.patch(monkey, return_value=None):
session.start()
assert any("not built" in c for c in calls)
def test_handles_a_missing_stdout_pipe(self) -> None:
after, calls = _FakeAfter(), []
child = _FakeChild([])
child.stdout = None
_session(child, after, calls).start()
after.drain()
assert "release" not in calls
class TestSessionEdges:
"""Paths a fake pipe or a happy path does not reach."""
def test_keeps_waiting_when_the_pipe_has_nothing_yet(self) -> None:
"""A quiet app is not a dead app; poll again, never block."""
after, calls = _FakeAfter(), []
child = _FakeChild([f"{READY_MARKER}\n"], exits_after=99)
session = WorkoutSession(
GrabHandoff(
release=lambda: calls.append("release"),
reacquire=lambda: calls.append("reacquire"),
),
after=after,
on_status=lambda _t: None,
binary=Path("/nonexistent/workout_app"),
hooks=ProcessHooks(
popen=lambda *_a, **_k: child,
# Never readable: the app is up but silent.
selector=lambda _r, _w, _x, _t: ([], [], []),
),
)
session._remaining = 2
session.start()
after.drain()
assert "release" not in calls
assert child.terminated
def test_abort_with_no_child_is_harmless(self) -> None:
after, calls = _FakeAfter(), []
session = _session(_FakeChild([]), after, calls)
session.abort() # never started
assert len(calls) == 1
assert "Workout app closed" in calls[0]
def test_reads_a_real_pipe_without_waiting_for_a_newline(self) -> None:
"""The production path: a text stream wrapping a binary buffer."""
import os
from screen_locker._workout_session import _read_available
read_fd, write_fd = os.pipe()
with os.fdopen(read_fd, "r") as reader, os.fdopen(write_fd, "w") as writer:
writer.write("WORKOUT_")
writer.flush()
assert _read_available(reader) == "WORKOUT_"
class TestDemoEscapeFlag:
"""The flag that arms the app's own escape hatch."""
def _argv_for(self, *, demo_escape: bool) -> list[str]:
seen: list[list[str]] = []
def _popen(argv: list[str], **_kwargs: object) -> _FakeChild:
seen.append(argv)
return _FakeChild([])
WorkoutSession(
GrabHandoff(release=lambda: None, reacquire=lambda: None),
after=_FakeAfter(),
on_status=lambda _t: None,
binary=Path("/nonexistent/workout_app"),
hooks=ProcessHooks(popen=_popen, demo_escape=demo_escape),
).start()
return seen[0]
def test_production_never_arms_the_hatch(self) -> None:
"""The default must not hand the user a way out of a real lock."""
assert "--demo-escape" not in self._argv_for(demo_escape=False)
def test_demo_arms_the_hatch(self) -> None:
argv = self._argv_for(demo_escape=True)
assert argv[-1] == "--demo-escape"
assert "--lock-mode" in argv

View File

@ -0,0 +1,145 @@
"""Try the workout-app handoff by hand, with one deliberate way out.
The lock itself is the real one: the demo builds the same lock window and the
workout app takes the same exclusive seat grab it takes in production, so what
is under test is the actual locking mechanism, not a softened copy.
Getting the escape right took two wrong tries, both worth recording because
they are the obvious ideas:
1. A Tk key binding cannot work. Once the workout app takes its seat grab
(``gdk_seat_grab`` with ``GDK_SEAT_CAPABILITY_ALL``) X delivers every
keystroke to that app and to nothing else, so no binding in this process
can fire -- no matter how healthy its event loop is.
2. "Escape from another terminal" cannot work either. The app covers the
screen with an override-redirect fullscreen window, so there is no other
terminal to reach and no way to raise one.
An escape therefore has to be handled INSIDE the app, by the app, or it cannot
be reached at all. ``--demo-escape`` (passed here, never by the production
supervisor) arms a key handler in the runner that drops the grab and quits:
Ctrl+Shift+Q
Verified in both directions: with the flag the real app exits on that
keystroke while holding the grab; without it the same keystroke does nothing.
VT switching is left enabled here as a second line of defence, so Ctrl+Alt+F2
also still works -- but the hatch above is the one this demo is testing.
One thing a green run does NOT prove: under the demo's local grab gatelock's
watchdog early-returns and never re-takes the grab, so the 1000ms steal-back
that makes ``_recovery.stop()`` load-bearing in production is not exercised.
python3 scripts/demo_workout_handoff.py
"""
from __future__ import annotations
import logging
from pathlib import Path
import sys
import tkinter as tk
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from gatelock import LockConfig, LockWindow
from screen_locker._workout_app import ProcessHooks, workout_app_binary
from screen_locker._workout_handoff import lock_grab_handoff
from screen_locker._workout_session import WorkoutSession
class _DemoHooks:
"""A minimal lock body: a status line and the two buttons under test."""
def __init__(self) -> None:
self.status: tk.Label | None = None
self.lock: LockWindow | None = None
self.session: WorkoutSession | None = None
def build_surface(self, parent: tk.Misc, _surface: object) -> None:
tk.Label(
parent,
text="DEMO LOCK — local grab, VT switching still enabled",
font=("TkDefaultFont", 18, "bold"),
bg="#1B1D21",
fg="#E6E6E6",
).pack(pady=(120, 8))
self.status = tk.Label(
parent,
text=(
"Press “Start workout”. While the app holds the screen, "
"press Ctrl+Shift+Q to escape."
),
font=("TkDefaultFont", 12),
bg="#1B1D21",
fg="#9AA0A6",
)
self.status.pack(pady=8)
tk.Button(
parent,
text="Start workout",
font=("TkDefaultFont", 14, "bold"),
bg="#3B82F6",
fg="#FFFFFF",
padx=24,
pady=12,
command=self._start,
).pack(pady=16)
tk.Button(
parent,
text="✕ Close demo (or press Escape)",
bg="#EF4444",
fg="#FFFFFF",
command=self._close,
).pack(pady=4)
def _start(self) -> None:
if self.lock is None or self.status is None: # pragma: no cover
return
self.session = WorkoutSession(
lock_grab_handoff(self.lock),
after=self.lock.root.after,
on_status=self._set_status,
# The only escape that can be RECEIVED once the app grabs the seat.
hooks=ProcessHooks(demo_escape=True),
)
self.session.start()
def _set_status(self, text: str) -> None:
if self.status is not None: # pragma: no branch
self.status.config(text=text)
def _close(self) -> None:
if self.lock is not None: # pragma: no cover
self.lock.close()
def teardown_surface(self, _surface: object) -> None: ...
def on_focus_ready(self, _surface: object) -> None: ...
def on_close(self) -> None: ...
def main() -> int:
"""Run the demo lock. Returns non-zero when the app is not built."""
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
if workout_app_binary() is None:
return 1
root = tk.Tk()
root.title("Workout handoff demo")
# Local grab + VT switching enabled: every escape hatch stays open.
config = LockConfig(mode="hard", grab="local", disable_vt=False)
hooks = _DemoHooks()
lock = LockWindow(root, config, hooks)
hooks.lock = lock
lock.setup()
root.bind("<Escape>", lambda _event: lock.close())
lock.grab_input()
lock.run()
return 0
if __name__ == "__main__":
raise SystemExit(main())

83
scripts/disarm_guard.sh Executable file
View File

@ -0,0 +1,83 @@
#!/bin/bash
# ============================================================================
# Disarm guard — shared by arm.sh, install_systemd.sh and install.sh.
#
# Masking the systemd units is not enough on its own. Every install path here
# *copies* unit files into ~/.config/systemd/user, which silently overwrites
# systemd's /dev/null mask symlinks and re-arms enforcement. So a mask alone
# loses to anyone — including a future agent session — running the obvious
# install command by reflex.
#
# The marker file is the deliberate second step: while it exists, no script
# may install units or enable timers. Removing it is an explicit `--rearm`.
#
# Source this file; it defines DISARM_MARKER, report_disarmed,
# refuse_if_disarmed and clear_disarm_marker.
# ============================================================================
# Machine-scoped, deliberately OUTSIDE the repo: a marker inside screen_locker/
# would be erased by `git clean` and is gitignored state anyway. This guards the
# machine, not the checkout.
DISARM_MARKER="${DISARM_MARKER:-$HOME/.local/share/screen_locker/DISARMED}"
readonly DISARM_MARKER
# Print the disarmed banner. Returns 0 when disarmed, 1 when armed.
report_disarmed() {
[[ -f $DISARM_MARKER ]] || return 1
echo "================================================================"
echo " ENFORCEMENT DISARMED - the screen locker will not trigger."
echo "================================================================"
echo "Marker: $DISARM_MARKER"
if [[ -s $DISARM_MARKER ]]; then
sed 's/^/ | /' "$DISARM_MARKER"
fi
return 0
}
# Hard stop for any path that installs units or enables timers.
# Read-only paths (--status) should call report_disarmed instead.
refuse_if_disarmed() {
report_disarmed || return 0
echo "" >&2
echo "Refusing to arm while disarmed. To re-arm deliberately:" >&2
echo " ./arm.sh --rearm" >&2
exit 1
}
# Remove the marker and unmask the units, so a subsequent install can proceed.
# Masking is what `systemctl --user mask` left behind; `cp` would clobber those
# symlinks silently, so unmask explicitly and let systemd report failures.
clear_disarm_marker() {
local unit
local -a masked_units=(
"workout-locker.service"
"workout-locker.timer"
"early-bird-workout-check.timer"
"workout-sync.service"
"workout-sync.timer"
)
if [[ -f $DISARM_MARKER ]]; then
rm -f "$DISARM_MARKER"
echo "Removed disarm marker: $DISARM_MARKER"
fi
for unit in "${masked_units[@]}"; do
# is-enabled prints "masked" for masked units; unmask only those, so a
# normal re-arm does not spew errors about units that were never masked.
if [[ $(systemctl --user is-enabled "$unit" 2>/dev/null) == masked* ]]; then
systemctl --user unmask "$unit"
fi
done
# Restore any unit files that were moved aside when disarming, so `cp` in
# the caller is not the only thing standing between here and a working unit.
local stash
for stash in "$HOME/.config/systemd/user"/disabled-*/; do
[[ -d $stash ]] || continue
echo "Note: preserved unit files remain in $stash"
done
systemctl --user daemon-reload
}

View File

@ -4,7 +4,7 @@
# This file should be version controlled and should not be manually edited.
version:
revision: "559ffa3f75e7402d65a8def9c28389a9b2e6fe42"
revision: "4cf24164269a5ebf0c16a028a00727d0e77bbb05"
channel: "stable"
project_type: app
@ -13,11 +13,14 @@ project_type: app
migration:
platforms:
- platform: root
create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
create_revision: 4cf24164269a5ebf0c16a028a00727d0e77bbb05
base_revision: 4cf24164269a5ebf0c16a028a00727d0e77bbb05
- platform: android
create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
create_revision: 4cf24164269a5ebf0c16a028a00727d0e77bbb05
base_revision: 4cf24164269a5ebf0c16a028a00727d0e77bbb05
- platform: linux
create_revision: 4cf24164269a5ebf0c16a028a00727d0e77bbb05
base_revision: 4cf24164269a5ebf0c16a028a00727d0e77bbb05
# User provided section

View File

@ -1,9 +1,12 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/screens/home_screen.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/http_server_service.dart';
import 'package:workout_app/services/lock_mode.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_device_id.dart';
@ -13,8 +16,18 @@ import 'package:workout_app/ui/theme.dart';
// App bootstrap: permission request, DB init, and a real listening socket —
// platform-channel work that can't run on the CI test host. The pieces it wires
// up are unit-tested individually; the entry point itself is not.
void main() async {
void main(List<String> args) async {
WidgetsFlutterBinding.ensureInitialized();
// Must precede runApp: the UI reads this to decide whether to offer
// any way out of the workout.
lockModeEnabled = parseLockMode(args);
// Linux desktop has no sqflite plugin. The FFI factory runs the same
// schema and migrations against the same SQL, so this is a transport
// swap, not a second storage implementation. Must precede any DB open.
if (Platform.isLinux) {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
}
// Before anything that stamps an Hlc or syncs: until this resolves, the
// device id falls back to the pre-migration constant.
await initSyncDeviceId();
@ -62,7 +75,12 @@ void main() async {
),
);
debugPrint('WorkoutApp: ${restored.reason}');
await HttpServerService.instance.start();
// Android-only transport: it exists so the PC can pull today's workout off
// the phone over LAN. On the PC itself it would bind the very port the PC
// scans, so it is skipped rather than serving the machine to itself.
if (!Platform.isLinux) {
await HttpServerService.instance.start();
}
runApp(const WorkoutApp());
}
// coverage:ignore-end
@ -93,8 +111,17 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
super.dispose();
}
// coverage:ignore-start
// Platform edge, same shape as storage_service_schema's: the suite runs on
// Linux, where this returns on the first line, so the switch below is
// unreachable from any test this repo can run. Covering it would mean
// threading a platform seam through the nine Platform.isLinux checks in
// this app purely for test reachability.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// The socket is never started on Linux (see main()), so there is nothing
// to stop or restart here either.
if (Platform.isLinux) return;
switch (state) {
case AppLifecycleState.paused:
case AppLifecycleState.detached:
@ -106,6 +133,7 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
break;
}
}
// coverage:ignore-end
@override
Widget build(BuildContext context) {

View File

@ -8,6 +8,7 @@ library;
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:workout_app/models/exercise.dart';
@ -29,11 +30,20 @@ class HistoryScreen extends StatefulWidget {
///
/// [httpClient] is injected only by tests, so the synced-workout fetch can
/// be driven without real network — same pattern as `SettingsScreen`.
const HistoryScreen({super.key, this.httpClient});
///
/// [firebaseFactory] is likewise tests-only, and is NOT redundant with
/// [httpClient]: the sync guard short-circuits on "no backend configured",
/// and it asks Firebase that question directly. On a desktop that has a
/// cached refresh token the real factory answers yes, so the guard opens and
/// the fetch goes to the network even with the sync token faked away.
const HistoryScreen({super.key, this.httpClient, this.firebaseFactory});
/// Overrides the HTTP client used to read synced workouts (tests only).
final http.Client? httpClient;
/// Overrides how a Firebase account is discovered (tests only).
final Future<FirebaseRestClient?> Function()? firebaseFactory;
@override
State<HistoryScreen> createState() => _HistoryScreenState();
}
@ -106,6 +116,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
Future<List<Map<String, dynamic>>> _readSyncedPayloads() =>
WorkoutSyncService(
httpClient: widget.httpClient,
firebaseFactory: widget.firebaseFactory,
).readMergedWorkoutPayloads();
Future<void> _pickExercise(String name) async {

View File

@ -11,6 +11,7 @@ import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_result.dart';
import 'package:workout_app/models/set_result.dart';
import 'package:workout_app/models/workout_session.dart';
import 'package:workout_app/services/lock_mode.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_service.dart';
@ -209,10 +210,11 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
@override
Widget build(BuildContext context) {
return PopScope(
// Explicit `canPop: true` makes it clear this scope never blocks the back
// button — a future reader must not assume the default silently.
// ignore: avoid_redundant_argument_values
canPop: true,
// In lock mode the workout IS the lock: popping back to the home screen
// would leave a fullscreen window holding the X grab with no way to
// finish, so the route is pinned until the workout is finished or reset.
// Outside lock mode the back button behaves exactly as it always has.
canPop: !lockModeEnabled,
child: Scaffold(
appBar: _WorkoutAppBar(
title:

View File

@ -12,13 +12,19 @@
/// half. On Android there is no such file.
library;
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
import 'package:workout_app/services/google_sign_in_backend.dart';
part 'firebase_backend_desktop.dart';
part 'firebase_backend_google.dart';
/// The shared `kuhy-syncs` project.
///
/// `databaseUrl` is the **regional** host. The plain `*.firebaseio.com` form
@ -42,14 +48,45 @@ const _secure = FlutterSecureStorage();
// coverage:ignore-start
/// The keystore-backed home for the Firebase refresh token.
SecureCredentialStore credentialStore() => SecureCredentialStore(
read: (key) => _secure.read(key: key),
write: (key, value) => _secure.write(key: key, value: value),
delete: (key) => _secure.delete(key: key),
);
///
/// On Linux the "keystore" is the shared 0600 file above rather than
/// libsecret, so the desktop build signs in with the same durable refresh
/// token the Python side already holds — the account password on this fleet
/// is stale, and only the refresh token still authenticates.
SecureCredentialStore credentialStore() {
if (Platform.isLinux) {
return SecureCredentialStore(
read: (key) async {
final file = _desktopCredentialFile();
if (!file.existsSync()) return null;
return file.readAsString();
},
write: (key, value) async {
final file = _desktopCredentialFile();
await file.parent.create(recursive: true);
await file.writeAsString(value);
// The refresh token is the secret worth protecting; keep it 0600 the
// way the Python half writes it.
await Process.run('chmod', ['600', file.path]);
},
delete: (key) async {
final file = _desktopCredentialFile();
if (file.existsSync()) await file.delete();
},
);
}
return SecureCredentialStore(
read: (key) => _secure.read(key: key),
write: (key, value) => _secure.write(key: key, value: value),
delete: (key) => _secure.delete(key: key),
);
}
/// Reads the per-device account, or null when sync has not been set up.
Future<FirebaseAccount?> loadAccount() async {
// Linux desktop reads the shared PC credential instead of the keystore,
// so a fresh desktop install is connected the moment it starts.
if (Platform.isLinux) return _accountFromDesktopConfig();
try {
return FirebaseAccount.tryParse(
await _secure.read(key: kFirebaseAccountKey),
@ -121,7 +158,15 @@ Future<FirebaseRestClient?> openFirebase() async {
// Passing '' would make firebaseClientFor treat it as a usable
// credential and sign in with it, which fails; null correctly
// means "no password on this device".
password: account.password.isEmpty ? null : account.password,
//
// On Linux the shared refresh token in ~/.config/screen_locker is the
// real credential and short-circuits sign-in before any password is
// consulted. The password in ~/.config/crdt-sync no longer authenticates
// on this fleet, so offering it would only turn a working token into an
// INVALID_LOGIN_CREDENTIALS failure.
password: (Platform.isLinux || account.password.isEmpty)
? null
: account.password,
// Deliberately NOT offering Google here. This path runs from background
// timers and, in some apps, before runApp -- offering it would let a
// non-interactive tick raise the OS account picker with no user action
@ -130,54 +175,6 @@ Future<FirebaseRestClient?> openFirebase() async {
);
}
/// Signs in with Google alone, for a device that has no account stored yet.
///
/// This is the one-tap path: [openFirebase] needs an account in the keystore
/// to know which email to use, but a fresh install has none. The Google token
/// carries the identity, so nothing needs to be typed.
///
/// The account is stored under the email **Firebase reports**, never one read
/// from the UI: a fresh install has no email anywhere on the device, so taking
/// it from a text field would persist an empty account and send the next
/// launch down the password path with ''.
///
/// Returns null when the user dismisses the picker; throws [FirebaseAuthError]
/// when Google succeeds but resolves to a uid the security rules do not pin,
/// which would otherwise authenticate fine and then be denied every read and
/// write with no other symptom.
Future<FirebaseRestClient?> openFirebaseWithGoogle({
Future<String?> Function()? tokenFetcher,
Future<void> Function(FirebaseAccount)? accountSaver,
http.Client? httpClient,
}) async {
final token = await (tokenFetcher ?? googleIdToken)();
if (token == null) return null;
final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey,
store: credentialStore(),
httpClient: httpClient,
);
final email = await auth.signInWithGoogle(
idToken: token,
expectedUid: kSyncUid,
);
// Saved unconditionally, and deliberately not gated on `email`:
// `signInWithIdp` omits that field whenever the Google account hides it, and
// gating the write on it returned a working client while persisting nothing,
// so the next launch looked unconfigured and fell back to GitHub-only.
// The session itself is already durable here -- signInWithGoogle stored the
// refresh token -- and that token, not the address, is the credential.
await (accountSaver ?? saveAccount)(
FirebaseAccount(email: email ?? '', password: ''),
);
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
}
/// Whether this device can actually authenticate against Firebase.
///
/// True when either half of the state is present: the account marker
/// [loadAccount] reads, or a stored refresh token. The token is the half that
/// matters -- it is what signs requests -- so reporting the marker alone calls
/// a working device "not connected", which is exactly how a phone that was in
/// fact syncing looked broken.
Future<bool> isFirebaseConfigured() async {

View File

@ -0,0 +1,85 @@
part of 'firebase_backend.dart';
// The Linux-desktop credential edge. Kept beside the Android keystore path
// rather than in it, because the two answer the same questions from entirely
// different places: Android from the OS keystore, desktop from the 0600 files
// the Python half of this fleet already maintains.
//
// Every function here touches the filesystem or the environment, which the
// `flutter test` host has no meaningful version of -- the same reason the rest
// of firebase_backend.dart is excluded.
// coverage:ignore-start
/// Path of the shared desktop credential cache, matching the Python
/// `crdt_sync.credential_store_for("screen_locker")`.
///
/// Deliberately the SAME file the PC's own sync already uses: the fleet holds
/// one long-lived refresh token per app, and a second copy would drift out of
/// date the first time either half refreshed it.
File _desktopCredentialFile() => File(
p.join(
Platform.environment['HOME'] ?? '',
'.config',
'screen_locker',
'firebase_auth.json',
),
);
/// Reads the shared desktop credential from `~/.config/crdt-sync/`.
///
/// Linux desktop only. The PC half of this fleet (screen_locker, and the
/// `crdt_sync` Python library) already keeps the sync account there as
/// `firebase.json` + `password`, both mode 600, so the desktop build reads
/// that rather than standing up a second credential the user would have to
/// enter and keep in step. It also sidesteps `google_sign_in`, which has no
/// Linux implementation at all.
///
/// Returns null when the files are absent or malformed; the caller then
/// reports the device as not connected, exactly as an empty keystore would.
Future<FirebaseAccount?> _accountFromDesktopConfig() async {
try {
final home = Platform.environment['HOME'];
if (home == null || home.isEmpty) {
log(
'WorkoutApp: HOME is unset — cannot locate ~/.config/crdt-sync, so '
'this desktop is NOT connected to sync.',
level: 1000,
);
return null;
}
final dir = Directory(p.join(home, '.config', 'crdt-sync'));
final configFile = File(p.join(dir.path, 'firebase.json'));
final passwordFile = File(p.join(dir.path, 'password'));
if (!configFile.existsSync() || !passwordFile.existsSync()) {
log(
'WorkoutApp: no desktop sync credential at ${dir.path} '
'(need firebase.json + password) — this desktop is NOT connected to '
'sync, so progression and workouts will not reach any other device.',
level: 1000,
);
return null;
}
final config =
jsonDecode(await configFile.readAsString()) as Map<String, dynamic>;
final email = config['email'] as String?;
if (email == null || email.isEmpty) {
log(
'WorkoutApp: ${configFile.path} has no "email" key — cannot sign in.',
level: 1000,
);
return null;
}
final password = (await passwordFile.readAsString()).trim();
return FirebaseAccount(email: email, password: password);
} on Object catch (error) {
log(
'WorkoutApp: failed to read the desktop sync credential from '
'~/.config/crdt-sync ($error) — treating this desktop as NOT connected.',
level: 1000,
error: error,
);
return null;
}
}
// coverage:ignore-end

View File

@ -0,0 +1,57 @@
part of 'firebase_backend.dart';
// The interactive Google sign-in path. Separate from the rest of the backend
// because it is the only piece that can raise UI, and because it is dead code
// on Linux desktop -- google_sign_in ships no Linux implementation, so the
// desktop build authenticates from the shared refresh token instead.
// coverage:ignore-start
/// Signs in with Google alone, for a device that has no account stored yet.
///
/// This is the one-tap path: [openFirebase] needs an account in the keystore
/// to know which email to use, but a fresh install has none. The Google token
/// carries the identity, so nothing needs to be typed.
///
/// The account is stored under the email **Firebase reports**, never one read
/// from the UI: a fresh install has no email anywhere on the device, so taking
/// it from a text field would persist an empty account and send the next
/// launch down the password path with ''.
///
/// Returns null when the user dismisses the picker; throws [FirebaseAuthError]
/// when Google succeeds but resolves to a uid the security rules do not pin,
/// which would otherwise authenticate fine and then be denied every read and
/// write with no other symptom.
Future<FirebaseRestClient?> openFirebaseWithGoogle({
Future<String?> Function()? tokenFetcher,
Future<void> Function(FirebaseAccount)? accountSaver,
http.Client? httpClient,
}) async {
final token = await (tokenFetcher ?? googleIdToken)();
if (token == null) return null;
final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey,
store: credentialStore(),
httpClient: httpClient,
);
final email = await auth.signInWithGoogle(
idToken: token,
expectedUid: kSyncUid,
);
// Saved unconditionally, and deliberately not gated on `email`:
// `signInWithIdp` omits that field whenever the Google account hides it, and
// gating the write on it returned a working client while persisting nothing,
// so the next launch looked unconfigured and fell back to GitHub-only.
// The session itself is already durable here -- signInWithGoogle stored the
// refresh token -- and that token, not the address, is the credential.
await (accountSaver ?? saveAccount)(
FirebaseAccount(email: email ?? '', password: ''),
);
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
}
/// Whether this device can actually authenticate against Firebase.
///
/// True when either half of the state is present: the account marker
/// [loadAccount] reads, or a stored refresh token. The token is the half that
/// matters -- it is what signs requests -- so reporting the marker alone calls
// coverage:ignore-end

View File

@ -0,0 +1,23 @@
/// Whether this process is acting as the screen lock.
///
/// The Linux runner takes the X grab and drops the window decorations when
/// `--lock-mode` is passed (see `linux/runner/my_application.cc`); this is the
/// Dart half, which removes the ways *out* of the app. Both halves read the
/// same argument so they can never disagree about which mode is live.
///
/// The distinction matters because a lock the user can dismiss is not a lock:
/// with enforcement armed, leaving the workout early has to be impossible
/// rather than merely discouraged.
library;
/// True when the process was started with `--lock-mode`.
///
/// Set once from `main()`; defaults to false so every test and the ordinary
/// windowed launch behave exactly as before.
bool lockModeEnabled = false;
/// The flag the runner and the Dart side agree on.
const String kLockModeFlag = '--lock-mode';
/// Returns whether [args] requests lock mode.
bool parseLockMode(List<String> args) => args.contains(kLockModeFlag);

View File

@ -3,8 +3,10 @@ library;
import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/workout_plan.dart';
@ -103,7 +105,7 @@ class StorageService {
final dbPath =
_testDbPath ??
// coverage:ignore-start
p.join(await getDatabasesPath(), 'workout_app.db');
p.join(await _databaseDirectory(), 'workout_app.db');
// coverage:ignore-end
_db = await openDatabase(
dbPath,

View File

@ -93,6 +93,19 @@ extension StorageServiceSchema on StorageService {
}
}
// coverage:ignore-start
// Platform-channel / filesystem edge: Android answers from the sqflite
// plugin, Linux desktop has no such plugin and uses an XDG directory under
// the FFI factory wired up in main().
Future<String> _databaseDirectory() async {
if (Platform.isLinux) {
final dir = await getApplicationSupportDirectory();
return dir.path;
}
return getDatabasesPath();
}
// coverage:ignore-end
// ── Settings ───────────────────────────────────────────────────────────────
}

View File

@ -0,0 +1 @@
flutter/ephemeral

View File

@ -0,0 +1,128 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "workout_app")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
set(APPLICATION_ID "com.kuhy.workout_app")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(SET CMP0063 NEW)
# Load bundled libraries from the lib/ directory relative to the binary.
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Root filesystem for cross-building.
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
# Define build configuration options.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_14)
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
# Only the install-generated bundle's copy of the executable will launch
# correctly, since the resources must in the right relative locations. To avoid
# people trying to run the unbundled copy, put it in a subdirectory instead of
# the default top-level location.
set_target_properties(${BINARY_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# By default, "installing" just makes a relocatable bundle in the build
# directory.
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
# Start with a clean build bundle directory every time.
install(CODE "
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
" COMPONENT Runtime)
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endforeach(bundled_library)
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()

View File

@ -0,0 +1,88 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.10)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
# which isn't available in 3.10.
function(list_prepend LIST_NAME PREFIX)
set(NEW_LIST "")
foreach(element ${${LIST_NAME}})
list(APPEND NEW_LIST "${PREFIX}${element}")
endforeach(element)
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
endfunction()
# === Flutter Library ===
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"fl_basic_message_channel.h"
"fl_binary_codec.h"
"fl_binary_messenger.h"
"fl_dart_project.h"
"fl_engine.h"
"fl_json_message_codec.h"
"fl_json_method_codec.h"
"fl_message_codec.h"
"fl_method_call.h"
"fl_method_channel.h"
"fl_method_codec.h"
"fl_method_response.h"
"fl_plugin_registrar.h"
"fl_plugin_registry.h"
"fl_standard_message_codec.h"
"fl_standard_method_codec.h"
"fl_string_codec.h"
"fl_value.h"
"fl_view.h"
"flutter_linux.h"
)
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
target_link_libraries(flutter INTERFACE
PkgConfig::GTK
PkgConfig::GLIB
PkgConfig::GIO
)
add_dependencies(flutter flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CMAKE_CURRENT_BINARY_DIR}/_phony_
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
)

View File

@ -0,0 +1,23 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <audioplayers_linux/audioplayers_linux_plugin.h>
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
#include <url_launcher_linux/url_launcher_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin");
audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar);
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
}

View File

@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter_linux/flutter_linux.h>
// Registers Flutter plugins.
void fl_register_plugins(FlPluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_

View File

@ -0,0 +1,27 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
audioplayers_linux
flutter_secure_storage_linux
url_launcher_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)

View File

@ -0,0 +1,27 @@
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME}
"main.cc"
"my_application.cc"
"demo_escape.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the application ID.
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
# Add dependency libraries. Add any application-specific dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")

View File

@ -0,0 +1,39 @@
#include "demo_escape.h"
// Deliberately awkward, so it cannot be hit by accident mid-workout, and
// deliberately NOT Escape: the Dart side already binds Escape for in-app
// navigation, and a demo hatch that shadowed it would change the behaviour
// being tested.
static const guint kEscapeKey = GDK_KEY_Q;
static const GdkModifierType kEscapeMods =
static_cast<GdkModifierType>(GDK_CONTROL_MASK | GDK_SHIFT_MASK);
static gboolean on_key_press(GtkWidget* widget, GdkEventKey* event,
gpointer user_data) {
(void)user_data;
const guint pressed = gdk_keyval_to_upper(event->keyval);
if (pressed != kEscapeKey) return FALSE;
if ((event->state & kEscapeMods) != kEscapeMods) return FALSE;
// Drop the grab before quitting: destroying a window that still holds the
// seat can leave the pointer and keyboard grabbed with nothing to release
// them, which would need exactly the reboot this hatch exists to avoid.
GdkWindow* gdk_window = gtk_widget_get_window(widget);
if (gdk_window != nullptr) {
GdkDisplay* display = gdk_window_get_display(gdk_window);
gdk_seat_ungrab(gdk_display_get_default_seat(display));
}
g_print("WORKOUT_LOCK: demo escape pressed; releasing grab and exiting\n");
fflush(stdout);
gtk_window_close(GTK_WINDOW(widget));
return TRUE;
}
void demo_escape_install(GtkWidget* window, gboolean enabled) {
if (!enabled) return;
gtk_widget_add_events(window, GDK_KEY_PRESS_MASK);
g_signal_connect(window, "key-press-event", G_CALLBACK(on_key_press),
nullptr);
g_print("WORKOUT_LOCK: demo escape armed (Ctrl+Shift+Q)\n");
fflush(stdout);
}

View File

@ -0,0 +1,22 @@
// Demo-only escape hatch for the lock-mode window.
//
// In lock mode the app takes an exclusive seat grab and never releases it, so
// while it is up X delivers every keystroke to this app and to nothing else.
// That is the point in production -- but it also means a human testing the
// handoff cannot reach a terminal, a VT, or the supervisor's own key bindings
// to get out. An escape has to be handled INSIDE the grab, by this app, or it
// cannot be reached at all.
//
// Enabled only by --demo-escape, which the demo harness passes and the
// production supervisor never does. The grab itself is unchanged, so the
// locking mechanism under test is the real one.
#ifndef RUNNER_DEMO_ESCAPE_H_
#define RUNNER_DEMO_ESCAPE_H_
#include <gtk/gtk.h>
// Installs the Ctrl+Shift+Q handler on `window`. No-op unless `enabled`.
void demo_escape_install(GtkWidget* window, gboolean enabled);
#endif // RUNNER_DEMO_ESCAPE_H_

View File

@ -0,0 +1,6 @@
#include "my_application.h"
int main(int argc, char** argv) {
g_autoptr(MyApplication) app = my_application_new();
return g_application_run(G_APPLICATION(app), argc, argv);
}

View File

@ -0,0 +1,258 @@
#include "my_application.h"
#include "demo_escape.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// ---------------------------------------------------------------------------
// Lock mode (--lock-mode): this window IS the screen lock.
//
// The Python locker (screen_locker) still owns the gatelock arbiter claim and
// keeps holding the X grab while we start up, so our first grab attempts fail
// by design. We map fullscreen + override-redirect FIRST -- covering the
// screen before anything is released -- then print the ready line, and retry
// the grab every 200ms until the supervisor drops its own. Ordering matters:
// releasing before we are up would expose the live desktop for the whole of
// Flutter's cold start.
//
// There is no Dart API for override-redirect or an X11 grab, which is why
// this lives in the runner rather than in lib/.
// ---------------------------------------------------------------------------
// Retry cadence for the grab, matching gatelock's _DEFAULT_GRAB_RETRY_MS.
static const guint kGrabRetryMs = 200;
static gboolean lock_mode_enabled = FALSE;
static gboolean lock_grab_held = FALSE;
// Demo harness only; the production supervisor never passes it.
static gboolean demo_escape_enabled = FALSE;
// Takes the exclusive seat grab. Returns TRUE while it should keep retrying.
static gboolean try_seat_grab(gpointer data) {
GtkWidget* window = GTK_WIDGET(data);
GdkWindow* gdk_window = gtk_widget_get_window(window);
if (gdk_window == nullptr) return G_SOURCE_CONTINUE; // not realized yet
GdkDisplay* display = gdk_window_get_display(gdk_window);
GdkSeat* seat = gdk_display_get_default_seat(display);
GdkGrabStatus status =
gdk_seat_grab(seat, gdk_window, GDK_SEAT_CAPABILITY_ALL,
TRUE, nullptr, nullptr, nullptr, nullptr);
if (status != GDK_GRAB_SUCCESS) {
// Expected until the supervisor releases. Never fatal: a lock that gave up
// here would leave the machine unlocked, which is the whole failure mode
// this design exists to prevent.
return G_SOURCE_CONTINUE;
}
lock_grab_held = TRUE;
g_print("WORKOUT_LOCK: grab acquired\n");
return G_SOURCE_REMOVE;
}
// Applies override-redirect + fullscreen, then starts the grab retry loop.
static void enter_lock_mode(GtkWindow* window) {
GtkWidget* widget = GTK_WIDGET(window);
gtk_window_set_decorated(window, FALSE);
gtk_window_set_deletable(window, FALSE);
gtk_window_set_keep_above(window, TRUE);
// An override-redirect window is invisible to the window manager, so
// gtk_window_fullscreen() -- which merely ASKS the WM for fullscreen -- does
// nothing here. Size and place it against the monitor geometry directly,
// otherwise the window keeps its default 1280x720 and leaves an uncovered
// strip of live desktop at the edge of a larger screen.
GdkDisplay* display = gtk_widget_get_display(widget);
GdkMonitor* monitor = gdk_display_get_primary_monitor(display);
if (monitor == nullptr) monitor = gdk_display_get_monitor(display, 0);
if (monitor != nullptr) {
GdkRectangle geometry;
gdk_monitor_get_geometry(monitor, &geometry);
gtk_window_move(window, geometry.x, geometry.y);
gtk_window_resize(window, geometry.width, geometry.height);
}
gtk_window_fullscreen(window);
// Realize (create the X window) without mapping it, so override-redirect is
// set on an unmapped window.
gtk_widget_realize(widget);
GdkWindow* gdk_window = gtk_widget_get_window(widget);
if (gdk_window != nullptr) {
// Bypass the WM entirely: i3 would otherwise re-tile or let the user
// move/close this window.
gdk_window_set_override_redirect(gdk_window, TRUE);
}
g_timeout_add(kGrabRetryMs, try_seat_grab, widget);
}
// Called when first Flutter frame received.
static void first_frame_cb(MyApplication* self, FlView* view) {
GtkWidget* toplevel = gtk_widget_get_toplevel(GTK_WIDGET(view));
if (lock_mode_enabled) {
// Configure BEFORE the first map: toggling override-redirect on a window
// that is already mapped leaves it mapped but never repainting (a blank
// grey rectangle that still holds the grab -- the worst possible lock).
enter_lock_mode(GTK_WINDOW(toplevel));
// Installed before the window is shown, so the hatch is live for every
// keystroke the grab will deliver -- including the first.
demo_escape_install(toplevel, demo_escape_enabled);
gtk_widget_show(toplevel);
// The supervisor releases its own grab only after seeing this line, so the
// screen is already covered by us when it does. Flushed because stdout to
// a pipe is block-buffered and the handshake would otherwise deadlock.
g_print("WORKOUT_LOCK: ready\n");
fflush(stdout);
} else {
gtk_widget_show(toplevel);
}
}
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = !lock_mode_enabled;
#ifdef GDK_WINDOWING_X11
GdkScreen* screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "workout_app");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
} else {
gtk_window_set_title(window, "workout_app");
}
gtk_window_set_default_size(window, 1280, 720);
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(
project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
GdkRGBA background_color;
// Background defaults to black, override it here if necessary, e.g. #00000000
// for transparent.
gdk_rgba_parse(&background_color, "#000000");
fl_view_set_background_color(view, &background_color);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
// Show the window when Flutter renders.
// Requires the view to be realized so we can start rendering.
g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb),
self);
gtk_widget_realize(GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application,
gchar*** arguments,
int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
// --lock-mode is handled here AND forwarded to Dart: the runner needs it
// for the grab, the Dart side for the no-exit UI.
for (gchar** arg = self->dart_entrypoint_arguments; *arg != nullptr; arg++) {
if (g_strcmp0(*arg, "--lock-mode") == 0) {
lock_mode_enabled = TRUE;
} else if (g_strcmp0(*arg, "--demo-escape") == 0) {
demo_escape_enabled = TRUE;
}
}
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GApplication::startup.
static void my_application_startup(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application startup.
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
}
// Implements GApplication::shutdown.
static void my_application_shutdown(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application shutdown.
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line =
my_application_local_command_line;
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
// Set the program name to the application ID, which helps various systems
// like GTK and desktop environments map this running application to its
// corresponding .desktop file. This ensures better integration by allowing
// the application to be recognized beyond its binary name.
g_set_prgname(APPLICATION_ID);
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID, "flags",
G_APPLICATION_NON_UNIQUE, nullptr));
}

View File

@ -0,0 +1,21 @@
#ifndef FLUTTER_MY_APPLICATION_H_
#define FLUTTER_MY_APPLICATION_H_
#include <gtk/gtk.h>
G_DECLARE_FINAL_TYPE(MyApplication,
my_application,
MY,
APPLICATION,
GtkApplication)
/**
* my_application_new:
*
* Creates a new Flutter-based application.
*
* Returns: a new #MyApplication.
*/
MyApplication* my_application_new();
#endif // FLUTTER_MY_APPLICATION_H_

View File

@ -5,10 +5,10 @@ packages:
dependency: transitive
description:
name: archive
sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff
sha256: be169cf6ac481e052c4538715d88841d567150dfe1df38aaec76461a4e7b39f2
url: "https://pub.dev"
source: hosted
version: "4.0.9"
version: "4.1.0"
args:
dependency: transitive
description:
@ -29,58 +29,58 @@ packages:
dependency: "direct main"
description:
name: audioplayers
sha256: "1d0c1b1f2095e59080e2d5046639096417a86687d89778da41b0c9a06d683dfd"
sha256: "2ba4bb2944baacbdd5372ff8254a8e7feb8c10d7739545e392f5605a8f618745"
url: "https://pub.dev"
source: hosted
version: "6.7.0"
version: "6.8.1"
audioplayers_android:
dependency: transitive
description:
name: audioplayers_android
sha256: "60a6728277228413a85755bd3ffd6fab98f6555608923813ce383b190a360605"
sha256: f5ff5b15620fbab8cb0849e9636c48e2b96c3f0f71723bbbe2ad3c761b205f05
url: "https://pub.dev"
source: hosted
version: "5.2.1"
version: "5.3.0"
audioplayers_darwin:
dependency: transitive
description:
name: audioplayers_darwin
sha256: c994b3bb3a921e4904ac40e013fbc94488e824fd7c1de6326f549943b0b44a91
sha256: "1ca553add991384ecf421b9569da850f3ab2472ffb83f6970b0416365abc51be"
url: "https://pub.dev"
source: hosted
version: "6.4.0"
version: "6.5.0"
audioplayers_linux:
dependency: transitive
description:
name: audioplayers_linux
sha256: f75bce1ce864170ef5e6a2c6a61cd3339e1a17ce11e99a25bae4474ea491d001
sha256: "15178b726b7cdee5364d0463c8d445630c4e0fb7d26612b73c767e7d25de9417"
url: "https://pub.dev"
source: hosted
version: "4.2.1"
version: "4.3.0"
audioplayers_platform_interface:
dependency: "direct dev"
description:
name: audioplayers_platform_interface
sha256: "0e2f6a919ab56d0fec272e801abc07b26ae7f31980f912f24af4748763e5a656"
sha256: "765f6f0e6dca55cb471c9483fc77700564b3484d19198aca4ebb5147c6c85acb"
url: "https://pub.dev"
source: hosted
version: "7.1.1"
version: "7.2.0"
audioplayers_web:
dependency: transitive
description:
name: audioplayers_web
sha256: "24a6f258062bd7da8cb2157e83fccb9816a08dd306cbaaa24f9813d071470545"
sha256: ae1e0103c865a03e273f6d13d97b93f5595eac09915729cd5e37ef96e2857319
url: "https://pub.dev"
source: hosted
version: "5.2.1"
version: "5.3.0"
audioplayers_windows:
dependency: transitive
description:
name: audioplayers_windows
sha256: "95f875a96c88c3dbbcb608d4f8288e300b0113d256a81d0b3197fcc18f0dc91a"
sha256: a70ae82bba2dfcb6eb03dd4815d737a2d46d33ea5a96a03f535cfcaac490e413
url: "https://pub.dev"
source: hosted
version: "4.3.1"
version: "4.4.1"
boolean_selector:
dependency: transitive
description:
@ -125,10 +125,10 @@ packages:
dependency: transitive
description:
name: code_assets
sha256: "67cf6d84013f9c601e42a6f8a6b74c4c0d9dc1a1619d775f2b28b732d3551b85"
sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8
url: "https://pub.dev"
source: hosted
version: "1.2.0"
version: "1.2.1"
collection:
dependency: transitive
description:
@ -158,10 +158,10 @@ packages:
dependency: transitive
description:
name: device_info_plus
sha256: "6a642e1daa10190af89ba6cb6386c0df7d071a3592080bfe1e44faa63ae1df65"
sha256: "0891702f96b2e465fe567b7ec448380e6b1c14f60af552a8536d9f583b6b8442"
url: "https://pub.dev"
source: hosted
version: "13.1.0"
version: "13.2.0"
device_info_plus_platform_interface:
dependency: transitive
description:
@ -251,18 +251,18 @@ packages:
dependency: transitive
description:
name: flutter_secure_storage_linux
sha256: a5f35ddab43cf5c8215d2feb4ce1957851f28c5c37e6f04335066a0602087bf5
sha256: "76fa9c841b3b1619fc5b5bc36efc7d158fa2356f223b6caeb1d0c80a54168546"
url: "https://pub.dev"
source: hosted
version: "3.0.1"
version: "3.0.2"
flutter_secure_storage_platform_interface:
dependency: transitive
description:
name: flutter_secure_storage_platform_interface
sha256: "8ceea1223bee3c6ac1a22dabd8feefc550e4729b3675de4b5900f55afcb435d6"
sha256: "788060052712555182aba55ecb5f8b6e5cb9cfe8f776c83249a61fe3ce877db4"
url: "https://pub.dev"
source: hosted
version: "2.0.1"
version: "2.0.3"
flutter_secure_storage_web:
dependency: transitive
description:
@ -349,10 +349,10 @@ packages:
dependency: transitive
description:
name: hooks
sha256: a41af4e8fc687cd6d33de9751eb936c8c0204ebe2bcb6c15ecf707504bf47f31
sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba"
url: "https://pub.dev"
source: hosted
version: "2.0.0"
version: "2.0.2"
http:
dependency: "direct main"
description:
@ -373,26 +373,34 @@ packages:
dependency: transitive
description:
name: image
sha256: "6300175e00616bbc832e2fc91bfa4d776af5402c81c7151bee6905bb08473c52"
sha256: "1976370a4df3091bb0f72409c187ad1f9132a818bc6b95ca59c0bae1c75c688e"
url: "https://pub.dev"
source: hosted
version: "4.9.1"
version: "4.9.2"
jni:
dependency: transitive
description:
name: jni
sha256: c2230682d5bc2362c1c9e8d3c7f406d9cbba23ab3f2e203a025dd47e0fb2e68f
sha256: f038e58b4dc2c9037f50e233175086337e0b305e356d28211bf55f21c504cbd3
url: "https://pub.dev"
source: hosted
version: "1.0.0"
version: "1.0.3"
jni_flutter:
dependency: transitive
description:
name: jni_flutter
sha256: "8b59e590786050b1cd866677dddaf76b1ade5e7bc751abe04b86e84d379d3ba6"
sha256: "7b717011ea40d04fd47c2731d3d1d36eb99eba3435c2753d62489e8c3c9991d5"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
version: "1.0.2"
jni_util:
dependency: transitive
description:
name: jni_util
sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
json_annotation:
dependency: transitive
description:
@ -461,34 +469,34 @@ packages:
dependency: transitive
description:
name: meta
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
sha256: c82594181e3312f3d0695fc95aaaf7758d75b8d4ae2bbecf223b9fd5109a059d
url: "https://pub.dev"
source: hosted
version: "1.19.0"
version: "1.18.3"
native_toolchain_c:
dependency: transitive
description:
name: native_toolchain_c
sha256: f59351d28f49520cd3a74eb1f41c5f19ae15e53c65a3231d14af672e46510a96
sha256: f9c168717100ae6d9fee9ffb0be379bf1f8b26b0f6bcbd4fdddcd931993a6a72
url: "https://pub.dev"
source: hosted
version: "0.19.1"
version: "0.19.2"
objective_c:
dependency: transitive
description:
name: objective_c
sha256: "6cb691c686fa2838c6deb34980d426145c2a5d537491cb83d463c33cdbc726ed"
sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e
url: "https://pub.dev"
source: hosted
version: "9.4.1"
version: "9.5.0"
package_config:
dependency: transitive
description:
name: package_config
sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc
sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d
url: "https://pub.dev"
source: hosted
version: "2.2.0"
version: "3.0.0"
path:
dependency: "direct main"
description:
@ -501,10 +509,10 @@ packages:
dependency: "direct main"
description:
name: path_provider
sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
url: "https://pub.dev"
source: hosted
version: "2.1.5"
version: "2.1.6"
path_provider_android:
dependency: transitive
description:
@ -525,18 +533,18 @@ packages:
dependency: transitive
description:
name: path_provider_linux
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
url: "https://pub.dev"
source: hosted
version: "2.2.1"
version: "2.2.2"
path_provider_platform_interface:
dependency: transitive
description:
name: path_provider_platform_interface
sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
version: "2.1.3"
path_provider_windows:
dependency: transitive
description:
@ -549,10 +557,10 @@ packages:
dependency: "direct main"
description:
name: permission_handler
sha256: ca045d03615023c08ccdb297aad46a9198193666039ddd36d4d85fd0b1864b98
sha256: fe54465bcc62a4564c6e4db337bbaded6c0c0fa6e10487414436d163114784f6
url: "https://pub.dev"
source: hosted
version: "12.0.2"
version: "12.0.3"
permission_handler_android:
dependency: transitive
description:
@ -565,42 +573,34 @@ packages:
dependency: transitive
description:
name: permission_handler_apple
sha256: "447c18bc3c5fdea5c3039f042b2b365fd51e3634f5f6e269ed22c1f00071addc"
sha256: f49cb15a064ea9d974fc7fbb302099353b7b170d07284e86e264561579e5bcf8
url: "https://pub.dev"
source: hosted
version: "9.4.8"
version: "9.6.1"
permission_handler_html:
dependency: transitive
description:
name: permission_handler_html
sha256: "38f000e83355abb3392140f6bc3030660cfaef189e1f87824facb76300b4ff24"
sha256: "6ea98b3f17f60d3b527f2647ed2ab4dc0f6bfe25b22cb1c363f5d8f62252f6ac"
url: "https://pub.dev"
source: hosted
version: "0.1.3+5"
version: "0.1.4+1"
permission_handler_platform_interface:
dependency: transitive
description:
name: permission_handler_platform_interface
sha256: eb99b295153abce5d683cac8c02e22faab63e50679b937fa1bf67d58bb282878
sha256: a5c8a97ecf5616112a5b16d4b8e9ec0e5ae90ef63ac69c0d7b8ae240be760b23
url: "https://pub.dev"
source: hosted
version: "4.3.0"
version: "4.4.0"
permission_handler_windows:
dependency: transitive
description:
name: permission_handler_windows
sha256: "1a790728016f79a41216d88672dbc5df30e686e811ad4e698bfc51f76ad91f1e"
sha256: caeae01858a0a7d2df67a445ac98e1ad95e55a0e77c73044f4e9b1c8c2289cbd
url: "https://pub.dev"
source: hosted
version: "0.2.1"
petitparser:
dependency: transitive
description:
name: petitparser
sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"
url: "https://pub.dev"
source: hosted
version: "7.0.2"
version: "0.2.2"
platform:
dependency: transitive
description:
@ -621,10 +621,10 @@ packages:
dependency: transitive
description:
name: posix
sha256: "185ef7606574f789b40f289c233efa52e96dead518aed988e040a10737febb07"
sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e
url: "https://pub.dev"
source: hosted
version: "6.5.0"
version: "6.5.2"
pub_semver:
dependency: transitive
description:
@ -653,10 +653,10 @@ packages:
dependency: transitive
description:
name: shared_preferences_android
sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53
sha256: "0634e64bd719f89c012f392938e173521f535d3ecaf66558fa94a056d22b5cc7"
url: "https://pub.dev"
source: hosted
version: "2.4.23"
version: "2.4.27"
shared_preferences_foundation:
dependency: transitive
description:
@ -714,58 +714,58 @@ packages:
dependency: "direct main"
description:
name: sqflite
sha256: "564cfed0746fe53140c23b70b308e045c3b31f17778f2f326ccb7d804ea0250a"
sha256: "58a799e6ac17dd32fbab93813d39ed835a75ccc0f8f85b8955fe318c6712b082"
url: "https://pub.dev"
source: hosted
version: "2.4.2+1"
version: "2.4.3"
sqflite_android:
dependency: transitive
description:
name: sqflite_android
sha256: "881e28efdcc9950fd8e9bb42713dcf1103e62a2e7168f23c9338d82db13dec40"
sha256: d0548f9d7422a2dae99ec6f8b0a3074463b132d216fa5ba0d230eeefc901983b
url: "https://pub.dev"
source: hosted
version: "2.4.2+3"
version: "2.4.3"
sqflite_common:
dependency: transitive
description:
name: sqflite_common
sha256: cce558075afe2a83f3fd7fc123acd6b090683e4f23910d44fbb31ecd7800b014
sha256: "5bf6a55c166e73bf651ba7ec3ed486e577620e3dc8f3a9c6a258a8031b624590"
url: "https://pub.dev"
source: hosted
version: "2.5.9"
version: "2.5.11"
sqflite_common_ffi:
dependency: "direct dev"
dependency: "direct main"
description:
name: sqflite_common_ffi
sha256: "3ddad0ec96ad411d5fea45b4912c3cd5743436c9e1890c26a6e688a32d901cae"
sha256: d5564f1308cafbf064be498f2beb1e993e742985a7cca9e2e228d6cbccd84a05
url: "https://pub.dev"
source: hosted
version: "2.4.1"
version: "2.4.2+1"
sqflite_darwin:
dependency: transitive
description:
name: sqflite_darwin
sha256: "279832e5cde3fe99e8571879498c9211f3ca6391b0d818df4e17d9fff5c6ccb3"
sha256: c86ca18b8f666bbf903924687fe21cc16fc385d086005067e26619ca530bef9f
url: "https://pub.dev"
source: hosted
version: "2.4.2"
version: "2.4.3+1"
sqflite_platform_interface:
dependency: transitive
description:
name: sqflite_platform_interface
sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920"
sha256: f84939f84350d92d04416f8bc4dc52d3896aec7716cc9e80cf0146342139dc50
url: "https://pub.dev"
source: hosted
version: "2.4.0"
version: "2.4.1"
sqlite3:
dependency: transitive
description:
name: sqlite3
sha256: "9488c7d2cdb1091c91cacf7e207cff81b28bff8e366f042bad3afe7d34afe189"
sha256: "4c7fe79840389aaeaf05fd093f795b631b5a98e2bd28d54e555c100f4a9c7a1c"
url: "https://pub.dev"
source: hosted
version: "3.3.2"
version: "3.5.2"
stack_trace:
dependency: transitive
description:
@ -803,10 +803,10 @@ packages:
dependency: transitive
description:
name: synchronized
sha256: "93b153dcb6a26dcddee6ca087dd634b53e38c10b5aa163e8e49501a776456153"
sha256: "3a7b5d17422dd0f8d5c6c14feaa5a1c65638b9455f871a96f08437562c046931"
url: "https://pub.dev"
source: hosted
version: "3.4.1"
version: "3.4.1+2"
term_glyph:
dependency: transitive
description:
@ -907,26 +907,26 @@ packages:
dependency: transitive
description:
name: vector_math
sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47
sha256: "1d774bbdf6b72a0b12122fc1560c9c2d2a67db5a4a4cc2bd8a5c990ab20e3188"
url: "https://pub.dev"
source: hosted
version: "2.4.2"
version: "2.4.0"
very_good_analysis:
dependency: "direct dev"
description:
name: very_good_analysis
sha256: d1cb1d66a5aae2c702d68caca6c8347306d35e728fd94555fa21fa0448a972e0
sha256: "481af67ab5877af20325251dc215a4ebac7666a1c8cf09198ffd457bc612b33d"
url: "https://pub.dev"
source: hosted
version: "10.2.0"
version: "10.3.0"
vibration:
dependency: "direct main"
description:
name: vibration
sha256: "9bb06614c69260f8bd11c80fe01ed7988905cf00e3417d656c2647e41f261d87"
sha256: c6c25eb7acadfd231925a60004736443cbf63f1eb5740d6dd83a1bc09cf00f6d
url: "https://pub.dev"
source: hosted
version: "3.1.8"
version: "3.2.0"
vibration_platform_interface:
dependency: transitive
description:
@ -939,10 +939,10 @@ packages:
dependency: transitive
description:
name: vm_service
sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360"
sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0"
url: "https://pub.dev"
source: hosted
version: "15.2.0"
version: "15.3.0"
web:
dependency: transitive
description:
@ -955,10 +955,10 @@ packages:
dependency: transitive
description:
name: win32
sha256: ba6f4bba816c8d7e3c1580e170f3786d216951cc6b94babc3b814c08d2cb2738
sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d
url: "https://pub.dev"
source: hosted
version: "6.3.0"
version: "6.4.0"
win32_registry:
dependency: transitive
description:
@ -975,14 +975,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.0"
xml:
dependency: transitive
description:
name: xml
sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4"
url: "https://pub.dev"
source: hosted
version: "7.0.1"
yaml:
dependency: transitive
description:

View File

@ -27,6 +27,9 @@ dependencies:
permission_handler: ^12.0.0
shared_preferences: ^2.5.3
sqflite: ^2.4.2
# Linux desktop has no sqflite plugin; the FFI factory drives the same
# schema (and already backed the test suite before the desktop target).
sqflite_common_ffi: ^2.4.1
sync_settings_ui:
git:
url: https://github.com/kuhyx/utils
@ -44,7 +47,6 @@ dev_dependencies:
flutter_lints: ^6.0.0
flutter_test:
sdk: flutter
sqflite_common_ffi: ^2.4.1
very_good_analysis: ^10.2.0
flutter:

View File

@ -0,0 +1,43 @@
// The lifecycle observer that starts and stops the phone's HTTP socket.
//
// Linux returns early because main() never starts the socket there, so a
// resume must not start one behind the lock screen's back.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/main.dart';
import 'package:workout_app/services/storage_service.dart';
import 'fake_secure_storage.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() {
// The widget-test host has no Android sqflite plugin; the FFI factory
// drives the same schema, as everywhere else in this suite.
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage();
});
testWidgets('every lifecycle transition is handled without throwing', (
tester,
) async {
await tester.pumpWidget(const WorkoutApp());
await tester.pump();
// Drives didChangeAppLifecycleState for each state the switch names.
for (final state in AppLifecycleState.values) {
tester.binding.handleAppLifecycleStateChanged(state);
await tester.pump();
}
expect(tester.takeException(), isNull);
});
}

View File

@ -23,9 +23,23 @@ Future<void> pumpHistory(WidgetTester tester, Widget w) async {
await tester.pump();
}
Widget wrapHistory({http.Client? httpClient}) => MaterialApp(
/// Wraps the history screen with sync pinned to a known state.
///
/// [firebaseFactory] defaults to "no account", which is what makes these
/// tests independent of the machine they run on. Faking the sync token is not
/// enough on its own: the guard also asks Firebase whether an account exists,
/// and on a desktop holding a cached refresh token the real factory says yes,
/// so the fetch escapes to the network and the test fails with a
/// RemoteSyncError that has nothing to do with the screen.
Widget wrapHistory({
http.Client? httpClient,
Future<FirebaseRestClient?> Function()? firebaseFactory,
}) => MaterialApp(
theme: buildAppTheme(),
home: HistoryScreen(httpClient: httpClient),
home: HistoryScreen(
httpClient: httpClient,
firebaseFactory: firebaseFactory ?? () async => null,
),
);
/// A GitHub mock serving one PC device log holding a run and a manual.

View File

@ -0,0 +1,30 @@
// The flag the Linux runner and the Dart side must agree on.
//
// They read the same argument on purpose: if the runner grabbed the screen
// while Dart still showed its exits, the lock would be dismissible.
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/lock_mode.dart';
void main() {
group('parseLockMode', () {
test('is false for an ordinary windowed launch', () {
expect(parseLockMode([]), isFalse);
});
test('is true when the runner was given the flag', () {
expect(parseLockMode([kLockModeFlag]), isTrue);
});
test('finds the flag alongside the other arguments', () {
expect(parseLockMode(['--demo-escape', kLockModeFlag]), isTrue);
});
test('does not match a different flag', () {
expect(parseLockMode(['--demo-escape']), isFalse);
});
});
test('lockModeEnabled defaults to false, so tests behave as before', () {
expect(lockModeEnabled, isFalse);
});
}

View File

@ -75,6 +75,7 @@ void main() {
);
final payloads = await WorkoutSyncService(
httpClient: httpClient,
firebaseFactory: () async => null,
).readMergedManualPayloads();
expect(payloads, hasLength(1));
expect(payloads.single['cost'], 'NEW');
@ -148,6 +149,7 @@ void main() {
);
final manuals = await WorkoutSyncService(
httpClient: httpClient,
firebaseFactory: () async => null,
).readMergedManualPayloads();
expect(manuals, hasLength(1));
expect(manuals.single['kind'], 'manual_workout');
@ -207,6 +209,7 @@ void main() {
final payloads = await WorkoutSyncService(
httpClient: httpClient,
firebaseFactory: () async => null,
).readMergedManualPayloads();
expect(payloads, hasLength(1));