Compare commits

...

13 Commits

Author SHA1 Message Date
83a5c6b4bc Fix lint in text-free check and glyph tests
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:32:10 +01:00
71a35d6aa1 Guard workout app screens against painted words
Walks every RenderParagraph of the main screens and widget states;
fails on any 2+ letter word besides exercise names and units after a
number. Red on 32a735f (22 of 23), green now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:49 +01:00
2c52408cec Make GitHub mirror screen text-free
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:49 +01:00
17014c6399 Make manual workout form text-free
Fields carry a glyph (old label spoken), group headings are dividers,
budget and date are numbers, errors an error glyph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:49 +01:00
b584c0441b Make settings screen text-free
Headings are glyphs, helper paragraphs are gone, statuses are a
tick/warning glyph with the sentence spoken, the exercise summary is
glyphs + numbers, PC pairing a link glyph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:48 +01:00
5fa160f114 Make history screen text-free
Section headings and the all-workouts entry are glyphs, tiles drop
their word prefixes, chart and calendar dates are numeric, weekday
headers are dots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:48 +01:00
661b293bc2 Make exercise tile and settings sheet text-free
Mode chip shows the mode glyph, paused row a pause glyph + 11.10 date
+ cross. Target change reads x13 / = instead of 13 reps / same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:48 +01:00
1f8f602564 Make workout summary and PC line text-free
Summary title is a trophy/flag glyph, duration mm:ss, save state a
glyph, home button a glyph. The PC line is PC glyph + outcome glyph +
the PC's own numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:48 +01:00
b24718710e Make workout app home screen text-free
Home card: plan letter + state glyph, play-glyph buttons. Sync card
and banner: state glyph, age as 5m/3h/2d, action glyph. Old words
stay as spoken labels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:47 +01:00
e5bfdd9a9a Make the Tk locker screens text-free
Every locker screen, the status window and the credit toast now show
glyphs (screen_locker/_glyphs.py) and numbers, coloured by state.
Sentences that carried a reason (verifier message, sync diagnosis,
sick refusal, form rejection) go to the log at warning instead.
New pre-commit hook text-free runs scripts/verify_text_free.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:20:23 +01:00
3073faa623 Add text-free check for locker screens
Paints every locker screen under Xvfb and fails on any painted word.
Red now: 18 screens. --shots DIR saves one PNG per screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:07:57 +01:00
32a735f168 Drop explanation pages and window titles
textgate scan 319 -> 0: docs/explanations (dropped explain-diff
output, not published, nothing links it), Tk window titles, the
MaterialApp title, '+kg' -> '+' plus the weight icon, and
spoken-only Semantics labels hoisted so the gate sees them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:04:56 +01:00
b6db88f9b9 Make workout app and locker text-free
Painted chrome becomes icons or symbols; old words stay as
spoken labels or code comments. OS window titles kept. Tests
build today from the local day.

Todo: ed07cff3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 00:54:59 +01:00
157 changed files with 3374 additions and 3760 deletions

View File

@ -298,6 +298,13 @@ repos:
files: '^screen_locker/.*\.py$'
pass_filenames: false
require_serial: true
- id: text-free
name: No locker screen paints a word (textgate)
entry: python3 -m scripts.verify_text_free
language: system
files: '^(screen_locker|scripts)/.*\.py$'
pass_filenames: false
require_serial: true
- id: flutter-analyze
name: flutter analyze (workout app)
# env -u GIT_DIR: git exports it to hooks, and flutter shells out to

View File

@ -1,464 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Driving the workout app to 100% test coverage</title>
<style>
:root {
--bg: #ffffff; --fg: #1a1a1a; --muted: #5a5a5a; --card: #f5f5f7;
--border: #e2e2e6; --accent: #4f46e5; --accent-soft: #ede9fe;
--good: #15803d; --good-bg: #dcfce7; --bad: #b91c1c; --bad-bg: #fee2e2;
--code-bg: #f6f8fa; --add: #e6ffec; --add-fg: #04562a; --del: #ffebe9; --del-fg: #82071e;
--pill: #eef2ff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14151a; --fg: #e6e6ea; --muted: #9aa0aa; --card: #1c1e26;
--border: #2a2d38; --accent: #a5b4fc; --accent-soft: #262347;
--good: #4ade80; --good-bg: #16351f; --bad: #f87171; --bad-bg: #3a1a1a;
--code-bg: #1a1c23; --add: #12321f; --add-fg: #7ee2a8; --del: #3a1a1d; --del-fg: #f0a8ae;
--pill: #23263a;
}
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--fg);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
line-height: 1.65; font-size: 17px;
}
.wrap { max-width: min(48rem, 92vw); margin: 0 auto; padding: 2.5rem 0 5rem; }
h1 { font-size: 2rem; line-height: 1.2; margin: 0 0 .3rem; }
h2 { font-size: 1.5rem; margin: 3rem 0 1rem; padding-top: .4rem; border-top: 1px solid var(--border); }
h3 { font-size: 1.15rem; margin: 1.8rem 0 .6rem; }
p, li { color: var(--fg); }
.sub { color: var(--muted); font-size: 1.02rem; margin: 0 0 1.5rem; }
a { color: var(--accent); }
code { background: var(--code-bg); padding: .1em .35em; border-radius: 5px; font-size: .88em;
font-family: "SF Mono", ui-monospace, Menlo, Consolas, monospace; }
pre { background: var(--code-bg); border: 1px solid var(--border); border-radius: 10px;
padding: 1rem; overflow-x: auto; white-space: pre-wrap; word-break: break-word; font-size: .82rem; line-height: 1.55; }
pre code { background: none; padding: 0; font-size: inherit; }
.toc { background: var(--card); border: 1px solid var(--border); border-radius: 12px;
padding: 1rem 1.25rem; margin: 1.5rem 0 0; }
.toc strong { font-size: .8rem; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); }
.toc ol { margin: .5rem 0 0; padding-left: 1.2rem; }
.toc a { text-decoration: none; }
.toc a:hover { text-decoration: underline; }
.card { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 1.25rem; margin: 1.25rem 0; }
.pill { display: inline-block; background: var(--pill); color: var(--accent); font-size: .72rem;
font-weight: 600; padding: .15em .6em; border-radius: 999px; letter-spacing: .03em; }
.add { color: var(--add-fg); background: var(--add); display: block; }
.del { color: var(--del-fg); background: var(--del); display: block; }
.diagram { display: flex; flex-wrap: wrap; gap: .75rem; align-items: stretch; margin: 1.25rem 0; }
.zone { flex: 1 1 220px; border: 2px solid var(--border); border-radius: 12px; padding: 1rem; }
.zone.fake { border-color: var(--bad); }
.zone.real { border-color: var(--good); }
.zone h4 { margin: 0 0 .5rem; font-size: .95rem; }
.zone .tag { font-size: .72rem; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; }
.zone.fake .tag { color: var(--bad); }
.zone.real .tag { color: var(--good); }
.box { border: 1px solid var(--border); border-radius: 8px; background: var(--bg); padding: .5rem .7rem; margin: .5rem 0; font-size: .82rem; }
.flowrow { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; margin: .4rem 0; font-size: .85rem; }
.arrow { color: var(--muted); font-weight: 700; }
.k { font-weight: 600; }
table.cov { width: 100%; border-collapse: collapse; margin: 1rem 0; font-size: .9rem; }
table.cov th, table.cov td { border: 1px solid var(--border); padding: .5rem .6rem; text-align: left; }
table.cov th { background: var(--card); }
table.cov td.num { text-align: right; font-variant-numeric: tabular-nums; }
.good { color: var(--good); font-weight: 600; }
.bad { color: var(--bad); font-weight: 600; }
/* micro-world */
.sim { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 1.25rem; margin: 1.5rem 0; }
.sim h4 { margin: 0 0 .25rem; }
.sim .controls { display: flex; flex-wrap: wrap; gap: .5rem; margin: .9rem 0; }
.seg { display: inline-flex; border: 1px solid var(--border); border-radius: 10px; overflow: hidden; }
.seg button { background: var(--bg); color: var(--fg); border: none; padding: .5rem .85rem; font-size: .85rem; cursor: pointer; }
.seg button.on { background: var(--accent); color: #fff; }
.runbtn { background: var(--accent); color: #fff; border: none; border-radius: 10px; padding: .6rem 1.1rem; font-size: .9rem; font-weight: 600; cursor: pointer; }
.runbtn:active { transform: translateY(1px); }
.stage { margin-top: 1rem; border: 1px dashed var(--border); border-radius: 10px; padding: 1rem; background: var(--bg); }
.step { font-size: .85rem; margin: .3rem 0; opacity: .35; transition: opacity .25s; }
.step.active { opacity: 1; }
.verdict { margin-top: .9rem; font-weight: 700; padding: .6rem .8rem; border-radius: 8px; font-size: .95rem; }
.verdict.pass { background: var(--good-bg); color: var(--good); }
.verdict.fail { background: var(--bad-bg); color: var(--bad); }
.verdict.idle { background: var(--code-bg); color: var(--muted); font-weight: 500; }
/* quiz */
.q { border: 1px solid var(--border); border-radius: 12px; padding: 1.1rem 1.25rem; margin: 1.1rem 0; background: var(--card); }
.q .qhead { font-weight: 600; margin-bottom: .75rem; }
.opt { display: block; width: 100%; text-align: left; background: var(--bg); color: var(--fg);
border: 1px solid var(--border); border-radius: 9px; padding: .6rem .8rem; margin: .4rem 0; font-size: .92rem; cursor: pointer; }
.opt:hover { border-color: var(--accent); }
.opt.correct { background: var(--good-bg); border-color: var(--good); color: var(--good); }
.opt.wrong { background: var(--bad-bg); border-color: var(--bad); color: var(--bad); }
.opt:disabled { cursor: default; }
.rationale { font-size: .85rem; color: var(--muted); margin-top: .5rem; display: none; }
.rationale.show { display: block; }
.score { position: sticky; bottom: 0; background: var(--accent); color: #fff; border-radius: 10px;
padding: .6rem 1rem; margin-top: 1rem; font-weight: 600; text-align: center; }
.mono { font-family: "SF Mono", ui-monospace, Menlo, Consolas, monospace; font-size: .85em; }
</style>
</head>
<body>
<div class="wrap">
<span class="pill">CHANGE EXPLAINED · 2026-07-13</span>
<h1>Driving the workout app to 100% test coverage</h1>
<p class="sub">How a stuck push gate got unblocked — and the Flutter widget-test techniques that made the hard 267 lines of chart, calendar and live-workout UI testable.</p>
<nav class="toc">
<strong>Contents</strong>
<ol>
<li><a href="#background">Background — the gate that never went green</a></li>
<li><a href="#intuition">Intuition — two clocks, one test</a></li>
<li><a href="#code">Code — what actually changed</a></li>
<li><a href="#quiz">Quiz — check your understanding</a></li>
</ol>
</nav>
<h2 id="background">1 · Background</h2>
<p>The repo contains a Flutter phone app, <code>workout_app</code>, that tracks strength workouts and syncs them to a PC. To keep quality high, the project installs a <em>pre-push gate</em>: whenever a commit touches Dart code, pushing runs two checks locally before the push is allowed to leave your machine.</p>
<div class="card">
<div class="flowrow"><span class="k">git push</span> <span class="arrow">→</span> <span class="box"><b>flutter analyze</b> — zero issues (even <span class="mono">info</span>-level)</span></div>
<div class="flowrow"><span class="k"></span> <span class="arrow">→</span> <span class="box"><b>flutter test --coverage</b> — <b>100%</b> of every <code>lib/</code> line, and every file must appear in the report</span></div>
</div>
<p>That second check is strict in two ways. First, the bar is <strong>100%</strong> — not 90%, not "the lines you changed". Second, a helper script (<code>check_flutter_coverage.sh</code>) also fails if any <code>lib/**/*.dart</code> file is <em>missing</em> from the coverage report, so you can't quietly earn 100% by never importing a file into a test.</p>
<p>The catch: this gate had <strong>never once passed</strong> for a Dart commit. It was added while the app was only ~83% covered, so ten commits — an entire phone-to-PC sync feature — sat finished but <em>unpushable</em>, stuck behind 316 uncovered lines. This change closes that gap and ships all of it.</p>
<h3>Where the 316 lines lived</h3>
<table class="cov">
<thead><tr><th>File</th><th class="num">Before</th><th class="num">After</th><th>Nature of the gap</th></tr></thead>
<tbody>
<tr><td>storage_service.dart</td><td class="num">139/165</td><td class="num good">163/163</td><td>migrations, restore, edge branches</td></tr>
<tr><td>home_screen.dart</td><td class="num">117/121</td><td class="num good">121/121</td><td>post-navigation reloads</td></tr>
<tr><td>settings_screen.dart</td><td class="num">243/262</td><td class="num good">262/262</td><td>device-flow branches, steppers</td></tr>
<tr><td>history_screen.dart</td><td class="num">167/308</td><td class="num good">307/307</td><td>whole exercise drill-down + chart</td></tr>
<tr><td>workout_screen.dart</td><td class="num">144/270</td><td class="num good">269/269</td><td>live-workout breaks &amp; finish</td></tr>
</tbody>
</table>
<p>The two screens at the bottom — the history charts/calendar and the live-workout timer UI — held 267 of the 316 lines and were the genuinely hard part. Testing them ran head-first into a subtlety about <em>how time works inside a Flutter widget test</em>. That's the idea worth understanding, so it gets its own section.</p>
<h2 id="intuition">2 · Intuition — two clocks, one test</h2>
<p>A normal <code>testWidgets</code> test does <strong>not</strong> run on real time. Flutter wraps it in a <em>fake clock</em> (<span class="mono">FakeAsync</span>): timers only advance when you explicitly say <code>tester.pump(someDuration)</code>. This is usually wonderful — you can "wait" 3 minutes for a rest timer in a microsecond, deterministically.</p>
<p>But the app's real database, <span class="mono">sqflite</span>, schedules work on <em>real</em> timers and background isolates. Under the fake clock, those never get a chance to finish. So the moment a tapped widget kicks off a database write, you get a landmine:</p>
<div class="diagram">
<div class="zone fake">
<div class="tag">Fake-async zone (default)</div>
<h4>tap outside <span class="mono">runAsync</span></h4>
<div class="box">tap a set → <span class="mono">_tapCircle</span></div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box"><span class="mono">unawaited(_saveActiveSession())</span> → sqflite write</div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box bad">write parks on a real timer the fake clock never ticks</div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box"><b class="bad">✗ "Pending timers" — test fails</b></div>
</div>
<div class="zone real">
<div class="tag">Real loop via <span class="mono">tester.runAsync</span></div>
<h4>tap inside <span class="mono">runAsync</span></h4>
<div class="box">tap a set → <span class="mono">_tapCircle</span></div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box"><span class="mono">unawaited(_saveActiveSession())</span> → sqflite write</div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box good">real event loop runs the write to completion</div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box"><b class="good">✓ no leftover timers — test passes</b></div>
</div>
</div>
<p>So the rule that unlocked the live-workout screen is: <strong>any tap that triggers a database write or starts a <span class="mono">Timer.periodic</span> must be dispatched inside <code>tester.runAsync(...)</code></strong>, which runs that code on the genuine event loop where the work can actually finish. The assertion afterward happens on the fake clock again, so you still get deterministic <code>expect</code>s.</p>
<p>Two corollaries fell out of this while writing the tests:</p>
<ul>
<li><b>A dialog that awaits, then does DB work, is one flow.</b> When you tap "Finish", a confirm dialog opens; confirming resumes <code>_confirmFinish</code> in the <em>same zone the first tap fired in</em>, and that continuation does six sqflite writes. So the <em>whole</em> finish flow — open dialog, confirm, save — has to live in a single <code>runAsync</code> block, not just the confirm tap.</li>
<li><b><code>tester.longPress</code> fights <code>runAsync</code>.</b> It does its own internal fake-clock pumps to time the press, which don't advance inside <code>runAsync</code>. The fix is a manual gesture: <code>startGesture</code>, hold for a real 700 ms, then release — a real-time long-press.</li>
</ul>
<div class="sim" id="sim">
<h4>▶ Micro-world: run the test yourself</h4>
<p style="font-size:.9rem;color:var(--muted);margin:.2rem 0 0">Pick where the tapped code runs and what it does, then dispatch the tap. Watch whether the background work completes or leaks a pending timer.</p>
<div class="controls">
<div>
<div style="font-size:.75rem;color:var(--muted);margin-bottom:.25rem">Dispatch the tap in…</div>
<div class="seg" id="zoneSeg">
<button data-zone="fake" class="on">fake-async (default)</button>
<button data-zone="real">tester.runAsync</button>
</div>
</div>
<div>
<div style="font-size:.75rem;color:var(--muted);margin-bottom:.25rem">The tapped code…</div>
<div class="seg" id="workSeg">
<button data-work="db" class="on">writes to sqflite</button>
<button data-work="timer">starts a break timer</button>
<button data-work="pure">just calls setState</button>
</div>
</div>
</div>
<button class="runbtn" id="runBtn">Dispatch tap →</button>
<div class="stage" id="stage">
<div class="step" id="s1">1 · gesture dispatched, <span class="mono">onTap</span> fires</div>
<div class="step" id="s2">2 · handler runs…</div>
<div class="step" id="s3">3 · background work scheduled…</div>
<div class="step" id="s4">4 · test tears down, checks for leftover timers…</div>
<div class="verdict idle" id="verdict">Choose options and press “Dispatch tap”.</div>
</div>
</div>
<h3>The other half: reaching the code at all</h3>
<p>Zone discipline makes taps <em>survive</em>, but many lines were uncovered simply because the widget was never <em>built</em>. Flutter's <code>ListView</code> lazily builds only what's near the viewport, so the history screen's session tiles and the "DUMBBELL LUNGE" section label — which sit below an 800×600 test fold — never existed in the tree, and their lines stayed cold. The fix is to <code>scrollUntilVisible</code> / <code>ensureVisible</code> them first: scrolling builds them, which both renders and covers them.</p>
<h3>Honest 100%: what <code>coverage:ignore</code> is for</h3>
<p>A few lines genuinely can't run on a Linux CI host, so they're marked <code>coverage:ignore</code> with a stated reason rather than faked. The bar for an ignore is "no reachable test path exists," not "this was annoying to test":</p>
<div class="diagram">
<div class="box" style="flex:1 1 240px"><b>Android/iOS only</b><br><span style="font-size:.85rem;color:var(--muted)"><code>Vibration.vibrate()</code> — <code>hasVibrator()</code> returns <b>false</b> on Linux (no <code>Platform.isAndroid/isIOS</code>), so the body never runs there.</span></div>
<div class="box" style="flex:1 1 240px"><b>Production-only path</b><br><span style="font-size:.85rem;color:var(--muted)">The real on-device DB path (<code>getDatabasesPath()</code>) — tests always inject an in-memory or temp-file path instead.</span></div>
<div class="box" style="flex:1 1 240px"><b>Truly unreachable</b><br><span style="font-size:.85rem;color:var(--muted)">A defensive <code>null</code>-state branch that seeding makes impossible, and a history <code>_load</code> branch only reachable via a path that never calls <code>_load</code>.</span></div>
</div>
<h2 id="code">3 · Code — what actually changed</h2>
<p>The diff is <strong>792 insertions</strong> across ten files, but it splits cleanly into two buckets: a lot of <em>test</em> code, and a handful of tiny <em>production</em> edits that make code reachable from tests. Grouped by concern:</p>
<h3>A · Test seams in production code</h3>
<p>To test the "server not started" placeholder, a private widget had to become public — private widgets can't be constructed from a test file:</p>
<pre><code><span class="del">-class _ServerAddressTile extends StatelessWidget {
- const _ServerAddressTile({required this.addresses});</span>
<span class="add">+/// ...Public so the empty-address fallback can be exercised in a widget test.
+class ServerAddressTile extends StatelessWidget {
+ const ServerAddressTile({required this.addresses, super.key});</span></code></pre>
<p>And to test the schema migration, <code>resetForTesting</code> gained an optional path so a test can hand it a real <em>file</em> DB (in-memory DBs can't be reopened at a new version, which is exactly what an <code>onUpgrade</code> migration needs):</p>
<pre><code><span class="del">- static void resetForTesting() {
- _testDbPath = ':memory:';</span>
<span class="add">+ static void resetForTesting({String dbPath = ':memory:'}) {
+ _testDbPath = dbPath;</span></code></pre>
<h3>B · Justified coverage ignores</h3>
<p>Four small blocks are marked unreachable-on-CI, each with a comment explaining <em>why</em> — for example the haptics call:</p>
<pre><code> if (await Vibration.hasVibrator()) {
<span class="add">+ // Android/iOS-only: hasVibrator() returns false on the Linux test host
+ // (no Platform.isAndroid/isIOS), so this body never runs there.
+ // coverage:ignore-start</span>
unawaited(Vibration.vibrate(duration: 800));
<span class="add">+ // coverage:ignore-end</span>
}</code></pre>
<h3>C · The tests — real behaviour, on the real loop</h3>
<p>The bulk of the change. A representative live-workout test: a tap starts a rest break, and the tap is dispatched through a helper that keeps it on the real event loop so the sqflite write and periodic timer complete cleanly.</p>
<pre><code>Future&lt;void&gt; _tapReal(WidgetTester tester, Finder f) async {
await tester.runAsync(() async {
await tester.tap(f);
await Future&lt;void&gt;.delayed(const Duration(milliseconds: 100));
});
await tester.pump();
}
testWidgets('tapping a set starts a break which Skip cancels', (tester) async {
await _pump(tester, _wrap());
await _tapReal(tester, find.byType(RepCircle).first);
expect(find.byType(BreakBanner), findsOneWidget); // break started
await _tapReal(tester, find.text('Skip'));
expect(find.byType(BreakBanner), findsNothing); // Skip cancelled it
});</code></pre>
<p>And the schema-migration unit test that the new <code>dbPath</code> seam unlocked — build a v1 database on disk, open it through <code>StorageService</code> (which runs at v3), and assert the migration ran:</p>
<pre><code>final oldDb = await databaseFactory.openDatabase(dbFile,
options: OpenDatabaseOptions(version: 1, onCreate: /* v1 schema */));
await oldDb.close();
StorageService.resetForTesting(dbPath: dbFile); // real file, not :memory:
await StorageService.init(); // triggers onUpgrade 1 → 3
expect(await _svc.getNextWorkoutType(), 'A'); // settings table now exists
expect((await _svc.getExerciseState(name))!.successThreshold, 3); // column added</code></pre>
<h3>D · Making analyze green</h3>
<p>The gate also requires a spotless <code>flutter analyze</code>, and it exits non-zero on even an <span class="mono">info</span>. The last commit documents the newly-public field, reshapes the ignore comment so it isn't an over-long line, and reflows one pre-existing 81-char comment. Small, but the push doesn't go through without it.</p>
<h2 id="quiz">4 · Quiz</h2>
<p class="sub">Five questions on the reasoning behind the change. Click an answer to reveal whether it's right and why.</p>
<div id="quiz"></div>
<div class="score" id="score">Score: 0 / 0</div>
</div>
<script>
/* ---------- Micro-world ---------- */
(function () {
var zone = 'fake', work = 'db';
var zoneSeg = document.getElementById('zoneSeg');
var workSeg = document.getElementById('workSeg');
zoneSeg.addEventListener('click', function (e) {
if (!e.target.dataset.zone) return;
zone = e.target.dataset.zone;
[].forEach.call(zoneSeg.children, function (b) { b.classList.toggle('on', b.dataset.zone === zone); });
});
workSeg.addEventListener('click', function (e) {
if (!e.target.dataset.work) return;
work = e.target.dataset.work;
[].forEach.call(workSeg.children, function (b) { b.classList.toggle('on', b.dataset.work === work); });
});
var steps = ['s1', 's2', 's3', 's4'].map(function (id) { return document.getElementById(id); });
var verdict = document.getElementById('verdict');
var timers = [];
function clearTimers() { timers.forEach(clearTimeout); timers = []; }
function labelFor() {
if (work === 'db') return 'schedules a sqflite write (a real timer)';
if (work === 'timer') return 'starts a Timer.periodic rest break';
return 'only calls setState — no async work';
}
document.getElementById('runBtn').addEventListener('click', function () {
clearTimers();
steps.forEach(function (s) { s.classList.remove('active'); });
verdict.className = 'verdict idle';
verdict.textContent = 'Running…';
var leaks = (zone === 'fake') && (work === 'db' || work === 'timer');
var texts = [
'1 · gesture dispatched, onTap fires',
'2 · handler runs in the ' + (zone === 'fake' ? 'fake-async zone' : 'real event loop (runAsync)'),
'3 · handler ' + labelFor(),
'4 · teardown checks for leftover timers…'
];
steps.forEach(function (s, i) {
timers.push(setTimeout(function () {
s.classList.add('active');
s.textContent = texts[i];
}, 350 * (i + 1)));
});
timers.push(setTimeout(function () {
if (leaks) {
verdict.className = 'verdict fail';
verdict.textContent = '✗ FAIL — the ' + (work === 'db' ? 'sqflite write' : 'periodic timer') +
' never completed under the fake clock. "Pending timers" at teardown.';
} else if (zone === 'real' && work !== 'pure') {
verdict.className = 'verdict pass';
verdict.textContent = '✓ PASS — on the real loop the ' + (work === 'db' ? 'write' : 'timer') +
' finished (or was cancelled on dispose). No leftover timers.';
} else {
verdict.className = 'verdict pass';
verdict.textContent = '✓ PASS — pure setState schedules no async work, so there is nothing to leak in either zone.';
}
}, 350 * 5));
});
})();
/* ---------- Quiz ---------- */
var QUESTIONS = [
{
q: "A set-tap test run outside runAsync failed with “pending timers.” What caused it?",
options: [
"Its sqflite write and break timer stayed unfinished in the FakeAsync zone",
"The RepCircle sat below the 800×600 test fold so the simulated tap never landed",
"The setUp block forgot the fake secure-storage handler the tap path needs",
"The BreakBanner threw while building because its remaining value was null"
],
correct: 0,
why: "Under the fake clock, the real timers that sqflite (and Timer.periodic) schedule never advance, so they linger and fail teardown."
},
{
q: "Why does dispatching that same tap inside tester.runAsync fix the failure?",
options: [
"runAsync disables the widget's own timers so none of them can leak later",
"It runs that code on the real event loop, where the DB write completes",
"It auto-mocks the vibration and audio platform channels for the test",
"It forces a pumpAndSettle that drains every pending microtask first"
],
correct: 1,
why: "runAsync escapes the fake clock: the write and timer execute on the genuine event loop and actually finish, leaving nothing pending."
},
{
q: "Why was _ServerAddressTile renamed to the public ServerAddressTile?",
options: [
"A second screen needed to embed the identical tile without copying it",
"The analyzer forbids underscore-prefixed StatelessWidgets in screen files",
"A test file can't build a private widget, so its empty case is untested",
"So HttpServerService could write new addresses straight into the tile"
],
correct: 2,
why: "Only its no-address 'Server not started' branch was uncovered, and a test can't construct a library-private widget — so it had to be exposed."
},
{
q: "Why is the Vibration.vibrate call wrapped in coverage:ignore rather than tested?",
options: [
"Vibration is a side effect that unit tests must never trigger on the build host",
"The vibration plugin channel was too slow to mock reliably in the suite",
"The team decided haptics fall outside the 100% coverage requirement",
"hasVibrator() is false on the Linux CI host, so that body never runs there"
],
correct: 3,
why: "hasVibrator() checks Platform.isAndroid/isIOS via device_info_plus; both are false on Linux, so the guarded body is genuinely unreachable in CI."
},
{
q: "Why did resetForTesting gain an optional dbPath parameter?",
options: [
"To speed the suite up by sharing a single database across every test",
"To let production override the DB location from an environment variable",
"So a test can point at a real file DB and drive the v1→v3 migration",
"To stop the in-memory DB from leaking rows between separate test cases"
],
correct: 2,
why: "onUpgrade only runs when a persisted DB is reopened at a higher version; an in-memory DB can't be reopened, so a real file path was needed."
}
];
(function () {
var host = document.getElementById('quiz');
var scoreEl = document.getElementById('score');
var answered = 0, correct = 0;
QUESTIONS.forEach(function (item, qi) {
var card = document.createElement('div');
card.className = 'q';
var head = document.createElement('div');
head.className = 'qhead';
head.textContent = (qi + 1) + '. ' + item.q;
card.appendChild(head);
var done = false;
var buttons = [];
item.options.forEach(function (opt, oi) {
var b = document.createElement('button');
b.className = 'opt';
b.textContent = opt;
b.addEventListener('click', function () {
if (done) return;
done = true;
answered++;
buttons.forEach(function (bb, bi) {
bb.disabled = true;
if (bi === item.correct) bb.classList.add('correct');
});
if (oi === item.correct) { correct++; }
else { b.classList.add('wrong'); }
rat.classList.add('show');
scoreEl.textContent = 'Score: ' + correct + ' / ' + answered;
});
buttons.push(b);
card.appendChild(b);
});
var rat = document.createElement('div');
rat.className = 'rationale';
rat.textContent = '→ ' + item.why;
card.appendChild(rat);
host.appendChild(card);
});
})();
</script>
</body>
</html>

View File

@ -1,686 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Multiple workouts per day, the sync that never ran, and a ban on silence</title>
<style>
:root {
--bg: #ffffff; --fg: #1a1a1a; --muted: #5b6470; --line: #e2e6ea;
--card: #f6f8fa; --accent: #0b6bcb; --good: #1a7f37; --bad: #b42318;
--warn: #9a6700; --code: #f2f4f7;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14171a; --fg: #e6e9ec; --muted: #9aa4b0; --line: #2b3138;
--card: #1b1f24; --accent: #6cb6ff; --good: #4ac26b; --bad: #ff7b72;
--warn: #d4a72c; --code: #1e2329;
}
}
* { box-sizing: border-box; }
body {
margin: 0 auto; padding: 2rem 1rem 5rem; max-width: min(48rem, 92vw);
background: var(--bg); color: var(--fg); line-height: 1.65;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
}
h1 { font-size: 1.9rem; line-height: 1.25; margin: 0 0 .4rem; }
h2 { font-size: 1.4rem; margin: 2.6rem 0 .8rem; padding-top: .6rem;
border-top: 1px solid var(--line); }
h3 { font-size: 1.08rem; margin: 1.6rem 0 .5rem; }
.sub { color: var(--muted); margin: 0 0 1.5rem; }
a { color: var(--accent); }
code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
code { background: var(--code); padding: .12em .35em; border-radius: 4px;
font-size: .88em; }
.codewrap { overflow-x: auto; background: var(--code); border: 1px solid var(--line);
border-radius: 8px; margin: .8rem 0; }
pre { margin: 0; padding: .85rem 1rem; white-space: pre-wrap; overflow-x: auto;
font-size: .84rem; line-height: 1.5; }
.add { color: var(--good); }
.del { color: var(--bad); }
nav.toc { background: var(--card); border: 1px solid var(--line);
border-radius: 10px; padding: .9rem 1.1rem; margin: 1.5rem 0 2rem; }
nav.toc ol { margin: .4rem 0 0; padding-left: 1.2rem; }
nav.toc li { margin: .25rem 0; }
.card { background: var(--card); border: 1px solid var(--line);
border-radius: 10px; padding: 1rem 1.1rem; margin: 1.2rem 0; }
.note { border-left: 3px solid var(--accent); }
.warnbox { border-left: 3px solid var(--warn); }
.badbox { border-left: 3px solid var(--bad); }
table { border-collapse: collapse; width: 100%; font-size: .9rem; }
.tablewrap { overflow-x: auto; margin: 1rem 0; }
th, td { border: 1px solid var(--line); padding: .45rem .6rem; text-align: left; }
th { background: var(--card); }
/* diagram primitives */
.diagram { margin: 1.2rem 0; }
.row { display: flex; gap: .6rem; align-items: stretch; flex-wrap: wrap; }
.box { border: 1px solid var(--line); border-radius: 8px; padding: .55rem .7rem;
background: var(--card); font-size: .84rem; flex: 1 1 0; min-width: 8.5rem; }
.box .t { font-weight: 600; font-size: .78rem; color: var(--muted);
text-transform: uppercase; letter-spacing: .03em; margin-bottom: .3rem; }
.arrow { display: flex; align-items: center; justify-content: center;
color: var(--muted); font-size: 1.3rem; padding: .2rem 0; }
.pill { display: inline-block; border-radius: 999px; padding: .08em .55em;
font-size: .76rem; border: 1px solid var(--line); }
.pill.v { color: var(--good); border-color: var(--good); }
.pill.m { color: var(--warn); border-color: var(--warn); }
.pill.x { color: var(--bad); border-color: var(--bad); }
/* micro-world */
.sim { border: 1px solid var(--line); border-radius: 10px; padding: 1rem;
background: var(--card); }
.sim .days { display: grid; grid-template-columns: repeat(auto-fit, minmax(6rem, 1fr));
gap: .5rem; margin: .8rem 0; }
.day { border: 1px solid var(--line); border-radius: 8px; padding: .5rem;
background: var(--bg); }
.day h4 { margin: 0 0 .35rem; font-size: .8rem; color: var(--muted); }
.day .slot { font-size: .74rem; margin: .12rem 0; }
.btnrow { display: flex; gap: .3rem; margin-top: .35rem; flex-wrap: wrap; }
button { font: inherit; font-size: .78rem; padding: .2rem .5rem; cursor: pointer;
border: 1px solid var(--line); border-radius: 6px;
background: var(--bg); color: var(--fg); }
button:hover { border-color: var(--accent); }
.verdict { margin-top: .8rem; padding: .7rem .9rem; border-radius: 8px;
background: var(--bg); border: 1px solid var(--line); font-size: .9rem; }
.big { font-size: 1.5rem; font-weight: 700; }
/* quiz */
.q { margin: 1.4rem 0; }
.q .stem { font-weight: 600; margin-bottom: .5rem; }
.opt { display: block; width: 100%; text-align: left; margin: .3rem 0;
padding: .5rem .7rem; border-radius: 8px; border: 1px solid var(--line);
background: var(--bg); color: var(--fg); cursor: pointer; font-size: .9rem; }
.opt:disabled { cursor: default; }
.opt.correct { border-color: var(--good); background: color-mix(in srgb, var(--good) 12%, var(--bg)); }
.opt.wrong { border-color: var(--bad); background: color-mix(in srgb, var(--bad) 12%, var(--bg)); }
.rat { font-size: .85rem; color: var(--muted); margin: .4rem 0 0; display: none; }
.rat.show { display: block; }
#score { font-weight: 600; }
</style>
</head>
<body>
<h1>Multiple workouts per day, the sync that never ran, and a ban on silence</h1>
<p class="sub">
<code>feat/check-phone-runnerup-and-tray</code> · 3 commits · 62 files ·
+2719 / −777 · 2026-07-17
</p>
<nav class="toc">
<strong>Contents</strong>
<ol>
<li><a href="#background">Background — what this thing is</a></li>
<li><a href="#intuition">Intuition — one slot per day</a></li>
<li><a href="#code">Code — the change, by concern</a></li>
<li><a href="#quiz">Quiz</a></li>
</ol>
</nav>
<h2 id="background">1. Background — what this thing is</h2>
<p>
<strong>screen-locker</strong> is a discipline tool. A systemd user service runs
<code>python -m screen_locker.screen_lock --production</code> at login and again
from a timer at 08:30/09:05. If you haven't earned your workout, it throws a
fullscreen Tk window over everything until you do. If you have, it calls
<code>sys.exit(0)</code> and you never see it. That's why "the locker isn't
running" is usually the <em>healthy</em> state, not a fault.
</p>
<p>
It decides using <code>screen_locker/log.json</code> — a gitignored,
HMAC-signed file. Each entry is signed with a key shared across screen-locker,
diet_guard and wake_alarm, so the log can't be quietly hand-edited to fake a
workout. Two things read it constantly: <code>has_weekly_minimum()</code>
(fire the lock or not?) and the reward path (how late may the PC stay on
tonight?).
</p>
<p>
A workout gets in three ways. <span class="pill v">phone_verified</span> — a
StrongLifts session pulled off the phone. <span class="pill v">runnerup_verified</span>
— a real run, parsed from the actual TCX file that RunnerUp writes to
<code>/sdcard/Documents/RunnerUp/</code> and pulled over ADB. And
<span class="pill m">manual_workout</span> — a self-reported evidence form
(squash, table tennis), rate-limited by a budget because nothing verifies it.
That distinction — machine-checked versus self-reported — is the hinge the
whole change turns on.
</p>
<p>
There's also a companion Flutter app on the phone, and a shared GitHub repo
(<code>kuhyx/syncs</code>) holding a small CRDT log per device, so the two
machines can agree on what happened.
</p>
<h3>The shape that caused everything</h3>
<p>
<code>log.json</code> was <strong>keyed by date, one entry per day</strong>.
The writer said so in as many words, and did exactly that:
</p>
<div class="codewrap"><pre><span class="muted"># _log_mixin.py — before</span>
"""...The log is day-keyed: one entry per date."""
logs[date] = entry <span class="del"># a second workout that day OVERWRITES the first</span></pre></div>
<p>
So the file physically could not hold two workouts on one day. Everything
downstream inherited that: <code>count_weekly_workouts</code> iterated the date
keys, so "4 workouts a week" and "4 <em>days</em> a week" were the same
sentence. Nobody had to choose between them, because the data model had
already chosen.
</p>
<h2 id="intuition">2. Intuition — one slot per day</h2>
<p>
The trigger was mundane. On Monday 13 July, kuhy played squash <em>and</em> went
for a 9.8&nbsp;km run. He logged the squash by hand. The run — a real, verified,
TCX-backed run — had nowhere to go. The day already had its slot.
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">Before — one slot</div>
<div>2026-07-13 →</div>
<div style="margin-top:.3rem"><span class="pill m">squash (manual)</span></div>
<div style="margin-top:.4rem; color:var(--bad); font-size:.8rem">
the 9.8 km run would <strong>overwrite</strong> this
</div>
</div>
<div class="box">
<div class="t">After — a list</div>
<div>2026-07-13 → [</div>
<div style="margin-top:.3rem">
<span class="pill m">squash</span> <span class="pill v">run 9.8 km</span>
</div>
<div>]</div>
<div style="margin-top:.4rem; color:var(--good); font-size:.8rem">
both kept, both counted
</div>
</div>
</div>
</div>
<h3>The trap: a list alone is a cheat code</h3>
<p>
Letting a day hold many workouts sounds harmless until you notice what the
lock is <em>for</em>. If every entry counted, you could type four
<span class="pill m">manual</span> entries on a Monday morning, satisfy "4
workouts this week", and never be locked again until Sunday. The whole tool
would be an honour system with extra steps.
</p>
<p>
So the rule isn't "count workouts". It's <strong>count what can't be
faked</strong>:
</p>
<div class="card note">
<strong>The weekly rule.</strong> Each <span class="pill v">verified</span>
workout counts <em>individually</em> — several in one day all count, because a
TCX file and a StrongLifts session are machine-checked.
<span class="pill m">manual</span> entries count <strong>at most once per
day</strong>, however many you write. Self-reports can't inflate the total.
</div>
<p>
Play with it. Add workouts and watch the count and the lock:
</p>
<div class="sim diagram" id="sim">
<div style="font-size:.85rem; color:var(--muted)">
A week (Mon–Thu shown). Weekly minimum is <strong>4</strong>.
</div>
<div class="days" id="days"></div>
<div class="btnrow">
<button id="reset">Reset</button>
<button id="preset-real">Preset: kuhy's Jul 13</button>
<button id="preset-cheat">Preset: the 4-manual cheat</button>
</div>
<div class="verdict" id="verdict"></div>
</div>
<h3>The second trap: the same workout, twice</h3>
<p>
Once a day can hold many workouts, "is this one already here?" stops being
free. Every entry now carries a <code>workout_id</code> — deliberately the
<em>same string</em> the sync layer uses as its record id, so a workout logged
on the PC and the same workout arriving from the phone collapse to one row
instead of two.
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">manual</div>
<code>manual:2026-07-13T14:00</code>
<div style="font-size:.78rem;color:var(--muted);margin-top:.3rem">date + start time</div>
</div>
<div class="box">
<div class="t">runnerup</div>
<code>runnerup_verified:2026-07-13</code>
<div style="font-size:.78rem;color:var(--muted);margin-top:.3rem">type + date</div>
</div>
<div class="box">
<div class="t">phone session</div>
<code>startTime.toIso8601String()</code>
<div style="font-size:.78rem;color:var(--muted);margin-top:.3rem">minted by the app</div>
</div>
</div>
</div>
<h3>The sync had never worked. Not once.</h3>
<p>
While fixing the above, a second thing surfaced. The PC was supposed to
publish its workouts so the phone could see them. It never had —
<code>screen-locker-sync/</code> in the repo contained a single
<code>.gitkeep</code>. Two independent reasons:
</p>
<ol>
<li>
<strong>No token.</strong> <code>push_pc_manuals()</code> opened with
<code>if token is None: return</code> — a bare return, no log line. The PAT
had been saved to the wrong app's config directory. The code knew and said
nothing.
</li>
<li>
<strong>A side-store.</strong> It pushed from <code>manual_sync_log.json</code>,
written only at log-time. So anything recorded before that feature existed —
like the squash — could never publish, no matter how many times it ran.
</li>
</ol>
<p>
The fix for (2) also fixes a category error: <em>derive the push from
<code>log.json</code> itself</em>. The log is the truth; the sync is a
projection of it. Then history publishes automatically, forever, with no
second place to fall out of date.
</p>
<h3>Why silence was the real bug</h3>
<p>
Notice the shape of the failure. Not a crash — a <code>return []</code>. During
the debugging session, <code>pull_all_manual_records()</code> returned
<code>0</code> and it was <strong>impossible to tell</strong> whether the repo
was empty or the call had failed, because the token guard was silent and real
errors logged at <code>INFO</code>. The answer only came from bypassing the
function and hitting the API by hand.
</p>
<div class="card badbox">
<strong>An invisible log is a silent failure with extra steps.</strong> That's
now a rule with teeth: <code>scripts/check_silent_failures.py</code>, a
pre-commit hook. Every <code>except</code> must re-raise or log at
<code>warning</code>+. It found <strong>27 violations across 16 modules</strong>
on its first run — and flagged its own source file too.
</div>
<p>
Worth knowing why a custom AST rule was needed at all: ruff already runs with
<code>select = ["ALL"]</code>, so <code>S110</code> (<code>except: pass</code>)
was <em>already</em> enforced — and the codebase had none. The lethal pattern
wasn't <code>pass</code>. It was <code>except: log.info(...); return []</code>,
which <em>looks</em> handled and no ruff rule catches.
</p>
<h2 id="code">3. Code — the change, by concern</h2>
<h3>3.1 One reader, two shapes</h3>
<p>
A new dependency-free module is the single place that reads the file. Old and
new shapes both load, so a half-migrated file — or a rolled-back writer — is
never a crash. Crucially, wrapping a legacy dict in a list leaves the
<em>signed bytes untouched</em>, so every existing HMAC still verifies with
zero re-signing.
</p>
<div class="codewrap"><pre><span class="add">+ # screen_locker/_log_io.py (new)</span>
+ def load_workout_log(log_file) -> dict[str, list[dict]]:
+ normalized = {}
+ for date, value in read_raw_log(log_file).items():
+ if isinstance(value, list):
+ normalized[date] = [e for e in value if isinstance(e, dict)]
+ elif isinstance(value, dict):
+ normalized[date] = [value] # legacy: wrap, don't rewrite
+ return normalized</pre></div>
<h3>3.2 One writer, which appends and dedups</h3>
<p>
The overwrite becomes an append behind a single chokepoint that returns a
result instead of <code>None</code> — so the caller can tell a genuinely new
workout from a duplicate, and scale the reward accordingly.
</p>
<div class="codewrap"><pre><span class="del">- logs[date] = entry # overwrite</span>
<span class="add">+ workout_id = _derive_workout_id(date, workout_data)
+ if workout_id is not None and any(
+ _entry_workout_id(date, e) == workout_id for e in entries
+ ):
+ return RecordResult(appended=False, prior_entries=prior)
+ entries.append(entry)
+ return RecordResult(appended=True, prior_entries=prior)</span></pre></div>
<div class="card warnbox">
<strong>This bit was written twice.</strong> The first version compared
<code>e.get("workout_id")</code> directly. Legacy entries predate that field,
so theirs is <code>None</code> — un-matchable. The moment the PC started
publishing history, the 08:30 timer ingested the squash back and appended a
<em>second</em> copy of it. It had been dismissed in the plan as a "known
minor, accepted" risk; it fired within the hour, on real data.
<code>_entry_workout_id()</code> now <em>derives</em> an existing entry's id
when it has none, so a legacy row matches its own synced twin.
</div>
<h3>3.3 The counting rule</h3>
<p>
The anti-gaming asymmetry from section 2, in the one function that both the
lock and the banked bonus consult:
</p>
<div class="codewrap"><pre>for date_str, entries in load_workout_log(log_file).items():
...
has_manual = False
for entry in entries:
wtype = entry.get("workout_data", {}).get("type", "")
if wtype in VERIFIED_WORKOUT_TYPES:
count += 1 <span class="add"># each verified workout counts</span>
elif wtype == MANUAL_WORKOUT_TYPE:
has_manual = True
if has_manual:
count += 1 <span class="add"># all of a day's manuals count as one</span></pre></div>
<h3>3.4 The reward, with two guards</h3>
<p>
<code>_apply_workout_credit</code> now scales to the day: the first counted
workout earns the base <strong>+2h</strong>; an <em>additional same-day
verified</em> one earns <strong>+1h</strong>; an additional manual earns
nothing. The old "+1h when <code>weekly_count &gt; 4</code>" gate was removed —
weekly volume is the banked bonus's job, and paying for it twice was the bug
hiding in plain sight. The credit fires only if the write actually appended
(<em>id guard</em>) and the entry is dated today (<em>date guard</em>) — so a
back-dated backfill raises the count but never pushes tonight's shutdown.
</p>
<p>
The tests caught a real defect here: the unlock screen still labelled the +1h
<code>#{weekly_count - 4}</code>, which under the new rule can render
<em>negative</em>.
</p>
<h3>3.5 The sync, derived from the log</h3>
<p>
Record id = the workout's own <code>workout_id</code>. HLC = derived from the
entry's own timestamp — which makes a re-push <em>byte-identical</em>, so the
repo never churns. That determinism is what lets the push run on every startup
without turning the sync repo into a commit firehose.
</p>
<div class="codewrap"><pre><span class="add">+ hlc = Hlc.new_tick(_PC_DEVICE_ID, wall_time_ms=_entry_wall_ms(entry, date))
+ log[record_id] = Record(id=record_id, fields={_PAYLOAD_FIELD: (payload, hlc)})</span></pre></div>
<p>
And nothing about it is silent any more:
</p>
<div class="codewrap"><pre><span class="add">+ @dataclass(frozen=True)
+ class PushResult:
+ pushed: bool
+ record_count: int
+ reason: str # always a sentence a human can act on</span></pre></div>
<h3>3.6 Two recoveries, one pattern</h3>
<p>
The phone kept a Keystore token and mirrored it to
<code>/sdcard</code> — but <code>load()</code> only consulted the mirror when
the Keystore was <strong>empty</strong>, never when its token was
present-but-<em>rejected</em>. A stale entry could shadow a good backup forever
while the UI insisted all was well. Now a 401 triggers one retry from the
mirror before anyone is asked to re-authorize.
</p>
<p>
The same pattern then closed a sharper hole. <code>active_session</code> — which
set you're on, and the reps done — lived only in app-private SQLite. A
<code>pm clear</code> wiped it <em>mid-workout</em>, and <code>backup.json</code>
didn't help because it mirrors only <em>completed</em> history. The state had to
be re-entered by hand. The persistence granularity was already right (it saves
on every set tap); only the <em>location</em> was wrong.
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">app-private (wiped)</div>
SQLite <code>active_session</code><br>
Keystore <code>sync.token</code>
</div>
<div class="arrow">→</div>
<div class="box">
<div class="t">/sdcard (survives)</div>
<code>active_session.json</code><br>
<code>sync_token</code><br>
<code>backup.json</code>
</div>
</div>
<p style="font-size:.82rem;color:var(--muted);margin:.5rem 0 0">
On launch, an empty table re-seeds itself from the mirror. Set 4 of the
Romanian Deadlift, reps <code>[8,8,8,8]</code>, survives an uninstall.
</p>
</div>
<h3>3.7 The rule that outlives the fix</h3>
<div class="codewrap"><pre><span class="add">+ # scripts/check_silent_failures.py — pre-commit hook `no-silent-failures`
+ def _handler_is_loud(handler) -> bool:
+ """True if the handler re-raises or logs loudly about the failure."""
+ return any(
+ isinstance(node, ast.Raise) or _is_loud_log_call(node)
+ for node in ast.walk(handler)
+ )</span></pre></div>
<p>
There's deliberately no escape hatch, because <code>noqa</code> is banned
repo-wide. Two ironies for the record: the checker's own docstring contained
the literal string <code>#&nbsp;noqa</code> and tripped the noqa-blocker, and
<code>_log_io.py</code> — written for this very change — violated the new rule.
Both were invisible while untracked, since <code>git ls-files</code> hides
untracked files from the hooks, and only surfaced once committed.
</p>
<h2 id="quiz">4. Quiz</h2>
<p style="color:var(--muted);font-size:.9rem">
Five questions on the reasoning. Score: <span id="score">0 / 0</span>
</p>
<div id="quiz"></div>
<script>
/* ---------------- micro-world: the weekly counting rule ---------------- */
(function () {
const DAYS = ["Mon 13", "Tue 14", "Wed 15", "Thu 16"];
const MIN = 4;
let state = DAYS.map(() => ({ verified: 0, manual: 0 }));
const daysEl = document.getElementById("days");
const verdictEl = document.getElementById("verdict");
function count() {
// Mirrors count_weekly_workouts: each verified counts; manuals cap at 1/day.
return state.reduce((n, d) => n + d.verified + (d.manual > 0 ? 1 : 0), 0);
}
function render() {
daysEl.innerHTML = "";
state.forEach((d, i) => {
const el = document.createElement("div");
el.className = "day";
const contrib = d.verified + (d.manual > 0 ? 1 : 0);
el.innerHTML =
"<h4>" + DAYS[i] + "</h4>" +
'<div class="slot"><span class="pill v">verified</span> ' + d.verified + "</div>" +
'<div class="slot"><span class="pill m">manual</span> ' + d.manual +
(d.manual > 1 ? ' <span style="color:var(--warn)">(capped)</span>' : "") + "</div>" +
'<div class="slot" style="margin-top:.3rem;color:var(--muted)">counts: <strong>' +
contrib + "</strong></div>";
const row = document.createElement("div");
row.className = "btnrow";
const bv = document.createElement("button");
bv.textContent = "+ verified";
bv.onclick = () => { state[i].verified++; render(); };
const bm = document.createElement("button");
bm.textContent = "+ manual";
bm.onclick = () => { state[i].manual++; render(); };
row.append(bv, bm);
el.append(row);
daysEl.append(el);
});
const n = count();
const locked = n < MIN;
verdictEl.innerHTML =
'<div>weekly count: <span class="big">' + n + "</span> / " + MIN + "</div>" +
'<div style="margin-top:.4rem">lock this week: ' +
(locked
? '<span class="pill x">FIRES</span>'
: '<span class="pill v">skipped — minimum met</span>') +
"</div>" +
'<div style="margin-top:.4rem;font-size:.84rem;color:var(--muted)">' +
"Each verified workout adds 1. All of a day's manual entries add 1 between them." +
"</div>";
}
document.getElementById("reset").onclick = () => {
state = DAYS.map(() => ({ verified: 0, manual: 0 })); render();
};
document.getElementById("preset-real").onclick = () => {
// Jul 13: squash (manual) + the 9.8 km run (verified) => that day counts 2.
state = DAYS.map(() => ({ verified: 0, manual: 0 }));
state[0] = { verified: 1, manual: 1 };
render();
};
document.getElementById("preset-cheat").onclick = () => {
// Four self-reports on one morning: the whole point of the cap.
state = DAYS.map(() => ({ verified: 0, manual: 0 }));
state[0] = { verified: 0, manual: 4 };
render();
};
render();
})();
/* ---------------- quiz ---------------- */
(function () {
const QS = [
{
stem: "The log moved from {date: entry} to {date: [entry]}. Why does load_workout_log wrap legacy dict values on read instead of rewriting the file up front?",
opts: [
"A rewrite needs the HMAC key, which is not always available at read time.",
"Wrapping leaves each entry's signed bytes untouched, so old HMACs verify.",
"The file is gitignored, so a rewrite would be lost on the next checkout.",
"SQLite locks the file during reads, so an in-place rewrite may corrupt it."
],
correct: 1,
rat: "Wrapping never changes the bytes compute_entry_hmac signed, so zero re-signing is needed."
},
{
stem: "A single day holds 2 verified workouts and 3 manual ones. What does that day contribute to the weekly count?",
opts: [
"5 — every counted workout counts on its own, as multi/day implies.",
"2 — only machine-verified workouts count toward the weekly total.",
"3 — each verified counts; the manual entries count once in total.",
"1 — the day contributes exactly one, matching the old day-based rule."
],
correct: 2,
rat: "Verified workouts stack (2); all of a day's manual entries collapse to a single 1."
},
{
stem: "Why is each pushed record's HLC derived from the entry's own timestamp rather than the current clock?",
opts: [
"It stops the phone's clock from overriding the PC on same-day workouts.",
"GitHub rejects records whose clock is newer than the commit timestamp.",
"Re-pushing an unchanged log yields identical records, so no churn.",
"crdt_sync requires a wall_time_ms whenever a node id is also supplied."
],
correct: 2,
rat: "Determinism makes the push idempotent, so running it on every startup never spams the repo."
},
{
stem: "The new hook flags silent except handlers. Why did `if token is None: return []` still need fixing by hand?",
opts: [
"It is a guard clause, not an except handler, so the AST rule never sees it.",
"The rule ignores functions whose return type is a list rather than a result.",
"The checker skips files that were untracked when the hook last ran on them.",
"ruff's S110 already covers it, so the custom checker deliberately skips it."
],
correct: 0,
rat: "The checker walks ast.ExceptHandler nodes; a bare guard return is invisible to it."
},
{
stem: "After the PC began publishing history, the Jul 13 squash appeared twice. What went wrong?",
opts: [
"The push minted a fresh workout_id each run, so the dedup never matched.",
"The legacy entry stored no workout_id, so the id comparison found no match.",
"The 08:30 timer ran ingest twice and the second run raced the first write.",
"The manual-sync ingest skipped its record-id check for pre-migration rows."
],
correct: 1,
rat: "Its stored id was None, so it could not match its own synced copy — the id is now derived."
}
];
const quizEl = document.getElementById("quiz");
const scoreEl = document.getElementById("score");
let answered = 0, right = 0;
QS.forEach((q, qi) => {
const wrap = document.createElement("div");
wrap.className = "q";
const stem = document.createElement("div");
stem.className = "stem";
stem.textContent = (qi + 1) + ". " + q.stem;
wrap.append(stem);
const rat = document.createElement("p");
rat.className = "rat";
q.opts.forEach((text, oi) => {
const b = document.createElement("button");
b.className = "opt";
b.textContent = text;
b.onclick = () => {
if (wrap.dataset.done) return;
wrap.dataset.done = "1";
answered++;
if (oi === q.correct) right++;
wrap.querySelectorAll(".opt").forEach((o, i) => {
o.disabled = true;
if (i === q.correct) o.classList.add("correct");
else if (i === oi) o.classList.add("wrong");
});
rat.textContent = (oi === q.correct ? "Correct. " : "Not quite. ") + q.rat;
rat.classList.add("show");
scoreEl.textContent = right + " / " + answered;
};
wrap.append(b);
});
wrap.append(rat);
quizEl.append(wrap);
});
})();
</script>
</body>
</html>

View File

@ -1,686 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Check Phone learns to look backward, and forgives shaky GPS</title>
<style>
:root {
--bg: #ffffff; --fg: #1a1a1a; --muted: #5b6470; --line: #e2e6ea;
--card: #f6f8fa; --accent: #0b6bcb; --good: #1a7f37; --bad: #b42318;
--warn: #9a6700; --code: #f2f4f7;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14171a; --fg: #e6e9ec; --muted: #9aa4b0; --line: #2b3138;
--card: #1b1f24; --accent: #6cb6ff; --good: #4ac26b; --bad: #ff7b72;
--warn: #d4a72c; --code: #1e2329;
}
}
* { box-sizing: border-box; }
body {
margin: 0 auto; padding: 2rem 1rem 5rem; max-width: min(48rem, 92vw);
background: var(--bg); color: var(--fg); line-height: 1.65;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
}
h1 { font-size: 1.9rem; line-height: 1.25; margin: 0 0 .4rem; }
h2 { font-size: 1.4rem; margin: 2.6rem 0 .8rem; padding-top: .6rem;
border-top: 1px solid var(--line); }
h3 { font-size: 1.08rem; margin: 1.6rem 0 .5rem; }
.sub { color: var(--muted); margin: 0 0 1.5rem; }
a { color: var(--accent); }
code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
code { background: var(--code); padding: .12em .35em; border-radius: 4px;
font-size: .88em; }
.codewrap { overflow-x: auto; background: var(--code); border: 1px solid var(--line);
border-radius: 8px; margin: .8rem 0; }
pre { margin: 0; padding: .85rem 1rem; white-space: pre-wrap; overflow-x: auto;
font-size: .84rem; line-height: 1.5; }
.add { color: var(--good); }
.del { color: var(--bad); }
nav.toc { background: var(--card); border: 1px solid var(--line);
border-radius: 10px; padding: .9rem 1.1rem; margin: 1.5rem 0 2rem; }
nav.toc ol { margin: .4rem 0 0; padding-left: 1.2rem; }
nav.toc li { margin: .25rem 0; }
.card { background: var(--card); border: 1px solid var(--line);
border-radius: 10px; padding: 1rem 1.1rem; margin: 1.2rem 0; }
.note { border-left: 3px solid var(--accent); }
.warnbox { border-left: 3px solid var(--warn); }
.badbox { border-left: 3px solid var(--bad); }
table { border-collapse: collapse; width: 100%; font-size: .9rem; }
.tablewrap { overflow-x: auto; margin: 1rem 0; }
th, td { border: 1px solid var(--line); padding: .45rem .6rem; text-align: left; }
th { background: var(--card); }
/* diagram primitives */
.diagram { margin: 1.2rem 0; }
.row { display: flex; gap: .6rem; align-items: stretch; flex-wrap: wrap; }
.box { border: 1px solid var(--line); border-radius: 8px; padding: .55rem .7rem;
background: var(--card); font-size: .84rem; flex: 1 1 0; min-width: 8.5rem; }
.box .t { font-weight: 600; font-size: .78rem; color: var(--muted);
text-transform: uppercase; letter-spacing: .03em; margin-bottom: .3rem; }
.arrow { display: flex; align-items: center; justify-content: center;
color: var(--muted); font-size: 1.3rem; padding: .2rem 0; }
.down { text-align: center; color: var(--muted); font-size: 1.2rem; margin: .1rem 0; }
.pill { display: inline-block; border-radius: 999px; padding: .08em .55em;
font-size: .76rem; border: 1px solid var(--line); }
.pill.v { color: var(--good); border-color: var(--good); }
.pill.m { color: var(--warn); border-color: var(--warn); }
.pill.x { color: var(--bad); border-color: var(--bad); }
/* micro-world */
.sim { border: 1px solid var(--line); border-radius: 10px; padding: 1rem;
background: var(--card); }
.sim label { display: block; font-size: .84rem; margin: .7rem 0 .25rem; }
.sim .grp { border: 1px solid var(--line); border-radius: 8px; padding: .6rem .7rem;
background: var(--bg); margin: .6rem 0; }
.sim select, .sim input[type=range] { width: 100%; }
.rangeval { font-size: .8rem; color: var(--muted); }
.btnrow { display: flex; gap: .3rem; margin-top: .5rem; flex-wrap: wrap; }
button { font: inherit; font-size: .82rem; padding: .3rem .6rem; cursor: pointer;
border: 1px solid var(--line); border-radius: 6px;
background: var(--bg); color: var(--fg); }
button:hover { border-color: var(--accent); }
button.primary { border-color: var(--accent); color: var(--accent); font-weight: 600; }
.trace { margin-top: .8rem; padding: .7rem .9rem; border-radius: 8px;
background: var(--bg); border: 1px solid var(--line); font-size: .85rem; }
.trace .step { padding: .35rem 0; border-bottom: 1px dashed var(--line); }
.trace .step:last-child { border-bottom: none; }
.trace .step .k { color: var(--muted); font-size: .78rem; }
.verdict-line { margin-top: .5rem; font-weight: 600; }
/* quiz */
.q { margin: 1.4rem 0; }
.q .stem { font-weight: 600; margin-bottom: .5rem; }
.opt { display: block; width: 100%; text-align: left; margin: .3rem 0;
padding: .5rem .7rem; border-radius: 8px; border: 1px solid var(--line);
background: var(--bg); color: var(--fg); cursor: pointer; font-size: .9rem; }
.opt:disabled { cursor: default; }
.opt.correct { border-color: var(--good); background: color-mix(in srgb, var(--good) 12%, var(--bg)); }
.opt.wrong { border-color: var(--bad); background: color-mix(in srgb, var(--bad) 12%, var(--bg)); }
.rat { font-size: .85rem; color: var(--muted); margin: .4rem 0 0; display: none; }
.rat.show { display: block; }
#score { font-weight: 600; }
</style>
</head>
<body>
<h1>Check Phone learns to look backward, and forgives shaky GPS</h1>
<p class="sub">
<code>c277325</code> · 12 files · +583 / −78 · 2026-07-18
</p>
<nav class="toc">
<strong>Contents</strong>
<ol>
<li><a href="#background">Background — what Check Phone actually checks</a></li>
<li><a href="#intuition">Intuition — a same-day blind spot, and a shaky GPS trace</a></li>
<li><a href="#code">Code — the change, by concern</a></li>
<li><a href="#quiz">Quiz</a></li>
</ol>
</nav>
<h2 id="background">1. Background — what Check Phone actually checks</h2>
<p>
<strong>screen-locker</strong> locks the screen until a weekly workout
quota is met. The status window has a voluntary "Check Phone" button
(<code>screen_locker/_status_view_verify.py</code>,
<code>PhoneCheckMixin</code>) that, on click, pulls real data off your
Android phone over ADB and — if it verifies — logs it and applies the
reward. It never trusts a typed claim; it always pulls the actual file
first. Two sources feed it:
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">StrongLifts</div>
Pulls <code>workout_result.json</code> off the phone.
<code>_verify_phone_workout</code> in
<code>_phone_verification.py</code>.
</div>
<div class="box">
<div class="t">RunnerUp</div>
Pulls the real <code>.tcx</code> file from
<code>/sdcard/Documents/RunnerUp/</code>.
<code>_verify_runnerup_workout</code> in
<code>_runnerup_verification.py</code>.
</div>
</div>
</div>
<p>
Both of those functions were written to answer one specific question:
<em>did you work out today?</em> They match on today's date only —
StrongLifts by comparing the JSON's <code>date</code> field, RunnerUp by
grepping filenames for today's date string. That's the right question for
the locked screen, which decides whether to unlock <em>right now</em>. But
the voluntary "Check Phone" button reused those same today-only functions,
even though what it's really trying to answer is broader: <em>is this
week's quota met?</em>
</p>
<p>
The quota itself, from <code>_weekly_check.py</code>, follows an
anti-gaming rule established in the previous change to this repo: each
<span class="pill v">verified</span> workout (StrongLifts or RunnerUp)
counts individually, however many happen on one day, because they're
machine-checked and can't be faked. A <span class="pill m">manual</span>
self-report counts at most once per day. The weekly minimum is 4.
</p>
<p>
A week-aware scanner for RunnerUp already existed —
<code>_scan_and_fill_week_runnerup</code> walks every day from Monday to
today, and for each one still ADB-pulls and validates the real TCX file
before writing anything. It was wired into the automatic login check and
the <code>--status</code> CLI, but never into the "Check Phone" button.
Nothing equivalent existed for StrongLifts at all.
</p>
<h2 id="intuition">2. Intuition — a same-day blind spot, and a shaky GPS trace</h2>
<p>
Here's what actually happened. Wednesday's status window connected to the
phone and clicked Check Phone. The phone had a real RunnerUp run from
<strong>yesterday</strong> — a 4.9&nbsp;km run recorded the evening before,
after the button's earlier check that day had already failed. The result:
</p>
<div class="card badbox">
<code>Phone check (not_verified): StrongLifts: Workout JSON is from
2026-07-17, not today · RunnerUp: No RunnerUp activity found for today</code>
</div>
<p>
Both messages are literally true and both are useless. There <em>is</em> a
real, verifiable run — the button just never looked at any date but today.
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">Before</div>
StrongLifts today? no →<br>
RunnerUp today? no →<br>
<span style="color:var(--bad)">give up</span>
</div>
<div class="box">
<div class="t">After</div>
StrongLifts today? no →<br>
RunnerUp today? no →<br>
<span style="color:var(--good)">scan Mon…today for anything unlogged</span>
</div>
</div>
</div>
<p>
The week-scan fallback reuses the existing RunnerUp scanner and a new,
symmetric StrongLifts one — both still pull and validate the real file via
ADB, they just stop requiring the date to be <em>today</em> and instead
accept anything from Monday through today that isn't logged yet.
</p>
<h3>The second problem the first one uncovered</h3>
<p>
Testing this against the real phone surfaced a second issue: that 4.9&nbsp;km
run should count, but <code>MIN_RUN_DISTANCE_KM</code> is 5.0. GPS traces
measure distance by summing straight-line hops between sampled points, so
tight turns, tree cover, and urban canyons make the recorded distance
consistently <em>shorter</em> than the run actually was. A real 5&nbsp;km run can
legitimately log as 4.9. So a 5% tolerance was added — applied to distance
only, since duration comes from the device clock and has no such noise:
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">recorded</div>
<span style="font-size:1.3rem;font-weight:700">4.90&nbsp;km</span>
</div>
<div class="arrow">×1.05 →</div>
<div class="box">
<div class="t">tolerant distance</div>
<span style="font-size:1.3rem;font-weight:700">5.145&nbsp;km</span>
</div>
<div class="arrow">≥ 5.0 →</div>
<div class="box" style="border-color:var(--good)">
<div class="t">verified</div>
<span class="pill v">counts</span>
</div>
</div>
</div>
<p>
Play with the whole chain below — it mirrors
<code>_verify_phone_then_runnerup</code>'s real order: StrongLifts today,
then RunnerUp today, then the week-scan fallback, using the same 5%
distance rule at every RunnerUp step.
</p>
<div class="sim diagram" id="sim">
<div class="grp">
<label><input type="checkbox" id="sl-today"> StrongLifts JSON dated <strong>today</strong></label>
</div>
<div class="grp">
<label><input type="checkbox" id="ru-today"> RunnerUp TCX dated <strong>today</strong></label>
<label for="ru-today-km">distance (km) <span class="rangeval" id="ru-today-km-val">4.9</span></label>
<input type="range" id="ru-today-km" min="3" max="6" step="0.1" value="4.9">
</div>
<div class="grp">
<label><input type="checkbox" id="week-gap" checked> Unlogged workout earlier this week</label>
<label for="week-type">source</label>
<select id="week-type">
<option value="runnerup">RunnerUp run</option>
<option value="stronglifts">StrongLifts session</option>
</select>
<div id="week-km-wrap">
<label for="week-km">distance (km) <span class="rangeval" id="week-km-val">4.9</span></label>
<input type="range" id="week-km" min="3" max="6" step="0.1" value="4.9">
</div>
</div>
<div class="btnrow">
<button class="primary" id="run-check">Click "Check Phone"</button>
<button id="reset-sim">Reset</button>
</div>
<div class="trace" id="trace"></div>
</div>
<h2 id="code">3. Code — the change, by concern</h2>
<h3>3.1 Splitting the date-check out of StrongLifts validation</h3>
<p>
<code>_validate_json_data</code> used to do two jobs at once: check the
date, then check the exercises/duration/succeeded content. The week-scan
needs the second job without the first, so it was split:
</p>
<div class="codewrap"><pre><span class="add">+ def _validate_json_content(self, data: dict) -> tuple[str, str]:
+ """...no date check..."""
+ if not data.get("exercises"):
+ return "no_exercises", "No exercises found in the workout JSON"
+ ...
def _validate_json_data(self, data: dict) -> tuple[str, str]:
<span class="del">- today = time.strftime("%Y-%m-%d")</span>
<span class="del">- if data.get("date") != today: return "stale", ...</span>
<span class="del">- if not data.get("exercises"): ...</span>
<span class="add">+ today = time.strftime("%Y-%m-%d")
+ if data.get("date") != today:
+ return "stale", f"Workout JSON is from {data.get('date')}, not today"
+ return self._validate_json_content(data)</span></pre></div>
<p>
<code>_validate_json_data</code> — the live, today-only check used by the
locked screen's unlock chain — keeps behaving exactly as before. It's now
just a thin date gate in front of the shared content check.
</p>
<h3>3.2 A week-scan backfill for StrongLifts (new — nothing existed before)</h3>
<p>
RunnerUp's <code>_scan_and_fill_week_runnerup</code> can find multiple
unlogged days because RunnerUp writes one <code>.tcx</code> file per
activity. StrongLifts only has <em>one</em> <code>workout_result.json</code>
snapshot on the phone at a time, so its equivalent can only ever backfill
one day per call — that's not a limitation of the fix, it's what the data
actually allows:
</p>
<div class="codewrap"><pre><span class="add">+ def _try_fill_stronglifts_for_week(self, log_file: Path) -> int:
+ if not self._has_adb_device():
+ return 0
+ data = self._pull_workout_app_json()
+ date_str = data.get("date") if data else None
+ if not date_str:
+ return 0
+ today = datetime.now(tz=timezone.utc).astimezone().date()
+ week_start = today - timedelta(days=today.weekday())
+ entry_date = date.fromisoformat(date_str) # ValueError -> 0, logged
+ if not week_start <= entry_date <= today:
+ return 0
+ status, msg = self._validate_json_content(data) # no date gate
+ if status != "verified":
+ return 0
+ ...
+ if write_signed_entry(log_file, date_str, workout_data).appended:
+ return 1
+ return 0</span></pre></div>
<p>
<code>write_signed_entry</code> dedups by <code>workout_id</code> (here
<code>"phone_verified:{date}"</code>), so re-scanning an already-filled day
is a safe no-op — calling this twice in a row correctly returns
<code>1</code> then <code>0</code>.
</p>
<h3>3.3 Wiring both week-scans into the button</h3>
<p>
The old return type was a bare 4-tuple, which had no room for "nothing
verified today, but something got backfilled." A small frozen dataclass
replaces it, and a new helper runs both scanners and applies whatever
bonus is earned — reusing the exact prev/new-count math the login
auto-check and <code>--status</code> already use, specifically <em>not</em>
routing through <code>_apply_workout_credit</code>, which always files
under <em>today</em> by design and would mis-date a backfilled entry:
</p>
<div class="codewrap"><pre><span class="add">+ @dataclass(frozen=True)
+ class PhoneCheckOutcome:
+ credited_type: str | None
+ status: str
+ phone_message: str
+ runnerup_message: str | None
+ week_fill_message: str | None = None
+ def _backfill_week_and_apply_bonus(verifier) -> str | None:
+ prev_count = count_weekly_workouts(verifier.log_file)
+ filled = verifier._scan_and_fill_week_runnerup(verifier.log_file)
+ filled += verifier._try_fill_stronglifts_for_week(verifier.log_file)
+ if not filled:
+ return None
+ new_count = count_weekly_workouts(verifier.log_file)
+ bonus = max(0, new_count - max(WEEKLY_WORKOUT_MINIMUM, prev_count))
+ if bonus > 0:
+ verifier._adjust_shutdown_time_by(bonus)
+ return f"Auto-filled {filled} workout(s) from earlier this week." + (
+ f" +{bonus}h shutdown time." if bonus > 0 else ""
+ )</span></pre></div>
<p>
<code>_verify_phone_then_runnerup</code> calls this only after both
today-checks fail, and <code>_on_phone_check_result</code> branches on it:
a verified-today result still goes through <code>_apply_workout_credit</code>
as before; a <code>week_fill_message</code> is shown as-is, because the
backfill step already wrote the entry and applied its own bonus — running
credit again there would double it.
</p>
<h3>3.4 The RunnerUp GPS tolerance</h3>
<div class="codewrap"><pre> distance_km = data["distance_m"] / 1000
<span class="add">+ if distance_km * (1 + RUNNERUP_DISTANCE_TOLERANCE) < MIN_RUN_DISTANCE_KM:</span>
<span class="del">- if distance_km < MIN_RUN_DISTANCE_KM:</span>
msg = f"Run was {distance_km:.1f} km — need {MIN_RUN_DISTANCE_KM:.0f}+ km"
return "too_short", msg
<span class="add">+ if distance_km < MIN_RUN_DISTANCE_KM:
+ _logger.info("...within %.0f%% GPS tolerance — accepted.", ...)</span></pre></div>
<p>
<code>RUNNERUP_DISTANCE_TOLERANCE = 0.05</code> lives in
<code>_constants.py</code> next to the minimum it adjusts. The log line on
a tolerance-assisted pass exists so a below-threshold-but-accepted run is
still visible in the logs, never a silent pass — the entry itself still
stores the true, un-inflated distance.
</p>
<div class="note" style="border-left:4px solid #b58900;padding:0.75rem 1rem;margin:1.5rem 0;background:#fdf6e3">
<strong>Superseded 2026-08-14.</strong> The numbers on this page describe the
rule as it stood on 2026-07-18 and are kept for that history. The thresholds
and their <em>shape</em> have both since changed: duration and distance were
an <strong>AND</strong> here (30+ min <em>and</em> 5.0+ km); they are now an
<strong>OR</strong> — a run qualifies at
<code>MIN_RUN_DISTANCE_KM = 3.5</code> (inclusive, still with the 5% GPS
tolerance described above) <em>or</em> at
<code>MIN_RUN_DURATION_MINUTES = 40</code> (strict, no tolerance). The
30-minute floor every run had to clear is gone, so a fast 5&nbsp;km now
passes too. The interactive demo and quiz below still use the old 5.0&nbsp;km
AND-rule.
</div>
<h3>3.5 The CLI bug this surfaced (unrelated file, same root cause)</h3>
<p>
Verifying the fix against the real phone produced a week with two
workouts on one day for the first time. That's when
<code>_status.py</code>'s <code>--status</code> CLI printed
<em>"Need 2 more to reach the minimum (4)"</em> for a week that was
actually 4/4 — the GUI, which uses <code>count_weekly_workouts</code>
directly, showed the correct number.
</p>
<div class="codewrap"><pre><span class="del">- before_count = 0
- for i in range(7):
- ...
- if _print_day_line(d, ...):
- before_count += 1 # capped at 1 per day, regardless of
- # how many workouts that day held</span>
<span class="add">+ for i in range(7):
+ ...
+ _print_day_line(d, ...) # display only now
+ before_count = count_weekly_workouts(log_file) # the real anti-gaming count</span></pre></div>
<p>
<code>before_count</code> had been derived from <code>_print_day_line</code>'s
boolean return — one checkmark per day, regardless of how many workouts
that day held. It happened to agree with the real count for years, because
until this change no day ever legitimately held two <em>verified</em>
entries. The fix makes the CLI compute the same weekly total the GUI
already used, so the two views can no longer disagree.
</p>
<h2 id="quiz">4. Quiz</h2>
<p style="color:var(--muted);font-size:.9rem">
Five questions on the reasoning. Score: <span id="score">0 / 0</span>
</p>
<div id="quiz"></div>
<script>
/* ---------------- micro-world: the Check Phone chain ---------------- */
(function () {
const TOLERANCE = 0.05;
const MIN_KM = 5.0;
const slToday = document.getElementById("sl-today");
const ruToday = document.getElementById("ru-today");
const ruTodayKm = document.getElementById("ru-today-km");
const ruTodayKmVal = document.getElementById("ru-today-km-val");
const weekGap = document.getElementById("week-gap");
const weekType = document.getElementById("week-type");
const weekKmWrap = document.getElementById("week-km-wrap");
const weekKm = document.getElementById("week-km");
const weekKmVal = document.getElementById("week-km-val");
const traceEl = document.getElementById("trace");
function passesDistance(km) {
return km * (1 + TOLERANCE) >= MIN_KM;
}
function syncLabels() {
ruTodayKmVal.textContent = parseFloat(ruTodayKm.value).toFixed(1);
weekKmVal.textContent = parseFloat(weekKm.value).toFixed(1);
weekKmWrap.style.display = weekType.value === "runnerup" ? "block" : "none";
}
[ruTodayKm, weekKm, weekType].forEach((el) => el.addEventListener("input", syncLabels));
syncLabels();
function step(label, detail, ok) {
return '<div class="step"><span class="k">' + label + "</span> — " + detail +
(ok === true ? ' <span class="pill v">pass</span>' :
ok === false ? ' <span class="pill x">fail</span>' : "") + "</div>";
}
function run() {
let html = "";
// 1. StrongLifts today
if (slToday.checked) {
html += step("1. StrongLifts today", "JSON dated today, content valid", true);
finish(html, "phone_verified", "Credited today: StrongLifts verified.");
return;
}
html += step("1. StrongLifts today", "no JSON dated today", false);
// 2. RunnerUp today
if (ruToday.checked) {
const km = parseFloat(ruTodayKm.value);
const tol = (km * (1 + TOLERANCE)).toFixed(2);
const ok = passesDistance(km);
html += step(
"2. RunnerUp today",
km.toFixed(1) + " km × 1.05 = " + tol + " km " + (ok ? "≥" : "<") + " 5.0 km",
ok
);
if (ok) {
finish(html, "runnerup_verified", "Credited today: RunnerUp verified.");
return;
}
} else {
html += step("2. RunnerUp today", "no TCX dated today", false);
}
// 3. Week-scan fallback
if (weekGap.checked) {
if (weekType.value === "stronglifts") {
html += step("3. Week-scan (StrongLifts)", "unlogged day, content valid", true);
finish(html, "week_fill", "Auto-filled 1 workout from earlier this week.");
return;
}
const km = parseFloat(weekKm.value);
const tol = (km * (1 + TOLERANCE)).toFixed(2);
const ok = passesDistance(km);
html += step(
"3. Week-scan (RunnerUp)",
km.toFixed(1) + " km × 1.05 = " + tol + " km " + (ok ? "≥" : "<") + " 5.0 km",
ok
);
if (ok) {
finish(html, "week_fill", "Auto-filled 1 workout from earlier this week.");
return;
}
} else {
html += step("3. Week-scan", "nothing unlogged this week", false);
}
finish(html, "none",
"StrongLifts: Workout JSON is from earlier, not today · " +
"RunnerUp: No RunnerUp activity found for today");
}
function finish(html, kind, message) {
const cls = kind === "none" ? "x" : "v";
html += '<div class="verdict-line">Result: <span class="pill ' + cls + '">' +
message + "</span></div>";
traceEl.innerHTML = html;
}
document.getElementById("run-check").onclick = run;
document.getElementById("reset-sim").onclick = () => {
slToday.checked = false;
ruToday.checked = false;
ruTodayKm.value = 4.9;
weekGap.checked = true;
weekType.value = "runnerup";
weekKm.value = 4.9;
syncLabels();
traceEl.innerHTML = "";
};
})();
/* ---------------- quiz ---------------- */
(function () {
const QS = [
{
stem: "A 4.9 km run is logged today, and no StrongLifts JSON exists for today. What does Check Phone report?",
opts: [
"runnerup_verified — 4.9 km times 1.05 clears the 5.0 km line.",
"not_verified — a 4.9 km run stays under the 5.0 km minimum.",
"phone_verified — RunnerUp falls back to the StrongLifts checker.",
"week_fill — today's date always routes to the week-scan path."
],
correct: 0,
rat: "The 5% tolerance is applied before comparing to MIN_RUN_DISTANCE_KM, so today's own RunnerUp check already passes it — the week-scan fallback is never reached."
},
{
stem: "Why does _try_fill_stronglifts_for_week return at most 1, while _scan_and_fill_week_runnerup can return more?",
opts: [
"StrongLifts entries are capped at one credit per week by policy.",
"The phone holds one snapshot; RunnerUp writes one file per run.",
"Only RunnerUp results carry a date, so StrongLifts can't span days.",
"ADB restricts a single pull command to one remote file at a time."
],
correct: 1,
rat: "RunnerUp writes a dated .tcx per activity, so several unlogged days can each supply one; StrongLifts only ever has the single latest snapshot to pull."
},
{
stem: "Why does the week-scan backfill skip _apply_workout_credit and call _adjust_shutdown_time_by directly instead?",
opts: [
"_apply_workout_credit needs a live Tk window a worker thread lacks.",
"_apply_workout_credit always files the entry under today's own date.",
"_adjust_shutdown_time_by is the only method the bare verifier exposes.",
"Skipping it avoids clearing the sick-day debt on a backfilled entry."
],
correct: 1,
rat: "Its own docstring says so: it 'always files under today' as the intra-day reward path, which would mis-date a backfilled entry from an earlier day."
},
{
stem: "Before this change, why did _status.py's CLI summary agree with the GUI for years despite using a different formula?",
opts: [
"Both formulas give identical totals for any log file's contents.",
"The CLI recomputed its total from count_weekly_workouts either way.",
"No day had ever held two verified entries until this very change.",
"The CLI only ran weekly, before a second same-day workout could occur."
],
correct: 2,
rat: "A checkmark-per-day count and a per-workout count only diverge once some day holds more than one verified entry — which this very change made possible for the first time."
},
{
stem: "In the Check Phone chain, in what order are the three checks tried?",
opts: [
"RunnerUp today, then StrongLifts today, then the week-scan fallback.",
"The week-scan fallback first, then StrongLifts today, then RunnerUp today.",
"StrongLifts today, then RunnerUp today, then the week-scan fallback.",
"All three run together, and the first one to finish wins the credit."
],
correct: 2,
rat: "_verify_phone_then_runnerup checks StrongLifts first, falls back to RunnerUp, and only reaches the week-scan when neither today-check verifies."
}
];
const quizEl = document.getElementById("quiz");
const scoreEl = document.getElementById("score");
let answered = 0, right = 0;
QS.forEach((q, qi) => {
const wrap = document.createElement("div");
wrap.className = "q";
const stem = document.createElement("div");
stem.className = "stem";
stem.textContent = (qi + 1) + ". " + q.stem;
wrap.append(stem);
const rat = document.createElement("p");
rat.className = "rat";
q.opts.forEach((text, oi) => {
const b = document.createElement("button");
b.className = "opt";
b.textContent = text;
b.onclick = () => {
if (wrap.dataset.done) return;
wrap.dataset.done = "1";
answered++;
if (oi === q.correct) right++;
wrap.querySelectorAll(".opt").forEach((o, i) => {
o.disabled = true;
if (i === q.correct) o.classList.add("correct");
else if (i === oi) o.classList.add("wrong");
});
rat.textContent = (oi === q.correct ? "Correct. " : "Not quite. ") + q.rat;
rat.classList.add("show");
scoreEl.textContent = right + " / " + answered;
};
wrap.append(b);
});
wrap.append(rat);
quizEl.append(wrap);
});
})();
</script>
</body>
</html>

View File

@ -1,51 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>screen-locker — change explanations</title>
<style>
:root{--bg:#fbfbfd;--fg:#1a1a1f;--muted:#5b5b6b;--card:#fff;--line:#e4e4ec;
--accent:#6b4fd6;--accent-soft:#efeaff;--shadow:0 1px 3px rgba(0,0,0,.08),0 8px 24px rgba(0,0,0,.05);}
@media (prefers-color-scheme:dark){:root{--bg:#131318;--fg:#e9e9f0;--muted:#a2a2b4;--card:#1c1c24;
--line:#2c2c38;--accent:#a78bfa;--accent-soft:#241f38;--shadow:0 1px 3px rgba(0,0,0,.4),0 10px 30px rgba(0,0,0,.35);}}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--fg);
font:16px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased}
.wrap{width:min(48rem,92vw);margin:0 auto;padding:2.6rem 0 5rem}
.kicker{color:var(--accent);font-weight:700;font-size:.8rem;letter-spacing:.08em;text-transform:uppercase}
h1{font-size:1.7rem;margin:.35rem 0 .3rem}
.lead{color:var(--muted);margin:0 0 1.6rem}
.grid{display:flex;flex-direction:column;gap:.7rem}
a.card{display:flex;flex-direction:column;gap:.2rem;text-decoration:none;color:var(--fg);
background:var(--card);border:1px solid var(--line);border-radius:12px;padding:.9rem 1.1rem;box-shadow:var(--shadow)}
a.card:hover{border-color:var(--accent);background:var(--accent-soft)}
.date{font-size:.75rem;color:var(--muted);font-variant-numeric:tabular-nums;letter-spacing:.03em}
.title{font-size:1.05rem;font-weight:600;line-height:1.35}
.empty{color:var(--muted)}
footer{margin-top:2.4rem;padding-top:1.1rem;border-top:1px solid var(--line);color:var(--muted);font-size:.83rem}
</style>
</head>
<body>
<div class="wrap">
<div class="kicker">screen-locker</div>
<h1>Change explanations</h1>
<p class="lead">3 explanations · interactive walkthroughs of notable changes, newest first.</p>
<div class="grid">
<a class="card" href="2026-07-18-explanation-check-phone-week-aware.html">
<span class="date">2026-07-18</span>
<span class="title">Check Phone learns to look backward, and forgives shaky GPS</span>
</a>
<a class="card" href="2026-07-17-explanation-multi-workout-day-and-sync.html">
<span class="date">2026-07-17</span>
<span class="title">Multiple workouts per day, the sync that never ran, and a ban on silence</span>
</a>
<a class="card" href="2026-07-13-explanation-flutter-coverage-to-100.html">
<span class="date">2026-07-13</span>
<span class="title">Driving the workout app to 100% test coverage</span>
</a>
</div>
<footer>Generated by the <code>explain-diff</code> skill. Open any card to replay its walkthrough.</footer>
</div>
</body>
</html>

View File

@ -34,7 +34,12 @@ if TYPE_CHECKING:
_logger: Final = logging.getLogger(__name__)
TITLE: Final = "Workout credited \N{FLEXED BICEPS}"
# textgate: glyphs + numbers (colour emoji are safe in the notification
# daemon, unlike Tk). Was "Workout credited 💪" / "Shutdown 23:00 (+2h) ·
# gaming 7.0h" / "Credit applied (details unavailable)".
TITLE: Final = "\N{FLEXED BICEPS} \N{CHECK MARK}"
_SHUTDOWN: Final = "\N{POWER SYMBOL}"
_GAMING: Final = "\N{VIDEO GAME}"
_NOTIFY_TIMEOUT_SECONDS: Final = 5
_MINUTES_PER_HOUR: Final = 60.0
@ -62,7 +67,7 @@ def credit_body(
after: tuple[int, int, int] | None,
gaming_minutes: int | None,
) -> str:
"""``Shutdown 23:00 (+2h) · gaming 7.0h`` -- whichever parts are known.
"""``⏻ 23:00 (+2h) · 🎮 7.0h`` -- whichever parts are known.
``before``/``after`` are the shutdown config around the credit; the delta
is tonight's actual move, so a capped or rest-day credit shows ``+0h``.
@ -76,14 +81,14 @@ def credit_body(
else:
day = date.fromisoformat(today_str())
tonight = tonight_minutes(after, day)
text = f"Shutdown {hhmm(tonight)}"
text = f"{_SHUTDOWN} {hhmm(tonight)}"
if before is not None:
moved = max(0, tonight - tonight_minutes(before, day))
text += f" (+{span(moved)})"
parts.append(text)
if gaming_minutes is not None:
parts.append(f"gaming {gaming_minutes / _MINUTES_PER_HOUR:.1f}h")
return " \N{MIDDLE DOT} ".join(parts) or "Credit applied (details unavailable)"
parts.append(f"{_GAMING} {gaming_minutes / _MINUTES_PER_HOUR:.1f}h")
return " \N{MIDDLE DOT} ".join(parts) or "\N{CHECK MARK}"
def send_notification(title: str, body: str) -> bool:

98
screen_locker/_glyphs.py Normal file
View File

@ -0,0 +1,98 @@
"""The locker's pictograms: one place, so a glyph means one thing everywhere.
textgate (kuhy, 2026-11-08): nothing he sees carries words. Every screen is
built from these plus numbers, each paired with a palette colour as the
second channel (success / warning / danger / muted). Plain geometric
characters only: a colour-emoji fallback font can crash Tk 8.6, so no
U+1Fxxx and nothing with an emoji presentation by default.
"""
from __future__ import annotations
from typing import Final
LIFT: Final = "●━━●" # a barbell: the StrongLifts workout / "go work out"
RUN: Final = "⇝" # a RunnerUp run
PHONE: Final = "▯" # the phone (adb)
WAIT: Final = "⋯" # checking / unlocking in progress
OK: Final = "✓"
FAIL: Final = "✗"
RETRY: Final = "↻"
CLOSE: Final = "✕"
BACK: Final = "↩"
GO: Final = "▶"
SKIP: Final = "↷"
SYNC: Final = "⇅" # a sync backend (Firebase)
CLOCK: Final = "◷" # time, the system clock
SHORT: Final = "◔" # a session shorter than the minimum
FORM: Final = "≡" # the manual-workout evidence form
SICK: Final = "✚" # a sick day
SHUTDOWN: Final = "⏻" # the PC's shutdown time
STREAK: Final = "▰" # one week of the streak
WEEK_DONE: Final = "●" # a counted day
WEEK_SICK: Final = "✚" # a sick day in the week row
WEEK_EMPTY: Final = "○" # a day with nothing counted
HEAT: Final = "▲" # the outdoor temperature
LOCK: Final = "■" # the lock fired
UNLOCK: Final = "□" # the lock stood down
OPTIONAL: Final = "◇" # Tue-Thu: a workout is optional today
GIFT: Final = "+" # an earned reward, always followed by its amount
# Startup phone-check status -> the glyph that replaces its sentence.
STATUS_GLYPH: Final[dict[str, str]] = {
"too_short": SHORT,
"clock_tampered": f"{CLOCK}{FAIL}",
"stale": f"{CLOCK}{FAIL}",
"no_exercises": f"{LIFT} 0",
"not_verified": FAIL,
"no_phone": f"{PHONE}{FAIL}",
"error": f"{PHONE}{FAIL}",
}
# log.json entry ``type`` -> glyph, for the status window's day cells.
ENTRY_GLYPH: Final[dict[str, str]] = {
"phone_verified": LIFT,
"strength": LIFT,
"pc_workout_verified": LIFT,
"runnerup_verified": RUN,
"running": RUN,
"manual_workout": FORM,
"heat_skip": HEAT,
"relaxed_day_skip": SKIP,
"early_bird": OK,
}
# Lock-decision stage (``_compliance_state._STEPS`` names) -> glyph. A stage
# not listed shows only the lock/unlock square and its colour.
STAGE_GLYPH: Final[dict[str, str]] = {
"scheduled_skip": SKIP,
"early_bird_pending_expired": CLOCK,
"early_bird_window_open": CLOCK,
"sick_day": SICK,
"already_logged": OK,
"wake_alarm_skip": CLOCK,
"test_hold_active": WAIT,
"relaxed_day_already_skipped": f"{OPTIONAL}{SKIP}",
"relaxed_day": OPTIONAL,
"weekly_minimum_met": WEEK_DONE,
"evening_lockdown_today": SHUTDOWN,
"would_lock": LIFT,
}
def entry_glyphs(types: tuple[str, ...]) -> str:
"""Glyphs for a day's entry types; an unknown type shows as ``OK``."""
return " ".join(ENTRY_GLYPH.get(t, OK) for t in types)
def dots(done: int, total: int) -> str:
"""``●●○○ 2/4``: progress as filled dots plus the numbers (two channels)."""
filled = max(0, min(done, total))
return f"{WEEK_DONE * filled}{WEEK_EMPTY * (total - filled)} {done}/{total}"
def status_glyph(status: str) -> str:
"""Return the glyph for a phone-check *status* (``FAIL`` if unknown)."""
return STATUS_GLYPH.get(status, FAIL)

View File

@ -42,39 +42,35 @@ def build_heat_skip_content(
outer = tk.Frame(parent, bg=_COLORS.palette.bg)
outer.place(relx=0.5, rely=0.5, anchor="center")
# textgate: glyphs + numbers only, warning colour as the second channel.
# Was "\u2600 Too hot to workout?" / "<city>: 31\u00b0C (threshold: 30\u00b0C)" /
# "Skip today's workout due to extreme heat?". Plain geometric glyphs,
# not the sun (U+2600 can fall back to a colour-emoji font and crash Tk).
tk.Label(
outer,
text="\u2600 Too hot to workout?",
font=_COLORS.font("body", bold=True, family=_FONT),
text="\u25b2",
font=_COLORS.font("display", bold=True, family=_FONT),
bg=_COLORS.palette.bg,
fg=_COLORS.palette.warning,
).pack(pady=(0, _COLORS.space("sm")))
tk.Label(
outer,
text=(
f"{HEAT_SKIP_CITY}: {temp:.0f}\u00b0C"
f" (threshold: {HEAT_SKIP_TEMP_THRESHOLD}\u00b0C)"
),
# The city name was dropped too: the reading is what matters.
text=f"{temp:.0f}\u00b0C \u2265 {HEAT_SKIP_TEMP_THRESHOLD}\u00b0C",
font=_COLORS.font("body", family=_FONT),
bg=_COLORS.palette.bg,
fg=_COLORS.palette.muted,
fg=_COLORS.palette.warning,
).pack(pady=_COLORS.space("xs"))
tk.Label(
outer,
text="Skip today's workout due to extreme heat?",
font=_COLORS.font("body", family=_FONT),
bg=_COLORS.palette.bg,
fg=_COLORS.palette.muted,
).pack(pady=(_COLORS.space("xs"), 0))
btn_frame = tk.Frame(outer, bg=_COLORS.palette.bg)
btn_frame.pack(pady=_COLORS.space("lg"))
# Was "Skip workout" (warning fill) / "No, I'll workout" (neutral fill).
skip_button = tk.Button(
btn_frame,
text="Skip workout",
name="skip",
text="\u21b7",
command=on_skip,
bg=_COLORS.palette.warning,
fg=_COLORS.palette.on_fill,
@ -89,7 +85,8 @@ def build_heat_skip_content(
decline_button = tk.Button(
btn_frame,
text="No, I'll workout",
name="decline",
text="▶",
command=on_decline,
bg=_COLORS.palette.field_bg,
fg=_COLORS.palette.fg,
@ -130,7 +127,7 @@ class HeatSkipMixin:
# Use the root itself (not a Toplevel) so we can go fullscreen.
# This window is destroyed before the main GateRoot is created.
root = tk.Tk()
root.title("Extreme Heat")
root.title("")
root.configure(bg=_COLORS.palette.bg)
root.attributes("-fullscreen", True)
root.attributes("-topmost", True)

View File

@ -32,6 +32,7 @@ from screen_locker._manual_workout_checks import (
from screen_locker._manual_workout_types import (
MANUAL_WORKOUT_TYPE,
SPORT_CHOICES,
SPORT_GLYPHS,
SPORT_LABELS,
SPORT_OTHER,
SPORT_TABLE_TENNIS,
@ -44,6 +45,7 @@ from screen_locker._manual_workout_types import (
__all__ = [
"MANUAL_WORKOUT_TYPE",
"SPORT_CHOICES",
"SPORT_GLYPHS",
"SPORT_LABELS",
"SPORT_OTHER",
"SPORT_TABLE_TENNIS",

View File

@ -13,6 +13,7 @@ the form shows a "scheduled" screen that returns to the host's cancelled hook
from __future__ import annotations
import logging
import tkinter as tk
from typing import TYPE_CHECKING
@ -29,6 +30,16 @@ from screen_locker._ui_widgets import disable_paste
if TYPE_CHECKING:
from screen_locker._manual_workout import ManualWorkoutDraft
# textgate: plain glyphs (no colour emoji: Tk 8.6 can crash on them).
SCHEDULED_GLYPH = "✓"
"""Heading of the scheduled screen (success colour)."""
BACK_GLYPH = "↩"
"""The scheduled screen's only button: back to the form's host."""
REJECTED_GLYPH = "✗"
"""Form rejected (danger); was the validator's sentence (now logged)."""
_logger = logging.getLogger(__name__)
class ManualWorkoutDateMixin:
"""Date row, budget gate and future-dated submission of the manual form."""
@ -59,9 +70,10 @@ class ManualWorkoutDateMixin:
)
entry.pack(side="right", padx=self._colors.space("xs"))
disable_paste(entry)
# Was "Workout date (today to +7 days):" -- a day square + the range.
tk.Label(
row,
text="Workout date (today to +7 days):",
text="□ +0…+7",
font=self._colors.font("label"),
fg=self._colors.palette.fg,
bg=self._colors.palette.bg,
@ -80,37 +92,45 @@ class ManualWorkoutDateMixin:
if error is None and not future:
error = budget_error(self.log_file, date)
if error is not None:
self._mw_error_label.config(text=error)
self._mw_reject(error)
return True
if not future:
return False
result = schedule_future_workout(self.log_file, draft, date)
if not result.scheduled:
self._mw_error_label.config(text=result.reason)
self._mw_reject(result.reason)
return True
self._show_manual_workout_scheduled(result.reason)
_logger.info("Manual workout scheduled for %s: %s", date, result.reason)
self._show_manual_workout_scheduled(date)
return True
def _show_manual_workout_scheduled(self, reason: str) -> None:
"""Confirm a future entry and go back; it does NOT unlock anything."""
def _mw_reject(self, reason: str) -> None:
"""Show the form's fail mark; the reason goes to the log (textgate)."""
_logger.warning("Manual workout date/budget rejected: %s", reason)
self._mw_error_label.config(text=REJECTED_GLYPH)
def _show_manual_workout_scheduled(self, date: str) -> None:
"""Confirm a future entry and go back; it does NOT unlock anything.
Shows the scheduled *date* (content) under the tick; the scheduler's
sentence is logged by the caller.
"""
self.clear_container()
# Was "✓ Workout Scheduled" + "Nothing is credited today. It counts by
# itself on that date, and can be deleted in the phone app until
# then." + an "OK" button: a green tick, the reason, a back arrow.
self._label(
"✓ Workout Scheduled",
SCHEDULED_GLYPH,
role="display",
scale=1.3,
color=self._colors.palette.success,
pad="lg",
)
self._text(reason, role="subtitle", color=self._colors.palette.success)
self._text(
"Nothing is credited today. It counts by itself on that date, and "
"can be deleted in the phone app until then.",
color=self._colors.palette.muted,
)
self._text(date, role="subtitle", color=self._colors.palette.success)
row = self._button_row()
self._button(
row,
"OK",
BACK_GLYPH,
bg=self._colors.palette.accent,
command=self._on_manual_workout_cancelled,
width=12,

View File

@ -23,12 +23,24 @@ from screen_locker import _manual_workout
from screen_locker._constants import (
MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
)
from screen_locker._manual_workout_date import ManualWorkoutDateMixin
from screen_locker._manual_workout_date import (
BACK_GLYPH,
REJECTED_GLYPH,
ManualWorkoutDateMixin,
)
from screen_locker._manual_workout_sport_fields import ManualWorkoutSportFieldsMixin
from screen_locker._manual_workout_widgets import ManualWorkoutFormWidgetsMixin
_logger = logging.getLogger(__name__)
# textgate glyphs (plain Unicode, no colour emoji: Tk 8.6 can crash on them).
FORM_GLYPH = "≡"
"""Form heading (accent); was "Log Manual Workout"."""
EXHAUSTED_GLYPH = "✕"
"""Budget used up (danger); was the "budget exhausted" sentence."""
SUBMIT_GLYPH = "✓"
"""Submit button (accent fill); was "SUBMIT"."""
_SPORT_LABEL_TO_CODE = {
label: code for code, label in _manual_workout.SPORT_LABELS.items()
}
@ -44,12 +56,11 @@ class ManualWorkoutDialogMixin(
def _show_manual_workout_form(self) -> None:
"""Render the manual-workout evidence form, or a budget-exhausted note."""
self.clear_container()
self._label("Log Manual Workout", color=self._colors.palette.accent, pad="xs")
# textgate: glyphs, colours second. Was "Log Manual Workout" heading /
# "Manual-workout budget exhausted for this window." / "BACK".
self._label(FORM_GLYPH, color=self._colors.palette.accent, pad="xs")
if self._mw_budget_closed():
self._text(
"Manual-workout budget exhausted for this window.",
color=self._colors.palette.danger,
)
self._label(EXHAUSTED_GLYPH, color=self._colors.palette.danger, pad="xs")
self._text(
_manual_workout.budget_summary(self.log_file),
color=self._colors.palette.muted,
@ -57,7 +68,7 @@ class ManualWorkoutDialogMixin(
row = self._button_row()
self._button(
row,
"BACK",
BACK_GLYPH,
bg=self._colors.palette.field_bg,
command=self._on_manual_workout_cancelled,
width=12,
@ -87,24 +98,23 @@ class ManualWorkoutDialogMixin(
self._mw_rpe_var = tk.IntVar(value=5)
self._mw_text_widgets: dict[str, tk.Text] = {}
self._mw_section(form, "Basics")
# textgate: every prompt is a glyph; optional fields are in
# parentheses; section headings are plain rules. The old prompts were
# the Basics heading, start and end time, the location heading and
# name, how you got there, the cost in PLN, the optional reservation
# phone number, and the activity-details heading.
self._mw_section(form)
self._mw_sport_row(form)
self._mw_vars["start_time"] = self._mw_entry(
form, "Start time (HH:MM):", focus=True
)
self._mw_vars["end_time"] = self._mw_entry(form, "End time (HH:MM):")
self._mw_vars["start_time"] = self._mw_entry(form, "◷▶", focus=True)
self._mw_vars["end_time"] = self._mw_entry(form, "◷■")
self._mw_section(form, "Location & logistics")
self._mw_vars["location_name"] = self._mw_entry(form, "Location name:")
self._mw_vars["transport_method"] = self._mw_entry(
form, "How did you get there?"
)
self._mw_vars["cost"] = self._mw_entry(form, "Cost (e.g. 40 PLN):")
self._mw_vars["reservation_phone"] = self._mw_entry(
form, "Reservation phone number (if booked by phone, optional):"
)
self._mw_section(form)
self._mw_vars["location_name"] = self._mw_entry(form, "⌖")
self._mw_vars["transport_method"] = self._mw_entry(form, "⇄")
self._mw_vars["cost"] = self._mw_entry(form, "¤")
self._mw_vars["reservation_phone"] = self._mw_entry(form, "(▯#)")
self._mw_section(form, "Activity details")
self._mw_section(form)
# Both sport sub-frames occupy the same full-width grid slot; only the
# selected one is shown (see _on_mw_sport_changed).
act_row = self._mw_next_full_row(form)
@ -124,33 +134,22 @@ class ManualWorkoutDialogMixin(
self._build_table_tennis_fields(self._mw_tt_frame)
self._build_other_sport_fields(self._mw_other_frame)
self._mw_rpe_row(form)
self._mw_vars["techniques_practiced"] = self._mw_entry(
form, "Techniques/focus areas practiced (optional):"
)
self._mw_vars["warm_up_minutes"] = self._mw_entry(
form, "Warm-up duration (optional):"
)
self._mw_vars["pain_or_injury"] = self._mw_entry(
form, "Pain or injury notes (optional, default none):"
)
# Was "Techniques/focus areas practiced (optional):", "Warm-up
# duration (optional):", "Pain or injury notes (optional, ...)".
self._mw_vars["techniques_practiced"] = self._mw_entry(form, "(◎)")
self._mw_vars["warm_up_minutes"] = self._mw_entry(form, "(∿)")
self._mw_vars["pain_or_injury"] = self._mw_entry(form, "(↯)")
self._on_mw_sport_changed(
_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
)
self._mw_section(form, "Reflection")
self._mw_text_widgets["went_well"] = self._mw_textbox(
form,
f"What went well (min {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} chars):",
)
self._mw_text_widgets["to_improve"] = self._mw_textbox(
form,
f"What to improve (min {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} chars):",
)
self._mw_text_widgets["overall_feeling"] = self._mw_textbox(
form,
"Overall feeling about the session "
f"(min {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} chars):",
)
# Was "Reflection", "What went well / What to improve / Overall
# feeling about the session (min N chars):".
self._mw_section(form)
least = f"≥{MANUAL_WORKOUT_REFLECTION_MIN_CHARS}"
self._mw_text_widgets["went_well"] = self._mw_textbox(form, f"+ {least}")
self._mw_text_widgets["to_improve"] = self._mw_textbox(form, f"↑ {least}")
self._mw_text_widgets["overall_feeling"] = self._mw_textbox(form, f"~ {least}")
self._mw_error_label = self._text(
"", role="label", color=self._colors.palette.danger, pad="xs"
@ -158,14 +157,14 @@ class ManualWorkoutDialogMixin(
button_row = self._button_row()
self._button(
button_row,
"SUBMIT",
SUBMIT_GLYPH,
bg=self._colors.palette.accent,
command=self._submit_manual_workout_form,
width=12,
).pack(side="left", padx=self._colors.space("sm"))
self._button(
button_row,
"BACK",
BACK_GLYPH,
bg=self._colors.palette.field_bg,
command=self._on_manual_workout_cancelled,
width=12,
@ -212,7 +211,9 @@ class ManualWorkoutDialogMixin(
)
error = _manual_workout.validate_manual_workout(draft)
if error is not None:
self._mw_error_label.config(text=error)
# textgate: the reason is logged; the form shows the fail mark.
_logger.warning("Manual workout form rejected: %s", error)
self._mw_error_label.config(text=REJECTED_GLYPH)
return
if self._mw_handled_by_date(draft):
return

View File

@ -49,17 +49,11 @@ class ManualWorkoutSportFieldsMixin:
value=_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
)
row = tk.Frame(parent, bg=self._colors.palette.bg)
tk.Label(
row,
text="Sport:",
font=self._colors.font("body"),
fg=self._colors.palette.fg,
bg=self._colors.palette.bg,
).pack(side="left", padx=self._colors.space("xs"))
for label in _manual_workout.SPORT_LABELS.values():
# textgate: the "Sport:" caption is gone; the radio row is the cue.
for code, label in _manual_workout.SPORT_LABELS.items():
tk.Radiobutton(
row,
text=label,
text=_manual_workout.SPORT_GLYPHS[code],
value=label,
variable=self._mw_sport_var,
# Radiobutton's command takes no argument -- bind the label.
@ -97,25 +91,25 @@ class ManualWorkoutSportFieldsMixin:
def _build_table_tennis_fields(self, parent: tk.Widget) -> None:
"""Build the table-tennis-specific score/equipment fields."""
self._mw_int_vars["matches_won"] = self._mw_int_field(parent, "Matches won:")
self._mw_int_vars["matches_lost"] = self._mw_int_field(parent, "Matches lost:")
self._mw_int_vars["sets_won"] = self._mw_int_field(parent, "Sets won:")
self._mw_int_vars["sets_lost"] = self._mw_int_field(parent, "Sets lost:")
self._mw_vars["racket"] = self._mw_entry(parent, "Racket used:")
self._mw_vars["balls"] = self._mw_entry(parent, "Balls used:")
# textgate: was "Matches won/lost:", "Sets won/lost:", "Racket used:",
# "Balls used:". Match / set glyph + win / loss mark.
self._mw_int_vars["matches_won"] = self._mw_int_field(parent, "◍✓")
self._mw_int_vars["matches_lost"] = self._mw_int_field(parent, "◍✗")
self._mw_int_vars["sets_won"] = self._mw_int_field(parent, "▤✓")
self._mw_int_vars["sets_lost"] = self._mw_int_field(parent, "▤✗")
self._mw_vars["racket"] = self._mw_entry(parent, "◖")
self._mw_vars["balls"] = self._mw_entry(parent, "•")
def _build_other_sport_fields(self, parent: tk.Widget) -> None:
"""Build the generic "other sport" fields."""
self._mw_vars["activity_type_other"] = self._mw_entry(
parent, "What sport/activity:"
)
# Was "What sport/activity:" / "What was done (min N chars):" /
# "Equipment used (optional):"; optional fields are in parentheses.
self._mw_vars["activity_type_other"] = self._mw_entry(parent, "✱")
self._mw_text_widgets["activity_details"] = self._mw_textbox(
parent,
f"What was done (min {MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS} chars):",
)
self._mw_vars["equipment"] = self._mw_entry(
parent, "Equipment used (optional):"
f"✱≡ ≥{MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS}",
)
self._mw_vars["equipment"] = self._mw_entry(parent, "(⊡)")
def _current_mw_sport(self) -> str:
"""Return the internal sport code for the currently-selected label."""

View File

@ -37,6 +37,12 @@ SPORT_LABELS: dict[str, str] = {
SPORT_TABLE_TENNIS: "Table tennis",
SPORT_OTHER: "Other",
}
# What the form paints for each sport (textgate); SPORT_LABELS stays the
# radio value and the data, never painted.
SPORT_GLYPHS: dict[str, str] = {
SPORT_TABLE_TENNIS: "◍",
SPORT_OTHER: "✱",
}
def _today_iso() -> str:
@ -133,12 +139,16 @@ def budget_summary(
*,
today: str | None = None,
) -> str:
"""One-line UI summary string for the manual-workout budget."""
"""One-line UI summary of the manual-workout budget: glyph and numbers.
``≡ used/7-day budget · used/30-day budget`` (textgate; was
``Manual: 0/2w · 0/10m``). The shorter window always comes first.
"""
week = count_in_window(log_file, 7, today=today)
month = count_in_window(log_file, 30, today=today)
return (
f"Manual: {week}/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS}w · "
f"{month}/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}m"
f"≡ {week}/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS} · "
f"{month}/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}"
)

View File

@ -66,17 +66,10 @@ class ManualWorkoutFormWidgetsMixin:
counters[id(parent)] = idx + 2
return idx // 2
def _mw_section(self, parent: tk.Widget, title: str) -> None:
"""Add a full-width section heading inside the form."""
label = tk.Label(
parent,
text=title,
font=self._colors.font("body", bold=True),
fg=self._colors.palette.accent,
bg=self._colors.palette.bg,
anchor="w",
)
self._mw_grid(parent, label, full=True)
def _mw_section(self, parent: tk.Widget) -> None:
"""Add a full-width rule between form sections (was a heading)."""
rule = tk.Frame(parent, bg=self._colors.palette.accent, height=2)
self._mw_grid(parent, rule, full=True)
def _mw_entry(
self, parent: tk.Widget, label: str, *, focus: bool = False
@ -190,10 +183,8 @@ class ManualWorkoutFormWidgetsMixin:
row = tk.Frame(parent, bg=self._colors.palette.bg)
tk.Label(
row,
text=(
f"RPE — perceived exertion "
f"({MANUAL_WORKOUT_RPE_MIN}-{MANUAL_WORKOUT_RPE_MAX}):"
),
# Was "RPE — perceived exertion (1-10):": effort bars + range.
text=f"▁▃▅▇ {MANUAL_WORKOUT_RPE_MIN}-{MANUAL_WORKOUT_RPE_MAX}",
font=self._colors.font("label"),
fg=self._colors.palette.fg,
bg=self._colors.palette.bg,

View File

@ -6,14 +6,19 @@ mixins, so the class's public surface is unchanged.
Every method here is display-only: it reads the snapshot it is handed and
paints widgets. Nothing in this module writes to disk or reaches the network.
textgate: no section has a heading or a sentence any more. Each is one or
two lines of glyphs (``_glyphs``) and numbers, coloured by state. Weekdays
are positions in a Mon..Sun row, not names.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker._earned import hhmm
from screen_locker._sync_status import format_sync_line, gather_sync_status
from screen_locker._sync_status import gather_sync_status
if TYPE_CHECKING:
import tkinter as tk
@ -30,56 +35,46 @@ if TYPE_CHECKING:
class StatusSectionsMixin:
"""Renders each section of the status window from a snapshot."""
def _day_cell(self, day: DayStatus) -> str:
"""One day as a glyph: its entries, sick, or an empty circle."""
if day.entry_types:
return g.entry_glyphs(day.entry_types)
return g.WEEK_SICK if day.is_sick_day else g.WEEK_EMPTY
def _section_today(self, parent: tk.Widget, day: DayStatus) -> None:
"""Render today's outcome."""
"""Render today's outcome (was "✓ Today (Wed Nov 11): phone_verified")."""
del parent
mark = "✓" if day.counted else ("😷" if day.is_sick_day else "—")
entry_str = ", ".join(day.entry_types) or (
"sick day" if day.is_sick_day else "no entry yet"
)
self._text(
f"{mark} Today ({day.label}): {entry_str}",
role="body",
mark = g.OK if day.counted else (g.SICK if day.is_sick_day else g.FAIL)
self._label(
f"{mark} {self._day_cell(day)}",
role="title",
color=self._colors.palette.success
if day.counted
else self._colors.palette.warning,
)
if day.source:
# Secondary provenance note on an already-shown entry -- a
# deliberately caption-sized exception to the 16px floor.
self._text(
day.source, role="caption", color=self._colors.palette.muted, pad="xs"
)
def _section_week(self, parent: tk.Widget, week: WeeklySummary) -> None:
"""Render this ISO week's per-day breakdown and totals."""
"""Render this ISO week: dots + count, then one cell per day.
Was "This Week: 2/4", a "Mon Nov 09: no entry" line per day and "Need
2 more this week." / "1 above the weekly minimum!".
"""
del parent
self._label(
f"This Week: {week.counted_count}/{week.minimum}", role="body", pad="sm"
enough = week.remaining <= 0
self._text(
g.dots(week.counted_count, week.minimum),
role="title",
color=self._colors.palette.success
if enough
else self._colors.palette.warning,
pad="sm",
)
self._text(
" ".join(self._day_cell(day) for day in week.days),
role="body",
color=self._colors.palette.muted,
pad="xs",
)
for day in week.days:
mark = "✓" if day.counted else ("😷" if day.is_sick_day else "·")
entry_str = ", ".join(day.entry_types) or (
"sick day" if day.is_sick_day else "no entry"
)
self._text(
f"{mark} {day.label}: {entry_str}",
role="body",
color=self._colors.palette.muted,
pad="xs",
)
if week.remaining > 0:
self._text(
f"Need {week.remaining} more this week.",
role="body",
color=self._colors.palette.warning,
)
elif week.extra > 0:
self._text(
f"{week.extra} above the weekly minimum!",
role="body",
color=self._colors.palette.success,
)
def _section_streak(
self, parent: tk.Widget, streak: int, week_rewards: tuple[str, ...] = ()
@ -87,29 +82,23 @@ class StatusSectionsMixin:
"""Render the consecutive 5+-workout-week streak and this week's reward.
Display only, and exactly the stored values (``extra_benefits_state``):
a streak of 0 is said plainly, never padded or rounded up. Nothing here
grants time or relaxes a lock. The early-bird extension is not shown:
it no longer changes anything (wake-alarm owns early bird).
a streak of 0 is shown as 0, never padded or rounded up. Nothing here
grants time or relaxes a lock. Was "🔥 N-week streak (5+ workouts a
week)" / "No streak yet: ..." and the reward sentences.
"""
del parent
self._label("Workout streak", role="body", pad="sm")
if streak > 0:
self._text(
f"🔥 {streak}-week streak (5+ workouts a week)",
role="body",
color=self._colors.palette.success,
)
else:
self._text(
"No streak yet: 5+ workouts in a week starts one.",
role="body",
color=self._colors.palette.muted,
)
self._text(
f"{g.STREAK * min(streak, 10)} {streak}" if streak else f"{g.STREAK} 0",
role="body",
color=self._colors.palette.success
if streak
else self._colors.palette.muted,
)
for message in week_rewards:
# A reset is news, not a celebration: it must not be painted green.
lost = message.startswith("Streak reset")
self._text(
message,
f"{g.STREAK}{g.FAIL}" if lost else f"{g.STREAK}{g.GIFT}",
role="body",
color=self._colors.palette.warning
if lost
@ -119,32 +108,30 @@ class StatusSectionsMixin:
def _section_lock_explanation(
self, parent: tk.Widget, expl: LockExplanation
) -> None:
"""Render why the lock did/didn't fire today, plus its evaluation trace."""
"""Render whether the lock fired today and the stage that decided it.
Was "Why the lock did/didn't fire" over the stage's sentence.
"""
del parent
self._label("Why the lock did/didn't fire", role="body", pad="sm")
square = g.LOCK if expl.fired else g.UNLOCK
self._text(
expl.reason,
role="body",
f"{square} {g.STAGE_GLYPH.get(expl.stage, '')}".rstrip(),
role="title",
color=self._colors.palette.danger
if expl.fired
else self._colors.palette.success,
)
if expl.auto_upgrade.would_attempt:
self._text(
f"Pending auto-upgrade: {expl.auto_upgrade.reason}",
role="label",
color=self._colors.palette.warning,
)
self._text(g.RETRY, role="label", color=self._colors.palette.warning)
def _section_manual_workout_budget(
self, parent: tk.Widget, manual: ManualWorkoutBudgetStatus
) -> None:
"""Render rolling manual-workout budget usage."""
"""Render rolling manual-workout budget usage (7-day, then 30-day)."""
del parent
self._label("Manual Workout Budget", role="body", pad="sm")
self._text(
f"{manual.used_7d}/{manual.budget_7d} week · "
f"{manual.used_30d}/{manual.budget_30d} month",
f"{g.FORM} {manual.used_7d}/{manual.budget_7d} · "
f"{manual.used_30d}/{manual.budget_30d}",
role="body",
color=self._colors.palette.danger
if manual.exhausted
@ -152,7 +139,7 @@ class StatusSectionsMixin:
)
def _section_sync_backend(self, parent: tk.Widget) -> None:
"""Render which backend this machine syncs through.
"""Render whether this machine's sync is healthy, and its peer count.
Read from local state only (see :mod:`screen_locker._sync_status`), so
opening or refreshing the window never makes a network call. Coloured
@ -162,9 +149,8 @@ class StatusSectionsMixin:
"""
del parent
status = gather_sync_status()
self._label("Sync backend", role="body", pad="sm")
self._text(
format_sync_line(status),
f"{g.SYNC} {g.OK if status.healthy else g.FAIL} {status.peer_count}",
role="body",
color=self._colors.palette.muted
if status.healthy
@ -174,41 +160,25 @@ class StatusSectionsMixin:
def _section_shutdown(
self, parent: tk.Widget, shutdown: ShutdownProjection
) -> None:
"""Render tonight's live config, rest-of-week, and next-week preview."""
"""Render tonight's live config, rest-of-week, and next-week preview.
Was "Live config — Mon-Wed 21:00, Thu-Sun 22:00", "Rest of week: Mon
21:00, ...", "Next week (speculative): ..." and an explanation. Now
the times only, in day order: live config bold, the rest muted.
"""
del parent
self._label("Shutdown Time", role="body", pad="sm")
if shutdown.tonight is not None:
mon_wed, thu_sun, _morning = shutdown.tonight
self._text(
f"Live config — Mon-Wed {hhmm(mon_wed)}, Thu-Sun {hhmm(thu_sun)}",
role="body",
)
self._text(f"{g.SHUTDOWN} {hhmm(mon_wed)} · {hhmm(thu_sun)}", role="title")
else:
self._text(
"Live shutdown config unavailable.",
role="body",
f"{g.SHUTDOWN} {g.FAIL}",
role="title",
color=self._colors.palette.warning,
)
# Rest-of-week/next-week/explanation are speculative annotations, not
# the section's primary content -- a deliberate caption-sized
# exception to the 16px floor, all sharing one muted tone instead of
# three unrelated ad hoc grays.
rest_line = ", ".join(
f"{d.label} {hhmm(d.minutes)}" for d in shutdown.rest_of_week
)
self._text(
f"Rest of week: {rest_line}",
role="caption",
color=self._colors.palette.muted,
)
next_line = ", ".join(
f"{d.label} {hhmm(d.minutes)}" for d in shutdown.next_week_preview
)
self._text(
f"Next week (speculative): {next_line}",
role="caption",
color=self._colors.palette.muted,
)
self._text(
shutdown.explanation, role="caption", color=self._colors.palette.muted
)
for days in (shutdown.rest_of_week, shutdown.next_week_preview):
self._text(
" ".join(hhmm(d.minutes) for d in days),
role="caption",
color=self._colors.palette.muted,
)

View File

@ -11,10 +11,12 @@ from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from datetime import date
import logging
from typing import TYPE_CHECKING
import earned_time
from screen_locker import _glyphs as g
from screen_locker._day import today_str
from screen_locker._earned import extra_minutes, span
from screen_locker._status_data import gather_status
@ -29,6 +31,9 @@ if TYPE_CHECKING:
from screen_locker._workout_credit import WorkoutCreditResult
_logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class PhoneCheckOutcome:
"""Result of the "Check Phone" button's verify-then-backfill chain.
@ -73,7 +78,9 @@ def _backfill_week_and_apply_bonus(verifier: ScreenLocker) -> str | None:
workout above the weekly minimum); it is a separate source with its own
dedup and is out of scope for the RunnerUp credit fix.
Returns a human-readable summary if anything was filled, else ``None``.
Returns a glyph summary if anything was filled, else ``None``:
``↻●━━● +N`` and, with a bonus, `` ⏻ +1h`` (textgate; was "Auto-filled
N workouts from earlier this week. +1h shutdown time.").
"""
prev_count = count_weekly_workouts(verifier.log_file)
filled = verifier._scan_and_fill_week_runnerup(
@ -93,10 +100,9 @@ def _backfill_week_and_apply_bonus(verifier: ScreenLocker) -> str | None:
filled += sl_filled
if not filled:
return None
plural = "workout" if filled == 1 else "workouts"
message = f"Auto-filled {filled} {plural} from earlier this week."
message = f"{g.RETRY}{g.LIFT} +{filled}"
if bonus > 0:
message += f" +{span(bonus)} shutdown time."
message += f" {g.SHUTDOWN} +{span(bonus)}"
return message
@ -184,10 +190,8 @@ class PhoneCheckMixin:
if outcome.credited_type == "runnerup_verified"
else outcome.phone_message
)
source_label = (
"RunnerUp"
if outcome.credited_type == "runnerup_verified"
else "StrongLifts"
source_glyph = (
g.RUN if outcome.credited_type == "runnerup_verified" else g.LIFT
)
verifier = self.verifier_factory(self.log_file)
verifier.workout_data = {
@ -196,24 +200,27 @@ class PhoneCheckMixin:
}
credit = verifier._apply_workout_credit()
self._credit_message = "\n".join(
self._credit_result_lines(f"{source_label} verified: {message}", credit)
self._credit_result_lines(f"{source_glyph} {g.OK}", credit)
)
elif outcome.week_fill_message is not None:
self._credit_message = outcome.week_fill_message
else:
# The reasons are logged; the window shows the failure glyphs.
_logger.warning(
"Check Phone found nothing: StrongLifts: %s · RunnerUp: %s",
outcome.phone_message,
outcome.runnerup_message,
)
self._phone_check_result = (
outcome.status,
(
f"StrongLifts: {outcome.phone_message} · "
f"RunnerUp: {outcome.runnerup_message}"
),
f"{g.LIFT}{g.FAIL} {g.RUN}{g.FAIL}",
)
self.render(gather_status())
def _credit_result_lines(
self, header: str, credit: WorkoutCreditResult
) -> list[str]:
"""Human-readable outcome lines for an applied workout credit.
"""Glyph outcome lines for an applied workout credit (no words).
Shared by the "Check Phone" verify path and the "Log Manual Workout"
path so both report the reward identically: the base +2h shutdown push
@ -223,12 +230,11 @@ class PhoneCheckMixin:
"""
lines = [header]
if credit.already_counted_today:
lines.append("(Already recorded today — no additional credit.)")
# Was "(Already recorded today — no additional credit.)".
lines.append(f"{g.OK}{g.OK} {g.GIFT}0")
return lines
if credit.shutdown_adjusted:
lines.append("Shutdown time +2h later!")
lines.append(f"{g.SHUTDOWN} {g.GIFT}{span(120)}")
if credit.extra_bonus_delta > 0:
lines.append(
f"Extra workout today! +{span(credit.extra_bonus_delta)} tonight"
)
lines.append(f"{g.LIFT} {g.GIFT}{span(credit.extra_bonus_delta)}")
return lines

View File

@ -15,8 +15,10 @@ writes to ``log.json``. Host class must provide:
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker._constants import HEAT_SKIP_CITY, HEAT_SKIP_TEMP_THRESHOLD
from screen_locker._temperature import HARD_TIMEOUT_SECONDS, submit_background
@ -25,54 +27,45 @@ if TYPE_CHECKING:
from screen_locker._temperature import TemperatureCheck
_logger = logging.getLogger(__name__)
class TemperatureStatusMixin:
"""Provides the background Warsaw-temperature fetch/poll/render."""
def _section_temperature(self, parent: tk.Widget) -> None:
"""Render the live Warsaw temperature.
"""Render the live temperature against the heat-skip threshold.
The same reading the real locker's heat-skip check would see,
fetched in the background.
fetched in the background. textgate: was "Warsaw Temperature" and a
sentence per state; now ``▲`` with the reading (or wait / clock-fail /
fail glyphs), danger-coloured with ``↷`` when it would heat-skip.
"""
del parent
self._label("Warsaw Temperature", role="body", pad="sm")
result = self._temp_result
palette = self._colors.palette
if result is None:
self._text(
"Checking Warsaw temperature…",
role="caption",
color=self._colors.palette.muted,
)
self._text(f"{g.HEAT} {g.WAIT}", role="body", color=palette.muted)
return
if result.timed_out:
_logger.warning(
"Temperature check timed out after ~%ds", int(HARD_TIMEOUT_SECONDS)
)
self._text(
f"Warsaw temperature check timed out after ~"
f"{int(HARD_TIMEOUT_SECONDS)}s — network may be down.",
role="caption",
color=self._colors.palette.warning,
f"{g.HEAT} {g.CLOCK}{g.FAIL}", role="body", color=palette.warning
)
return
if result.temp_celsius is None:
self._text(
"Warsaw temperature check failed (network/API error).",
role="caption",
color=self._colors.palette.warning,
)
self._text(f"{g.HEAT} {g.FAIL}", role="body", color=palette.warning)
return
hot = result.temp_celsius >= HEAT_SKIP_TEMP_THRESHOLD
relation = "≥" if hot else "<"
self._text(
f"Warsaw: {result.temp_celsius:.0f}°C (heat-skip threshold "
f"{HEAT_SKIP_TEMP_THRESHOLD}°C)",
role="caption",
color=self._colors.palette.warning if hot else self._colors.palette.muted,
f"{g.HEAT} {result.temp_celsius:.0f}°C {relation} "
f"{HEAT_SKIP_TEMP_THRESHOLD}°C" + (f" {g.SKIP}" if hot else ""),
role="body",
color=palette.danger if hot else palette.muted,
)
if hot:
self._text(
"Would trigger heat-skip today.",
role="caption",
color=self._colors.palette.danger,
)
def _start_temperature_check(self) -> None:
"""Submit a background Warsaw-temperature fetch and start polling it.

View File

@ -1,10 +1,18 @@
"""UI flow methods mixin for the screen locker."""
"""UI flow methods mixin for the screen locker.
textgate: every screen here is glyphs (``_glyphs``) plus numbers, with the
palette colour as the second channel. The sentences these screens used to
paint ("No Workout Found", the verifier's reason, the sync diagnosis) go to
the log at warning instead, so the reason is never lost, only unpainted.
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
import logging
from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker import _manual_workout
from screen_locker._source_health import collect_source_findings, explain_findings
from screen_locker._ui_flows_lockout import LockoutFlowMixin
@ -14,6 +22,8 @@ from screen_locker._ui_flows_sick_panel import SickPanelFlowMixin
if TYPE_CHECKING:
from collections.abc import Callable
_logger = logging.getLogger(__name__)
class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
"""Mixin providing UI flow logic for the screen locker.
@ -28,15 +38,16 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
Split from :meth:`_start_phone_check` so the fit check
(``scripts/verify_screen_fits.py``) can measure this screen without
starting a background thread that talks to a phone over adb.
Was "Checking phone..." / "Looking for today's workout in StrongLifts".
"""
self.clear_container()
self._label(
"Checking phone...",
f"{g.PHONE} {g.LIFT}",
role="display",
color=self._colors.palette.warning,
pad="lg",
)
self._text("Looking for today's workout in StrongLifts...", role="body")
self._text(g.WAIT, role="display", color=self._colors.palette.muted)
def _start_phone_check(self) -> None:
"""Check phone for today's workout immediately at startup."""
@ -54,23 +65,39 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
else:
self.root.after(500, self._poll_phone_check)
def _show_retry_and_sick(self, message: str) -> None:
"""Show TRY AGAIN, I'm sick and (budget allowing) the manual log."""
def _show_retry_and_sick(self, message: str, *, status: str = "") -> None:
"""Show retry, I'm sick and (budget allowing) the manual log.
Was "No Workout Found" over *message*. The screen now shows the
failure glyph for *status*; *message* goes to the log.
"""
_logger.warning("No workout accepted (%s): %s", status or "?", message)
self.clear_container()
self._label(
"No Workout Found",
f"{g.LIFT} {g.FAIL}",
role="display",
color=self._colors.palette.danger,
pad="md",
)
self._text(message, color=self._colors.palette.warning)
if status:
self._text(
g.status_glyph(status),
role="display",
color=self._colors.palette.warning,
)
# Never accuse the user of skipping a workout the machine simply could
# not see. On 2026-08-24 this screen said "No Workout Found" after a
# 1h57m session, because Firebase was unreadable and the GitHub mirror
# had been stale for nine days -- neither of which was shown here.
diagnosis = explain_findings(collect_source_findings())
if diagnosis:
self._text(diagnosis, color=self._colors.palette.muted)
# Now a sync-fault glyph, one per finding; the prose is logged.
findings = collect_source_findings()
if findings:
_logger.warning("%s", explain_findings(findings))
self._text(
f"{g.SYNC}{g.FAIL} " * len(findings),
role="title",
color=self._colors.palette.warning,
)
self._text(
_manual_workout.budget_summary(self.log_file),
color=self._colors.palette.muted,
@ -78,44 +105,47 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
frame = self._button_row()
self._button(
frame,
"TRY AGAIN",
g.RETRY,
bg=self._colors.palette.accent,
command=self._start_phone_check,
width=12,
width=4,
).pack(side="left", padx=self._colors.space("sm"))
self._sick_button(frame)
if self._mw_budget_closed():
self._text(
"Manual-workout budget exhausted. No manual-log option available.",
color=self._colors.palette.danger,
)
# Was "Manual-workout budget exhausted. No manual-log option".
self._text(f"{g.FORM} {g.CLOSE}", color=self._colors.palette.danger)
else:
self._button(
frame,
"Log Manual Workout",
g.FORM,
bg=self._colors.palette.accent,
command=self._show_manual_workout_form,
width=16,
width=4,
).pack(side="left", padx=self._colors.space("sm"))
def _on_manual_workout_saved(self, entry: dict) -> None:
"""Show confirmation and unlock after a manual-workout entry is built."""
self.workout_data = entry
def _paint_accepted(self, glyph: str) -> None:
"""Paint "accepted, unlocking" and schedule the unlock.
Was "✓ Workout Verified!" / "✓ Run Verified!" / "✓ Manual Workout
Logged!" over the source line and "Unlocking...".
"""
self.clear_container()
self._label(
"✓ Manual Workout Logged!",
f"{glyph} {g.OK}",
role="display",
scale=1.3,
color=self._colors.palette.success,
pad="lg",
)
self._text(
entry.get("source", ""), role="subtitle", color=self._colors.palette.success
)
self._text("Unlocking...", role="body", color=self._colors.palette.muted)
self._text(g.WAIT, role="display", color=self._colors.palette.muted)
unlock_delay = 1500 if self.demo_mode else 2000
self.root.after(unlock_delay, self.unlock_screen)
def _on_manual_workout_saved(self, entry: dict) -> None:
"""Show confirmation and unlock after a manual-workout entry is built."""
self.workout_data = entry
self._paint_accepted(g.FORM)
def _on_manual_workout_cancelled(self) -> None:
"""Return to the retry screen when the manual-workout form is cancelled."""
self._start_phone_check()
@ -125,39 +155,13 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
if status == "verified":
self.workout_data["type"] = "phone_verified"
self.workout_data["source"] = message
self.clear_container()
self._label(
"✓ Workout Verified!",
role="display",
scale=1.3,
color=self._colors.palette.success,
pad="lg",
)
self._text(message, role="subtitle", color=self._colors.palette.success)
self._text("Unlocking...", role="body", color=self._colors.palette.muted)
unlock_delay = 1500 if self.demo_mode else 2000
self.root.after(unlock_delay, self.unlock_screen)
elif status == "too_short":
self._show_retry_and_sick(
f"❌ {message}\n\n"
"Your workout was too short!\n"
"Actually do the full workout, don't just\n"
"spam through the exercises.",
)
elif status == "clock_tampered":
self._show_retry_and_sick(
f"❌ {message}\n\n"
"System clock appears to be manipulated.\n"
"Fix your system time and try again.",
)
self._paint_accepted(g.LIFT)
elif status in ("too_short", "clock_tampered"):
self._show_retry_and_sick(message, status=status)
elif status in ("stale", "no_exercises", "not_verified"):
# Try RunnerUp before showing failure — user may have run instead of lifted.
self._start_runnerup_fallback(
lambda: self._show_retry_and_sick(
f"❌ {message}\n\n"
"Neither StrongLifts nor RunnerUp found a workout today.\n"
"Go do your workout first!",
)
lambda: self._show_retry_and_sick(message, status=status)
)
else:
# no_phone or error — try RunnerUp first, then penalty timer.
@ -168,15 +172,16 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
Shows a waiting screen, runs the check in a background thread, then
either unlocks (run verified) or calls ``on_failure``.
Was "Checking RunnerUp..." / "Looking for today's run in RunnerUp".
"""
self.clear_container()
self._label(
"Checking RunnerUp...",
f"{g.PHONE} {g.RUN}",
role="display",
color=self._colors.palette.warning,
pad="lg",
)
self._text("Looking for today's run in RunnerUp...", role="body")
self._text(g.WAIT, role="display", color=self._colors.palette.muted)
executor = ThreadPoolExecutor(max_workers=1)
self._runnerup_future = executor.submit(self._verify_runnerup_workout)
executor.shutdown(wait=False)
@ -190,20 +195,7 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
if status == "verified":
self.workout_data["type"] = "runnerup_verified"
self.workout_data["source"] = message
self.clear_container()
self._label(
"✓ Run Verified!",
role="display",
scale=1.3,
color=self._colors.palette.success,
pad="lg",
)
self._text(message, role="subtitle", color=self._colors.palette.success)
self._text(
"Unlocking...", role="body", color=self._colors.palette.muted
)
unlock_delay = 1500 if self.demo_mode else 2000
self.root.after(unlock_delay, self.unlock_screen)
self._paint_accepted(g.RUN)
else:
self._runnerup_on_failure()
else:

View File

@ -7,8 +7,10 @@ Split out of :mod:`screen_locker._ui_flows` to keep every file under the
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker._constants import (
NO_PHONE_EXTRA_LOCKOUT_SECONDS,
PHONE_PENALTY_DELAY_DEMO,
@ -18,6 +20,8 @@ from screen_locker._constants import (
if TYPE_CHECKING:
from collections.abc import Callable
_logger = logging.getLogger(__name__)
class LockoutFlowMixin:
"""Lockout countdown and the no-phone penalty timer."""
@ -27,10 +31,14 @@ class LockoutFlowMixin:
# ------------------------------------------------------------------
def lockout(self) -> None:
"""Display lockout screen with countdown timer."""
"""Display lockout screen with countdown timer.
Was "Go work out! Locked for N seconds": the barbell in the danger
colour over the seconds counting down.
"""
self.clear_container()
self.lockout_label = self._label(
f"Go work out!\nLocked for {self.lockout_time} seconds",
g.LIFT,
role="display",
scale=1.5,
color=self._colors.palette.danger,
@ -61,7 +69,13 @@ class LockoutFlowMixin:
def _show_phone_penalty(
self, message: str, *, on_done: Callable[[], None] | None = None
) -> None:
"""Show penalty countdown when phone verification is unavailable."""
"""Show penalty countdown when phone verification is unavailable.
Was "Cannot Verify Workout", the reason, and "Connect phone via ADB
to skip this wait, or wait for the penalty timer". Now the phone glyph
crossed out over the seconds left; the reason goes to the log.
"""
_logger.warning("Phone check unavailable, penalty wait: %s", message)
self.clear_container()
self._phone_penalty_done_fn: Callable[[], None] = (
on_done
@ -80,18 +94,11 @@ class LockoutFlowMixin:
else base_delay + NO_PHONE_EXTRA_LOCKOUT_SECONDS
)
self._label(
"Cannot Verify Workout",
f"{g.PHONE}{g.FAIL}",
role="display",
color=self._colors.palette.warning,
pad="md",
)
self._text(message, color=self._colors.palette.warning)
self._text(
"Connect phone via ADB to skip this wait,\n"
"or wait for the penalty timer.\n\n"
"Note: Phone must be rooted and StrongLifts installed.",
role="body",
)
self.phone_penalty_remaining = delay
self.phone_penalty_label = self._label(
str(delay),

View File

@ -1,15 +1,23 @@
"""Relaxed-day (Tue/Wed/Thu) UI flow methods mixin."""
"""Relaxed-day (Tue/Wed/Thu) UI flow methods mixin.
textgate: glyphs and numbers only (``_glyphs``); the verifier's reason goes
to the log, not the screen.
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
import logging
from screen_locker import _glyphs as g
from screen_locker._weekly_check import (
RELAXED_DAY_SKIP_TYPE,
WEEKLY_WORKOUT_MINIMUM,
count_weekly_workouts,
)
_logger = logging.getLogger(__name__)
class UIFlowsRelaxedMixin:
"""Mixin providing the relaxed-day UI flow logic."""
@ -23,36 +31,39 @@ class UIFlowsRelaxedMixin:
The screen is not locked — the user can skip freely or voluntarily
import a Stronglift workout that counts toward the weekly minimum.
Was "Optional Day (Tue / Wed / Thu)" / "Weekly workouts: N / M. No
penalty for skipping today." / "Skip — No Penalty" / "Log Stronglift
Workout": now the optional-day diamond, the week as dots + numbers,
skip (green) and the barbell (go).
"""
count = count_weekly_workouts(self.log_file)
self.clear_container()
self._label(
"Optional Day (Tue / Wed / Thu)",
role="title",
g.OPTIONAL,
role="display",
color=self._colors.palette.warning,
pad="md",
)
self._text(
f"Weekly workouts: {count} / {WEEKLY_WORKOUT_MINIMUM}\n"
"No penalty for skipping today.",
role="subtitle",
g.dots(count, WEEKLY_WORKOUT_MINIMUM),
role="title",
color=self._colors.palette.muted,
pad="sm",
)
frame = self._button_row()
self._button(
frame,
"Skip — No Penalty",
g.SKIP,
bg=self._colors.palette.success,
command=self._skip_relaxed_day,
width=18,
width=4,
).pack(side="left", padx=self._colors.space("sm"))
self._button(
frame,
"Log Stronglift Workout",
f"{g.GO} {g.LIFT}",
bg=self._colors.palette.accent,
command=self._start_relaxed_phone_check,
width=20,
width=8,
).pack(side="left", padx=self._colors.space("sm"))
# Skipping is free here, but a sick day is more than a skip: it
# stands every gate down and lifts tonight's shutdown to 20:00.
@ -74,12 +85,12 @@ class UIFlowsRelaxedMixin:
"""Run Stronglift check in relaxed mode (no screen grab)."""
self.clear_container()
self._label(
"Checking phone...",
f"{g.PHONE} {g.LIFT}",
role="display",
color=self._colors.palette.warning,
pad="lg",
)
self._text("Looking for today's workout in StrongLifts...", role="body")
self._text(g.WAIT, role="display", color=self._colors.palette.muted)
executor = ThreadPoolExecutor(max_workers=1)
self._phone_future = executor.submit(self._verify_phone_workout)
executor.shutdown(wait=False)
@ -108,30 +119,34 @@ class UIFlowsRelaxedMixin:
self._show_relaxed_retry(message, status)
def _show_relaxed_retry(self, message: str, status: str) -> None:
"""Show retry and skip-close when workout not found in relaxed mode."""
"""Show retry and skip-close when workout not found in relaxed mode.
Was "No Workout Found" / the reason / "TRY AGAIN" / "Close (Skip)".
"""
_logger.warning("Relaxed-day check found no workout (%s): %s", status, message)
self.clear_container()
self._label(
"No Workout Found",
f"{g.LIFT} {g.FAIL}",
role="display",
color=self._colors.palette.danger,
pad="md",
)
self._text(
f"❌ {message}\n\nReason: {status}", color=self._colors.palette.warning
g.status_glyph(status), role="display", color=self._colors.palette.warning
)
frame = self._button_row()
self._button(
frame,
"TRY AGAIN",
g.RETRY,
bg=self._colors.palette.accent,
command=self._start_relaxed_phone_check,
width=12,
width=4,
).pack(side="left", padx=self._colors.space("sm"))
self._sick_button(frame)
self._button(
frame,
"Close (Skip)",
g.SKIP,
bg=self._colors.palette.success,
command=self.close,
width=14,
width=4,
).pack(side="left", padx=self._colors.space("sm"))

View File

@ -23,8 +23,10 @@ Split out of :mod:`screen_locker._ui_flows` to keep every file under the
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker._constants import SHUTDOWN_BASE_FILE
from screen_locker._credit_slot import locked_shutdown_state
from screen_locker._sick import mark_today_sick, push_in_background
@ -32,18 +34,20 @@ from screen_locker._sick import mark_today_sick, push_in_background
if TYPE_CHECKING:
import tkinter as tk
_logger = logging.getLogger(__name__)
class SickDayFlowMixin:
"""The one-tap sick-day button and what follows it."""
def _sick_button(self, frame: tk.Widget) -> None:
"""Pack the "I'm sick" button into ``frame``."""
"""Pack the sick-day button (was "I'm sick") into ``frame``."""
self._button(
frame,
"I'm sick",
g.SICK,
bg=self._colors.palette.warning,
command=self.mark_sick_and_unlock,
width=12,
width=4,
).pack(side="left", padx=self._colors.space("sm"))
# The keep-aware alternative (``_ui_flows_sick_panel``), next to it.
self._choose_lockers_link(frame)
@ -78,15 +82,19 @@ class SickDayFlowMixin:
self.close()
def _show_sick_refused(self, message: str) -> None:
"""Say why today could not be marked sick; the lock stays up."""
"""Show that today could not be marked sick; the lock stays up.
Was "Could not mark today as sick" over sickdays' reason; the reason
(a free day, an unreadable pool) now goes to the log.
"""
_logger.warning("Could not mark today sick: %s", message)
self.clear_container()
self._label(
"Could not mark today as sick",
f"{g.SICK} {g.FAIL}",
role="display",
color=self._colors.palette.danger,
pad="md",
)
self._text(message, color=self._colors.palette.warning)
frame = self._button_row()
back = (
self._start_relaxed_day_flow
@ -95,8 +103,8 @@ class SickDayFlowMixin:
)
self._button(
frame,
"Back",
g.BACK,
bg=self._colors.palette.accent,
command=back,
width=12,
width=4,
).pack(side="left", padx=self._colors.space("sm"))

View File

@ -29,6 +29,7 @@ from gatelock import bind_activate
import sickdays
from sickdays.gui import KeepPanel
from screen_locker import _glyphs as g
from screen_locker._sick import stands_down_workout
from screen_locker._surface_group import FrameGroup
@ -39,8 +40,10 @@ if TYPE_CHECKING:
_logger = logging.getLogger(__name__)
LINK_TEXT = "choose lockers…"
KEPT_NOTE = "Workout lock kept — finish the workout to unlock."
# textgate: was "choose lockers…" (sick, then pick) and "Workout lock kept —
# finish the workout to unlock." (sick, but the barbell lock stays).
LINK_TEXT = f"{g.SICK}▾"
KEPT_NOTE = f"{g.SICK} {g.LIFT} {g.LOCK}"
def build_sick_panel(
@ -162,10 +165,10 @@ class SickPanelFlowMixin:
).pack(pady=self._colors.space("md"))
back = self._button(
box,
"Back",
g.BACK,
bg=self._colors.palette.accent,
command=self._close_sick_panel,
width=12,
width=4,
)
back.pack(pady=self._colors.space("sm"))
back.first.focus_set()

View File

@ -3,10 +3,16 @@
Split out of ``screen_lock`` so that module stays inside the repo's 400-line
cap; this is pure view code (paint the credit, then close), which is exactly
the kind of thing the other ``_ui_*`` mixins already own.
textgate: was "Great job! 💪" / "Shutdown time +2h later! 🎁" / "Extra
workout today! +1h tonight" / "🔥 N-week streak (5+ workouts each)" /
"Screen Unlocked!". Now: the open lock in green, then each reward as its
glyph and amount, then the streak as week bars and their count.
"""
from __future__ import annotations
from screen_locker import _glyphs as g
from screen_locker._constants import EXTRA_BENEFITS_FILE
from screen_locker._earned import span
from screen_locker._extra_benefits import current_streak
@ -18,12 +24,12 @@ class UnlockViewMixin:
"""Paints the unlock screen, then closes it."""
def unlock_screen(self) -> None:
"""Apply workout credit and display the success message."""
"""Apply workout credit and display the success glyphs."""
credit = self._apply_workout_credit()
self.clear_container()
self._label(
"Great job! 💪",
f"{g.UNLOCK} {g.OK}",
role="display",
scale=1.5,
color=self._colors.palette.success,
@ -31,22 +37,21 @@ class UnlockViewMixin:
)
if credit.shutdown_adjusted:
self._text(
"Shutdown time +2h later! 🎁",
f"{g.SHUTDOWN} {g.GIFT}{span(120)}",
role="title",
color=self._colors.palette.warning,
)
if credit.extra_bonus_delta > 0:
self._text(
f"Extra workout today! +{span(credit.extra_bonus_delta)} tonight",
f"{g.LIFT} {g.GIFT}{span(credit.extra_bonus_delta)}",
role="subtitle",
color=self._colors.palette.warning,
)
streak = current_streak(EXTRA_BENEFITS_FILE)
if streak >= 1:
self._text(
f"🔥 {streak}-week streak (5+ workouts each)",
f"{g.STREAK * min(streak, 10)} {streak}",
role="label",
color=self._colors.palette.muted,
)
self._text("Screen Unlocked!", role="display", pad="md")
self.root.after(_UNLOCK_DELAY_MS, self.close)

View File

@ -201,9 +201,10 @@ class WindowSetupMixin:
def _setup_demo_close_button(self) -> None:
"""Add close button for demo mode."""
# Was "✕ Close Demo": the cross on the danger fill says it alone.
close_btn = tk.Button(
self.root,
text="✕ Close Demo",
text="✕",
font=self._colors.font("caption"),
bg=self._colors.palette.danger,
fg=self._colors.palette.on_fill,

View File

@ -168,7 +168,9 @@ class ScreenLocker(
self._instance_lock.release()
sys.exit(0)
self.root.on_callback_error = self.on_callback_error
self.root.title("Workout Locker" + (" [DEMO MODE]" if demo_mode else ""))
# textgate: the window is fullscreen, so its title is never painted;
# was "Workout Locker" (+ " [DEMO MODE]"). Nothing matches on it.
self.root.title("")
self.demo_mode = demo_mode
self.lockout_time = 10 if demo_mode else 1800
self._lock: LockWindow | None = None

View File

@ -30,6 +30,7 @@ from typing import TYPE_CHECKING
from gatelock import LockConfig
from screen_locker import _glyphs as g
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
from screen_locker._status_data import (
StatusSnapshot,
@ -112,7 +113,7 @@ class StatusWindow(
"""Redraw the whole window from *snapshot*."""
self._last_snapshot = snapshot
self.clear_container()
self._label("Workout Status", role="title", pad="md")
# textgate: the "Workout Status" heading is gone; see the sections.
self._section_today(self.container, snapshot.today)
self._section_week(self.container, snapshot.week)
self._section_streak(self.container, snapshot.streak, snapshot.week_rewards)
@ -130,44 +131,29 @@ class StatusWindow(
if status == "verified"
else self._colors.palette.warning
)
self._text(f"Phone check ({status}): {message}", role="body", color=color)
self._text(message, role="title", color=color)
if self._credit_message is not None:
self._text(
self._credit_message, role="body", color=self._colors.palette.success
)
# "Check Phone"/"Log Manual Workout" are the primary write actions
# (accent, high contrast per rule 3); "Refresh"/"Close" are secondary
# utility actions (muted) -- two tiers instead of four arbitrary hues.
# Check phone / manual log are the primary write actions (accent,
# high contrast per rule 3); refresh / close are secondary utility
# actions (muted) -- two tiers instead of four arbitrary hues. Was
# "Check Phone" / "Log Manual Workout" / "Refresh" / "Close".
frame = self._button_row()
self._button(
frame,
"Check Phone",
bg=self._colors.palette.accent,
command=self._on_check_phone_clicked,
width=14,
).pack(side="left", padx=self._colors.space("sm"))
buttons = [(g.PHONE, self._colors.palette.accent, self._on_check_phone_clicked)]
if not self._mw_budget_closed():
self._button(
frame,
"Log Manual Workout",
bg=self._colors.palette.accent,
command=self._show_manual_workout_form,
width=16,
).pack(side="left", padx=self._colors.space("sm"))
self._button(
frame,
"Refresh",
bg=self._colors.palette.field_bg,
command=self._on_refresh_clicked,
width=10,
).pack(side="left", padx=self._colors.space("sm"))
self._button(
frame,
"Close",
bg=self._colors.palette.field_bg,
command=self.root.destroy,
width=8,
).pack(side="left", padx=self._colors.space("sm"))
buttons.append(
(g.FORM, self._colors.palette.accent, self._show_manual_workout_form)
)
buttons += [
(g.RETRY, self._colors.palette.field_bg, self._on_refresh_clicked),
(g.CLOSE, self._colors.palette.field_bg, self.root.destroy),
]
for glyph, bg, command in buttons:
self._button(frame, glyph, bg=bg, command=command, width=4).pack(
side="left", padx=self._colors.space("sm")
)
def _on_refresh_clicked(self) -> None:
"""Clear any stale phone-check/credit/temperature results, re-check both."""
@ -192,9 +178,7 @@ class StatusWindow(
verifier.workout_data = entry
credit = verifier._apply_workout_credit()
self._credit_message = "\n".join(
self._credit_result_lines(
f"Manual workout logged: {entry.get('source', '')}", credit
)
self._credit_result_lines(f"{g.FORM} {g.OK}", credit)
)
self.render(gather_status())
@ -221,7 +205,7 @@ def main(argv: list[str] | None = None) -> None:
return
root = tk.Tk()
root.title("Workout Status")
root.title("")
root.configure(bg=_STATUS_COLORS.palette.bg)
root.minsize(560, 200)

View File

@ -37,7 +37,7 @@ def setup_unlock(
if seed_today_type is None:
log_file.write_text("{}")
else:
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
log_file.write_text(
json.dumps(
{

View File

@ -199,7 +199,8 @@ def _isolate_shutdown_base(tmp_path: Path) -> Iterator[None]:
refresh sees an empty unit dir, never the real one.
"""
target = tmp_path / "shutdown_base.json"
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
# Local day, as the code compares it (_day.today_str), not the UTC one.
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
target.write_text(json.dumps(dict.fromkeys(["last_reset_date", *_BONUS], today)))
with (
patch("screen_locker._constants.SHUTDOWN_BASE_FILE", target),

View File

@ -22,7 +22,7 @@ if TYPE_CHECKING:
def _today() -> str:
return datetime.now(tz=UTC).strftime("%Y-%m-%d")
return datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
class TestIsScheduledSkipToday:

View File

@ -19,7 +19,7 @@ if TYPE_CHECKING:
def _today() -> str:
return datetime.now(tz=UTC).strftime("%Y-%m-%d")
return datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
class TestExplainLockDecision:

View File

@ -18,6 +18,10 @@ import pytest
from screen_locker import _credit_notify
from screen_locker.tests.conftest import create_locker
# The toast's glyphs (textgate): the module's own constants, not words.
_SHUTDOWN = _credit_notify._SHUTDOWN
_GAMING = _credit_notify._GAMING
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
@ -64,28 +68,30 @@ class TestCreditBody:
def test_full_body(self) -> None:
"""Shutdown time, tonight's move and the gaming budget."""
body = _credit_notify.credit_body((0, 1200, 0), (0, 1320, 0), 420)
assert body == "Shutdown 22:00 (+2h) \N{MIDDLE DOT} gaming 7.0h"
assert body == f"{_SHUTDOWN} 22:00 (+2h) \N{MIDDLE DOT} {_GAMING} 7.0h"
def test_a_capped_credit_shows_plus_zero(self) -> None:
"""No backwards move is ever shown: the delta floors at zero."""
body = _credit_notify.credit_body((0, 1380, 0), (0, 1320, 0), None)
assert body == "Shutdown 22:00 (+0h)"
assert body == f"{_SHUTDOWN} 22:00 (+0h)"
def test_unknown_before_drops_the_delta(self) -> None:
"""Without the old config there is no move to show."""
assert _credit_notify.credit_body(None, (0, 1320, 0), None) == "Shutdown 22:00"
assert (
_credit_notify.credit_body(None, (0, 1320, 0), None) == f"{_SHUTDOWN} 22:00"
)
def test_unreadable_after_warns_and_shows_gaming_only(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""An unreadable config is said out loud, not silently omitted."""
assert _credit_notify.credit_body(None, None, 90) == "gaming 1.5h"
assert _credit_notify.credit_body(None, None, 90) == f"{_GAMING} 1.5h"
assert _warned(caplog, "unreadable")
def test_nothing_known_still_says_something(self) -> None:
"""An empty body would read as a glitch; say the credit happened."""
body = _credit_notify.credit_body(None, None, None)
assert body == "Credit applied (details unavailable)"
assert body == "\N{CHECK MARK}"
class TestSendNotification:
@ -151,7 +157,7 @@ def test_notify_workout_credit_sends_the_composed_body() -> None:
):
assert _real_notify((0, 1200, 0), (0, 1260, 0), None)
send.assert_called_once_with(
_credit_notify.TITLE, "Shutdown 21:00 (+1h) \N{MIDDLE DOT} gaming 1.0h"
_credit_notify.TITLE, f"{_SHUTDOWN} 21:00 (+1h) \N{MIDDLE DOT} {_GAMING} 1.0h"
)

View File

@ -49,7 +49,7 @@ class TestTryAutoUpgradeEarlyBird:
assert result is True
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
assert data[today][0]["workout_data"]["type"] == "phone_verified"
assert data[today][0]["workout_data"]["after_early_bird"] == "true"

View File

@ -81,7 +81,7 @@ class TestIsEarlyBirdPending:
) -> None:
"""Return False when HMAC verification fails."""
locker = create_locker(mock_tk, tmp_path)
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": today, "hmac": "bad"}))
with (
@ -105,7 +105,7 @@ class TestIsEarlyBirdPending:
) -> None:
"""Return True when today's marker is present and HMAC-valid."""
locker = create_locker(mock_tk, tmp_path)
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": today, "hmac": "sig"}))
with (
@ -125,7 +125,7 @@ class TestIsEarlyBirdPending:
) -> None:
"""Unsigned marker is accepted when no HMAC key is configured."""
locker = create_locker(mock_tk, tmp_path)
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": today}))
with (
@ -163,7 +163,7 @@ class TestSaveEarlyBirdPending:
assert pending_file.exists()
with pending_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
assert data["date"] == today
assert not locker.log_file.exists()

View File

@ -2,8 +2,10 @@
from __future__ import annotations
import re
from unittest.mock import MagicMock
from screen_locker._constants import HEAT_SKIP_CITY, HEAT_SKIP_TEMP_THRESHOLD
from screen_locker._heat_skip import HeatSkipMixin
@ -15,11 +17,15 @@ class _HeatSkipHost(HeatSkipMixin):
self.save_workout_log = MagicMock()
def _button_command(mock_tk: MagicMock, text: str):
def _button_command(mock_tk: MagicMock, name: str):
"""The command of the button created with Tk widget ``name``.
By name, not by glyph: the buttons carry symbols only (textgate).
"""
for call in mock_tk.Button.call_args_list:
if call.kwargs.get("text") == text:
if call.kwargs.get("name") == name:
return call.kwargs["command"]
msg = f"No button with text {text!r} was created"
msg = f"No button named {name!r} was created"
raise AssertionError(msg)
@ -31,7 +37,7 @@ class TestShowHeatSkipDialog:
host = _HeatSkipHost()
def _simulate_click() -> None:
_button_command(mock_tk, "Skip workout")()
_button_command(mock_tk, "skip")()
mock_tk.Tk.return_value.mainloop.side_effect = _simulate_click
assert host._show_heat_skip_dialog(35.0) is True
@ -42,19 +48,21 @@ class TestShowHeatSkipDialog:
host = _HeatSkipHost()
def _simulate_click() -> None:
_button_command(mock_tk, "No, I'll workout")()
_button_command(mock_tk, "decline")()
mock_tk.Tk.return_value.mainloop.side_effect = _simulate_click
assert host._show_heat_skip_dialog(35.0) is False
def test_dialog_shows_temperature_and_threshold(self, mock_tk: MagicMock) -> None:
"""The dialog text shows the rounded temperature and mentions the threshold."""
"""The dialog shows the rounded temperature against the threshold, no words."""
host = _HeatSkipHost()
mock_tk.Tk.return_value.mainloop.side_effect = None
host._show_heat_skip_dialog(36.4)
texts = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
assert any("36°C" in t for t in texts)
assert any("threshold" in t for t in texts)
assert any(f"36°C ≥ {HEAT_SKIP_TEMP_THRESHOLD}°C" in t for t in texts)
# Only the city (config data) may carry letters: no chrome sentence.
chrome = [t.replace(HEAT_SKIP_CITY, "") for t in texts]
assert not any(re.search(r"[A-Za-z]{2,}", t) for t in chrome)
class TestSaveHeatSkipLog:

View File

@ -140,7 +140,7 @@ class TestHasLoggedToday:
) -> None:
"""Test when today's workout is logged with valid HMAC."""
log_file = tmp_path / "log.json"
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
log_file.write_text(
json.dumps({today: {"workout": "data", "hmac": "valid"}}),
)
@ -161,7 +161,7 @@ class TestHasLoggedToday:
) -> None:
"""Test rejects entry when HMAC verification fails."""
log_file = tmp_path / "log.json"
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
log_file.write_text(
json.dumps({today: {"workout": "data", "hmac": "tampered"}}),
)
@ -182,7 +182,7 @@ class TestHasLoggedToday:
) -> None:
"""Accept unsigned entry when HMAC key is unavailable."""
log_file = tmp_path / "log.json"
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
log_file.write_text(
json.dumps({today: {"workout": "data"}}),
)
@ -209,7 +209,7 @@ class TestHasLoggedToday:
) -> None:
"""Reject unsigned entry when HMAC key IS available."""
log_file = tmp_path / "log.json"
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
log_file.write_text(
json.dumps({today: {"workout": "data"}}),
)

View File

@ -36,7 +36,7 @@ class TestSaveWorkoutLog:
assert log_file.exists()
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
assert today in data
# The log now holds a list of entries per day (multiple workouts/day).
assert data[today][0]["workout_data"]["type"] == "running"
@ -61,7 +61,7 @@ class TestSaveWorkoutLog:
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
assert "hmac" not in data[today][0]
def test_save_to_existing_file(
@ -86,7 +86,7 @@ class TestSaveWorkoutLog:
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
assert "2020-01-01" in data
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
assert today in data
def test_save_with_corrupted_existing_file(
@ -110,7 +110,7 @@ class TestSaveWorkoutLog:
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
assert today in data
def test_save_with_write_error(

View File

@ -163,8 +163,11 @@ class TestBudgetSummary:
log_file = tmp_path / "log.json"
_write_logs(log_file, {"2026-07-04": "manual_workout"})
summary = budget_summary(log_file, today=_TODAY)
assert "Manual:" in summary
assert "1/" in summary
# Glyph + used/7-day budget · used/30-day budget, no words.
assert summary == (
f"≡ 1/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS} · "
f"1/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}"
)
_TT_DEFAULT = ManualWorkoutDraft(

View File

@ -8,12 +8,19 @@ from unittest.mock import MagicMock, patch
from screen_locker._day import today_str
from screen_locker._manual_schedule import ScheduleResult
from screen_locker._manual_workout_date import (
BACK_GLYPH,
REJECTED_GLYPH,
SCHEDULED_GLYPH,
)
from screen_locker.tests import test_manual_workout_dialog_part2 as dialog_tests
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
import pytest
_MOD = "screen_locker._manual_workout_date"
@ -32,6 +39,11 @@ def _locker(mock_tk: MagicMock, tmp_path: Path, day: str) -> MagicMock:
return locker
def _warned(caplog: pytest.LogCaptureFixture) -> list[str]:
"""Every WARNING message logged during the test."""
return [r.getMessage() for r in caplog.records if r.levelname == "WARNING"]
class TestBudgetClosed:
"""The button gate reads the local ledger only (no network)."""
@ -66,25 +78,35 @@ class TestHandledByDate:
"""An unparsable date shows an error and schedules nothing."""
locker = _locker(mock_tk, tmp_path, "soon")
assert locker._mw_handled_by_date(MagicMock()) is True
locker._mw_error_label.config.assert_called_once()
locker._mw_error_label.config.assert_called_once_with(text=REJECTED_GLYPH)
locker._show_manual_workout_scheduled.assert_not_called()
def test_a_past_date_shows_the_error(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A date before today is rejected with a message mentioning the past."""
"""A past date shows the fail mark; the reason (the past) is logged."""
locker = _locker(mock_tk, tmp_path, _plus(-1))
assert locker._mw_handled_by_date(MagicMock()) is True
assert "past" in locker._mw_error_label.config.call_args.kwargs["text"]
locker._mw_error_label.config.assert_called_once_with(text=REJECTED_GLYPH)
assert any("past" in m for m in _warned(caplog))
def test_today_over_budget_shows_the_error(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Today's date with no budget left shows the budget error and is handled."""
locker = _locker(mock_tk, tmp_path, today_str())
with patch(f"{_MOD}.budget_error", return_value="budget full"):
assert locker._mw_handled_by_date(MagicMock()) is True
locker._mw_error_label.config.assert_called_once_with(text="budget full")
locker._mw_error_label.config.assert_called_once_with(text=REJECTED_GLYPH)
assert any("budget full" in m for m in _warned(caplog))
def test_today_within_budget_is_left_to_the_host(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
@ -96,14 +118,19 @@ class TestHandledByDate:
locker._mw_error_label.config.assert_not_called()
def test_a_refused_future_entry_shows_why(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A future entry the scheduler refuses shows its reason and no confirmation."""
"""A refused future entry shows the fail mark, logs why, confirms nothing."""
locker = _locker(mock_tk, tmp_path, _plus(2))
refused = ScheduleResult(scheduled=False, record_id="r", reason="no room")
with patch(f"{_MOD}.schedule_future_workout", return_value=refused):
assert locker._mw_handled_by_date(MagicMock()) is True
locker._mw_error_label.config.assert_called_once_with(text="no room")
locker._mw_error_label.config.assert_called_once_with(text=REJECTED_GLYPH)
assert any("no room" in m for m in _warned(caplog))
locker._show_manual_workout_scheduled.assert_not_called()
def test_a_scheduled_future_entry_shows_the_confirmation(
@ -116,7 +143,7 @@ class TestHandledByDate:
with patch(f"{_MOD}.schedule_future_workout", return_value=done) as schedule:
assert locker._mw_handled_by_date(draft) is True
schedule.assert_called_once_with(locker.log_file, draft, _plus(2))
locker._show_manual_workout_scheduled.assert_called_once_with("scheduled")
locker._show_manual_workout_scheduled.assert_called_once_with(_plus(2))
locker._mw_error_label.config.assert_not_called()
@ -134,18 +161,18 @@ class TestScheduledConfirmation:
object.__setattr__(locker, "_on_manual_workout_cancelled", cancelled)
mock_tk.Button.reset_mock()
locker._show_manual_workout_scheduled("scheduled for tomorrow")
locker._show_manual_workout_scheduled("2026-11-13")
buttons = {
c.kwargs.get("text"): c.kwargs for c in mock_tk.Button.call_args_list
}
assert set(buttons) == {"OK"}
buttons["OK"]["command"]()
assert set(buttons) == {BACK_GLYPH}
buttons[BACK_GLYPH]["command"]()
cancelled.assert_called_once_with()
saved.assert_not_called()
texts = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
assert any("Workout Scheduled" in t for t in texts)
assert any("scheduled for tomorrow" in t for t in texts)
assert SCHEDULED_GLYPH in texts
assert "2026-11-13" in texts
class TestSubmitRoutesThroughTheDateRules:

View File

@ -6,6 +6,8 @@ from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker import _manual_workout
from screen_locker._manual_workout_date import BACK_GLYPH
from screen_locker._manual_workout_dialog import EXHAUSTED_GLYPH, SUBMIT_GLYPH
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
@ -25,8 +27,8 @@ class TestShowManualWorkoutForm:
with patch(_CLOSED, return_value=False):
locker._show_manual_workout_form()
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
assert "SUBMIT" in button_texts
assert "BACK" in button_texts
assert SUBMIT_GLYPH in button_texts
assert BACK_GLYPH in button_texts
def test_shows_exhausted_message_and_hides_submit(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
@ -36,10 +38,10 @@ class TestShowManualWorkoutForm:
with patch(_CLOSED, return_value=True):
locker._show_manual_workout_form()
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
assert "BACK" in button_texts
assert "SUBMIT" not in button_texts
assert BACK_GLYPH in button_texts
assert SUBMIT_GLYPH not in button_texts
text_calls = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
assert any("exhausted" in t for t in text_calls)
assert EXHAUSTED_GLYPH in text_calls
class TestSportToggle:

View File

@ -6,6 +6,7 @@ import pathlib
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker import _glyphs as g
from screen_locker.tests.conftest import create_locker
# The Dart mirror of the budget caps; read at test time so drift on
@ -38,7 +39,7 @@ class TestShowRetryAndManualWorkoutBudget:
):
locker._show_retry_and_sick("nope")
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
assert "Log Manual Workout" in button_texts
assert g.FORM in button_texts
def test_hides_button_when_budget_exhausted(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
@ -52,9 +53,9 @@ class TestShowRetryAndManualWorkoutBudget:
button_texts: set[str] = set()
for call in mock_tk.Button.call_args_list:
button_texts.add(call.kwargs.get("text", ""))
assert "Log Manual Workout" not in button_texts
assert g.FORM not in button_texts
text_calls = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
assert any("Manual-workout budget exhausted" in t for t in text_calls)
assert f"{g.FORM} {g.CLOSE}" in text_calls
class TestOnManualWorkoutSaved:

View File

@ -5,6 +5,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker import _glyphs as g
from screen_locker._workout_credit import WorkoutCreditResult
from screen_locker.tests._status_view_helpers import (
_button_texts,
@ -31,7 +32,7 @@ class TestSectionManualWorkoutBudget:
calls = [
c
for c in mock_tk.Label.call_args_list
if "week" in c.kwargs.get("text", "")
if c.kwargs.get("text", "") == f"{g.FORM} 2/2 · 0/5"
]
assert any(c.kwargs.get("fg") == window._colors.palette.danger for c in calls)
@ -44,7 +45,7 @@ class TestSectionManualWorkoutBudget:
calls = [
c
for c in mock_tk.Label.call_args_list
if "week" in c.kwargs.get("text", "")
if c.kwargs.get("text", "") == f"{g.FORM} 0/2 · 0/5"
]
assert any(c.kwargs.get("fg") == window._colors.palette.muted for c in calls)
@ -57,7 +58,7 @@ class TestManualWorkoutButtonVisibility:
) -> None:
"""The Log Manual Workout button appears while budget remains."""
_make_window(mock_tk, _snapshot(), log_file=temp_log_file)
assert "Log Manual Workout" in _button_texts(mock_tk)
assert g.FORM in _button_texts(mock_tk)
def test_hidden_when_budget_exhausted(
self, mock_tk: MagicMock, temp_log_file: Path
@ -65,7 +66,7 @@ class TestManualWorkoutButtonVisibility:
"""The Log Manual Workout button is hidden once the budget is closed."""
with patch(_CLOSED, return_value=True):
_make_window(mock_tk, _snapshot(), log_file=temp_log_file)
assert "Log Manual Workout" not in _button_texts(mock_tk)
assert g.FORM not in _button_texts(mock_tk)
class TestOnManualWorkoutSaved:
@ -102,8 +103,7 @@ class TestOnManualWorkoutSaved:
fake_verifier._apply_workout_credit.assert_called_once()
message = window._credit_message
assert message is not None
assert "table tennis at Solec" in message
assert "Shutdown time +2h later!" in message
assert message.splitlines() == [f"{g.FORM} {g.OK}", f"{g.SHUTDOWN} +2h"]
def test_shows_extra_bonus_line_and_no_debt(
self, mock_tk: MagicMock, temp_log_file: Path
@ -127,13 +127,12 @@ class TestOnManualWorkoutSaved:
message = window._credit_message
assert message is not None
assert "Extra workout today! +1h tonight" in message
assert "debt" not in message.lower()
assert message.splitlines() == [f"{g.FORM} {g.OK}", f"{g.LIFT} +1h"]
def test_already_counted_today_shows_no_extra_credit_note(
self, mock_tk: MagicMock, temp_log_file: Path
) -> None:
"""A second workout the same day says no additional credit was given."""
"""A second workout the same day shows a zero gift and no reward line."""
credit = WorkoutCreditResult(
shutdown_adjusted=False,
extra_bonus_delta=0,
@ -152,8 +151,7 @@ class TestOnManualWorkoutSaved:
message = window._credit_message
assert message is not None
assert "no additional credit" in message
assert "Shutdown time" not in message
assert message.splitlines() == [f"{g.FORM} {g.OK}", f"{g.OK}{g.OK} +0"]
class TestOnManualWorkoutCancelled:

View File

@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patch
import pytest
from screen_locker import _glyphs as g
from screen_locker.tests._unlock_helpers import setup_unlock
if TYPE_CHECKING:
@ -49,7 +50,7 @@ class TestUnlockScreenExtras:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""extra_bonus_delta > 0 → _text called with 'Extra workout'."""
"""extra_bonus_delta > 0 → _text shows the barbell and the +1h gift."""
locker = setup_unlock(mock_tk, tmp_path, seed_today_type="manual_workout")
# Simulate before=22:00, after=23:00 → delta=60
@ -77,7 +78,7 @@ class TestUnlockScreenExtras:
):
locker.unlock_screen()
assert any("Extra workout" in c for c in text_calls)
assert f"{g.LIFT} {g.GIFT}1h" in text_calls
def test_no_extra_bonus_when_adjust_fails(
self,

View File

@ -64,7 +64,7 @@ class TestTryAutoUpgradeEarlyBirdRunnerUp:
result = locker._try_auto_upgrade_early_bird()
assert result is True
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
data = json.loads(log_file.read_text())
assert data[today][0]["workout_data"]["type"] == "runnerup_verified"
assert data[today][0]["workout_data"]["after_early_bird"] == "true"

View File

@ -12,6 +12,7 @@ from unittest.mock import MagicMock, patch
import pytest
from screen_locker import _glyphs as g
from screen_locker.tests._locker_factories import create_locker
from screen_locker.tests._unlock_helpers import setup_unlock
@ -51,7 +52,7 @@ class TestUnlockScreenRewards:
):
locker.unlock_screen()
assert any("streak" in c.lower() for c in text_calls)
assert f"{g.STREAK * 3} 3" in text_calls
def test_extra_bonus_skipped_when_old_cfg_none(
self,

View File

@ -78,7 +78,7 @@ class TestResetToBaseIfNewDay:
def test_returns_false_when_already_reset_today(self, tmp_path: Path) -> None:
"""Same-day last_reset_date → early False return (line 63)."""
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
f = tmp_path / "state.json"
f.write_text(json.dumps({"last_reset_date": today}))
assert reset_to_base_if_new_day(f, self._make_mixin()) is False

View File

@ -10,6 +10,7 @@ from unittest.mock import MagicMock, patch
import freedays
import sickdays
from screen_locker import _glyphs as g
from screen_locker import _sick, _ui_flows_sick
from screen_locker._auto_upgrade import AutoUpgradeMixin
from screen_locker._compliance_predicates import is_sick_day_today
@ -20,6 +21,8 @@ from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
import pytest
def _button_texts(mock_tk: MagicMock) -> list[str]:
"""Return the text of every Button created on the mocked tk module."""
@ -155,7 +158,7 @@ class TestButtonEverywhere:
"""The retry screen shows the I'm sick button."""
locker = create_locker(mock_tk, tmp_path)
locker._show_retry_and_sick("nope")
assert "I'm sick" in _button_texts(mock_tk)
assert g.SICK in _button_texts(mock_tk)
def test_phone_penalty_screen_offers_it_without_waiting(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
@ -163,7 +166,7 @@ class TestButtonEverywhere:
"""The phone penalty screen shows I'm sick immediately."""
locker = create_locker(mock_tk, tmp_path)
locker._show_phone_penalty("no phone")
assert "I'm sick" in _button_texts(mock_tk)
assert g.SICK in _button_texts(mock_tk)
def test_relaxed_prompt_and_retry_offer_it(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
@ -171,10 +174,10 @@ class TestButtonEverywhere:
"""Both the relaxed-day prompt and its retry screen show I'm sick."""
locker = create_locker_relaxed_day(mock_tk, tmp_path)
locker._start_relaxed_day_flow()
assert "I'm sick" in _button_texts(mock_tk)
assert g.SICK in _button_texts(mock_tk)
mock_tk.Button.reset_mock()
locker._show_relaxed_retry("nothing", "no_workout")
assert "I'm sick" in _button_texts(mock_tk)
assert g.SICK in _button_texts(mock_tk)
class TestTap:
@ -200,9 +203,13 @@ class TestTap:
close.assert_called_once_with()
def test_refusal_stays_locked_and_says_why(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A refused tap keeps the lock, shows the reason and offers a Back button."""
"""A refused tap keeps the lock, shows sick-fail, logs why, offers back."""
locker = create_locker(mock_tk, tmp_path)
close = MagicMock()
object.__setattr__(locker, "close", close)
@ -214,9 +221,15 @@ class TestTap:
locker.mark_sick_and_unlock()
close.assert_not_called()
push.assert_not_called()
assert "today is a free day" in _label_texts(mock_tk)
assert f"{g.SICK} {g.FAIL}" in _label_texts(mock_tk)
assert "today is a free day" not in _label_texts(mock_tk)
assert any(
"today is a free day" in r.getMessage()
for r in caplog.records
if r.levelname == "WARNING"
)
back = next(
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == "Back"
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == g.BACK
)
assert [back.kwargs["command"]] == [locker._start_phone_check]
@ -227,6 +240,6 @@ class TestTap:
locker = create_locker_relaxed_day(mock_tk, tmp_path)
locker._show_sick_refused("nope")
back = next(
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == "Back"
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == g.BACK
)
assert [back.kwargs["command"]] == [locker._start_relaxed_day_flow]

View File

@ -13,6 +13,7 @@ import pytest
import sickdays
import sickdays.gui._panel
from screen_locker import _glyphs as g
from screen_locker import _ui_flows_sick, _ui_flows_sick_panel
from screen_locker._ui_flows_sick_panel import LINK_TEXT, build_sick_panel
from screen_locker.tests.conftest import create_locker
@ -97,15 +98,15 @@ class TestLink:
def test_the_link_sits_next_to_the_one_tap_button(
self, mock_tk: MagicMock, locker: ScreenLocker
) -> None:
"""The link is wired to open_sick_panel and appears right after the "I'm sick" button."""
"""The link is wired to open_sick_panel and sits right after the sick button."""
locker._show_retry_and_sick("nope")
buttons = mock_tk.Button.call_args_list
texts = _texts(mock_tk.Button)
sick = next(c for c in buttons if c.kwargs.get("text") == "I'm sick")
sick = next(c for c in buttons if c.kwargs.get("text") == g.SICK)
link = next(c for c in buttons if c.kwargs.get("text") == LINK_TEXT)
assert sick.kwargs["command"] == locker.mark_sick_and_unlock
assert link.kwargs["command"] == locker.open_sick_panel
assert texts.index(LINK_TEXT) == texts.index("I'm sick") + 1
assert texts.index(LINK_TEXT) == texts.index(g.SICK) + 1
def test_opening_builds_todays_panel_on_a_backdrop(
self, locker: ScreenLocker, panels: list[FakePanel]

View File

@ -8,6 +8,7 @@ from unittest.mock import MagicMock, patch
import pytest
import sickdays
from screen_locker import _glyphs as g
from screen_locker import _ui_flows_sick
from screen_locker._ui_flows_sick_panel import KEPT_NOTE
from screen_locker.tests._sick_helpers import mark_sick
@ -75,7 +76,7 @@ class TestSaved:
assert KEPT_NOTE in _texts(mock_tk.Label)
mock_tk.Button.return_value.focus_set.assert_called_once_with()
back = next(
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == "Back"
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == g.BACK
)
back.kwargs["command"]()
assert locker._sick_overlay is None

View File

@ -4,6 +4,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker.tests._status_view_helpers import (
_make_window,
_snapshot,
@ -14,32 +15,38 @@ if TYPE_CHECKING:
from unittest.mock import MagicMock
def _fg_of(mock_tk: MagicMock, needle: str) -> list[object]:
def _fg_of(mock_tk: MagicMock, text: str) -> list[object]:
"""fg of every Label whose text is exactly *text*."""
return [
c.kwargs.get("fg")
for c in mock_tk.Label.call_args_list
if needle in c.kwargs.get("text", "")
if c.kwargs.get("text", "") == text
]
class TestSectionStreak:
"""Tests for StatusWindow._section_streak (display only)."""
"""Tests for StatusWindow._section_streak (display only, glyphs + numbers)."""
def test_shows_the_real_week_count_in_success_color(
self, mock_tk: MagicMock
) -> None:
"""The streak line shows the real week count in the success colour."""
"""One bar per streak week plus the real count, in the success colour."""
window = _make_window(mock_tk, _snapshot(streak=3))
assert any("3-week streak" in t for t in _texts(mock_tk))
assert window._colors.palette.success in _fg_of(mock_tk, "3-week streak")
line = f"{g.STREAK * 3} 3"
assert line in _texts(mock_tk)
assert window._colors.palette.success in _fg_of(mock_tk, line)
def test_long_streak_caps_the_bars_not_the_number(self, mock_tk: MagicMock) -> None:
"""Past 10 weeks the bars stop growing; the number stays exact."""
_make_window(mock_tk, _snapshot(streak=14))
assert f"{g.STREAK * 10} 14" in _texts(mock_tk)
def test_zero_streak_is_stated_plainly_not_padded(self, mock_tk: MagicMock) -> None:
"""A zero streak reads No streak in the muted colour, with no week count."""
"""A zero streak is one bar and 0, muted, never padded."""
window = _make_window(mock_tk, _snapshot(streak=0))
texts = _texts(mock_tk)
assert any("No streak" in t for t in texts)
assert not any("-week streak" in t for t in texts)
assert window._colors.palette.muted in _fg_of(mock_tk, "No streak")
line = f"{g.STREAK} 0"
assert line in _texts(mock_tk)
assert window._colors.palette.muted in _fg_of(mock_tk, line)
def test_early_bird_is_never_rendered(self, mock_tk: MagicMock) -> None:
"""The 09:00 early-bird extension is gone (wake-alarm owns it)."""
@ -49,19 +56,24 @@ class TestSectionStreak:
def test_week_reward_reaches_the_window_in_success_color(
self, mock_tk: MagicMock
) -> None:
"""A week reward message is shown in the success colour."""
"""A week reward shows as bar + gift, success colour; never its words."""
msg = "5 workouts in 2026-W41! 4-week streak"
window = _make_window(mock_tk, _snapshot(streak=4, week_rewards=(msg,)))
assert msg in _texts(mock_tk)
assert window._colors.palette.success in _fg_of(mock_tk, msg)
assert msg not in _texts(mock_tk)
line = f"{g.STREAK}{g.GIFT}"
assert window._colors.palette.success in _fg_of(mock_tk, line)
def test_no_reward_text_when_the_week_has_none(self, mock_tk: MagicMock) -> None:
"""No reward line appears when the week has no reward."""
def test_no_reward_line_when_the_week_has_none(self, mock_tk: MagicMock) -> None:
"""No reward or reset line appears when the week has no reward."""
_make_window(mock_tk, _snapshot(streak=4))
assert not any("workouts in 20" in t for t in _texts(mock_tk))
texts = _texts(mock_tk)
assert f"{g.STREAK}{g.GIFT}" not in texts
assert f"{g.STREAK}{g.FAIL}" not in texts
def test_a_streak_reset_is_not_painted_as_a_win(self, mock_tk: MagicMock) -> None:
"""A streak-reset message is shown in the warning colour, not as a win."""
"""A streak reset shows as bar + fail in the warning colour, not as a win."""
msg = "Streak reset (was 3 weeks of 5+ workouts)"
window = _make_window(mock_tk, _snapshot(streak=0, week_rewards=(msg,)))
assert window._colors.palette.warning in _fg_of(mock_tk, msg)
assert _fg_of(mock_tk, f"{g.STREAK}{g.FAIL}") == [
window._colors.palette.warning
]

View File

@ -1,9 +1,16 @@
"""Tests for the read-only Tkinter status window's rendering (StatusWindow.render)."""
"""Tests for the read-only Tkinter status window's rendering (StatusWindow.render).
textgate: every section is glyphs (``screen_locker._glyphs``) and numbers,
so these assert glyphs, numbers and colours, never English words.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from gatelock import LockConfig
from screen_locker import _glyphs as g
from screen_locker._compliance_state import AutoUpgradeOpportunity
if TYPE_CHECKING:
@ -18,12 +25,22 @@ from screen_locker.tests._status_view_helpers import (
_week,
)
_PALETTE = LockConfig().palette
def _colored(mock_tk: MagicMock) -> list[tuple[str, str]]:
"""(text, fg) of every Label, in call order."""
return [
(c.kwargs.get("text", ""), c.kwargs.get("fg", ""))
for c in mock_tk.Label.call_args_list
]
class TestSectionToday:
"""SectionToday."""
def test_counted_shows_checkmark_and_entry(self, mock_tk: MagicMock) -> None:
"""Counted shows checkmark and entry."""
"""A counted day shows the tick and its entry's glyph, not the source."""
snap = _snapshot(
today=_day(
entry_types=("phone_verified",),
@ -34,64 +51,53 @@ class TestSectionToday:
)
_make_window(mock_tk, snap)
texts = _texts(mock_tk)
assert any("✓" in t and "phone_verified" in t for t in texts)
assert any(t == "gym" for t in texts)
assert f"{g.OK} {g.LIFT}" in texts
assert "gym" not in texts
def test_sick_day_shows_sick_mark(self, mock_tk: MagicMock) -> None:
"""Sick day shows sick mark."""
"""Sick day shows the sick cross twice: mark and cell."""
snap = _snapshot(today=_day(entry_types=(), is_sick_day=True))
_make_window(mock_tk, snap)
assert any("😷" in t and "sick day" in t for t in _texts(mock_tk))
assert f"{g.SICK} {g.WEEK_SICK}" in _texts(mock_tk)
def test_no_entry_shows_dash(self, mock_tk: MagicMock) -> None:
"""No entry shows dash."""
def test_no_entry_shows_fail_and_empty_circle(self, mock_tk: MagicMock) -> None:
"""No entry: the fail mark over an empty circle, in warning colour."""
snap = _snapshot(today=_day(entry_types=(), is_sick_day=False))
_make_window(mock_tk, snap)
assert any("no entry yet" in t for t in _texts(mock_tk))
assert (f"{g.FAIL} {g.WEEK_EMPTY}", _PALETTE.warning) in _colored(mock_tk)
def test_empty_source_adds_no_extra_line(self, mock_tk: MagicMock) -> None:
"""Empty source adds no extra line."""
snap = _snapshot(
today=_day(
entry_types=("phone_verified",),
counted=True,
day_count=1,
source="",
)
)
def test_unknown_entry_type_falls_back_to_tick(self, mock_tk: MagicMock) -> None:
"""An entry type with no glyph shows as a tick, never as its name."""
snap = _snapshot(today=_day(entry_types=("mystery",), counted=True))
_make_window(mock_tk, snap)
# Only the main "Today (...)" line, no second call for an empty source.
today_related = [t for t in _texts(mock_tk) if "Today" in t]
assert len(today_related) == 1
texts = _texts(mock_tk)
assert f"{g.OK} {g.OK}" in texts
assert not any("mystery" in t for t in texts)
class TestSectionWeek:
"""SectionWeek."""
def test_shows_remaining_message_when_under_minimum(
self, mock_tk: MagicMock
) -> None:
"""Shows remaining message when under minimum."""
def test_under_minimum_is_warning_dots(self, mock_tk: MagicMock) -> None:
"""Under the minimum: filled/empty dots and the count, warning colour."""
snap = _snapshot(week=_week(counted_count=2, remaining=2, extra=0))
_make_window(mock_tk, snap)
assert any("Need 2 more this week." in t for t in _texts(mock_tk))
assert (g.dots(2, 4), _PALETTE.warning) in _colored(mock_tk)
def test_shows_extra_message_when_over_minimum(self, mock_tk: MagicMock) -> None:
"""Shows extra message when over minimum."""
def test_over_minimum_is_success_dots(self, mock_tk: MagicMock) -> None:
"""Over the minimum: the count above the total, success colour."""
snap = _snapshot(week=_week(counted_count=5, remaining=0, extra=1))
_make_window(mock_tk, snap)
assert any("above the weekly minimum" in t for t in _texts(mock_tk))
assert ("●●●● 5/4", _PALETTE.success) in _colored(mock_tk)
def test_shows_neither_message_at_exact_minimum(self, mock_tk: MagicMock) -> None:
"""Shows neither message at exact minimum."""
def test_exact_minimum_is_success(self, mock_tk: MagicMock) -> None:
"""At exactly the minimum the week is met: success colour."""
snap = _snapshot(week=_week(counted_count=4, remaining=0, extra=0))
_make_window(mock_tk, snap)
texts = _texts(mock_tk)
assert not any("Need" in t and "more this week" in t for t in texts)
assert not any("above the weekly minimum" in t for t in texts)
assert (g.dots(4, 4), _PALETTE.success) in _colored(mock_tk)
def test_renders_a_line_per_day(self, mock_tk: MagicMock) -> None:
"""Renders a line per day."""
def test_renders_one_cell_per_day(self, mock_tk: MagicMock) -> None:
"""One row, one cell per day in order, no weekday names."""
days = (
_day(
date="2024-01-01",
@ -106,9 +112,8 @@ class TestSectionWeek:
snap = _snapshot(week=_week(days=days))
_make_window(mock_tk, snap)
texts = _texts(mock_tk)
assert any("Mon Jan 01" in t and "✓" in t for t in texts)
assert any("Tue Jan 02" in t and "😷" in t for t in texts)
assert any("Wed Jan 03" in t and "no entry" in t for t in texts)
assert f"{g.LIFT} {g.WEEK_SICK} {g.WEEK_EMPTY}" in texts
assert not any("Mon" in t for t in texts)
class TestSectionLockExplanation:
@ -117,10 +122,11 @@ class TestSectionLockExplanation:
def test_fired_with_auto_upgrade_and_heat_skip_pending(
self, mock_tk: MagicMock
) -> None:
"""Fired with auto upgrade and heat skip pending."""
"""Fired: the lock square + stage glyph in danger, and a retry mark."""
snap = _snapshot(
lock_explanation=_lock_explanation(
fired=True,
stage="would_lock",
reason="Full lock.",
auto_upgrade=AutoUpgradeOpportunity(
would_attempt=True, via="sick_day", reason="will try phone"
@ -129,19 +135,26 @@ class TestSectionLockExplanation:
)
)
_make_window(mock_tk, snap)
texts = _texts(mock_tk)
assert any(t == "Full lock." for t in texts)
assert any("Pending auto-upgrade: will try phone" in t for t in texts)
colored = _colored(mock_tk)
assert (f"{g.LOCK} {g.LIFT}", _PALETTE.danger) in colored
assert (g.RETRY, _PALETTE.warning) in colored
assert "Full lock." not in _texts(mock_tk)
def test_not_fired_no_auto_upgrade(self, mock_tk: MagicMock) -> None:
"""Not fired no auto upgrade."""
"""Not fired: the open square + stage glyph in success, no retry mark."""
snap = _snapshot(
lock_explanation=_lock_explanation(fired=False, reason="Skipped.")
)
_make_window(mock_tk, snap)
texts = _texts(mock_tk)
assert any(t == "Skipped." for t in texts)
assert not any("Pending auto-upgrade" in t for t in texts)
colored = _colored(mock_tk)
assert (f"{g.UNLOCK} {g.OK}", _PALETTE.success) in colored
assert (g.RETRY, _PALETTE.warning) not in colored
def test_unknown_stage_shows_only_the_square(self, mock_tk: MagicMock) -> None:
"""A stage without a glyph shows just the square, no trailing space."""
snap = _snapshot(lock_explanation=_lock_explanation(stage="brand_new_step"))
_make_window(mock_tk, snap)
assert g.UNLOCK in _texts(mock_tk)
def test_temperature_section_renders_regardless_of_heat_skip_evaluated(
self, mock_tk: MagicMock
@ -152,28 +165,28 @@ class TestSectionLockExplanation:
lock_explanation=_lock_explanation(fired=True, heat_skip_evaluated=True)
)
_make_window(mock_tk, snap)
assert any("Warsaw Temperature" in t for t in _texts(mock_tk))
assert any(t.startswith(g.HEAT) for t in _texts(mock_tk))
class TestSectionShutdown:
"""SectionShutdown."""
def test_tonight_present_shows_live_config(self, mock_tk: MagicMock) -> None:
"""Tonight present shows live config."""
"""Tonight present shows both live times after the shutdown glyph."""
snap = _snapshot(shutdown=_shutdown(tonight=(1320, 1380, 300)))
_make_window(mock_tk, snap)
assert any("22:00" in t and "23:00" in t for t in _texts(mock_tk))
assert f"{g.SHUTDOWN} 22:00 · 23:00" in _texts(mock_tk)
def test_tonight_absent_shows_unavailable_message(self, mock_tk: MagicMock) -> None:
"""Tonight absent shows unavailable message."""
def test_tonight_absent_shows_fail_glyph(self, mock_tk: MagicMock) -> None:
"""Tonight absent shows the shutdown glyph crossed out, warning colour."""
snap = _snapshot(shutdown=_shutdown(tonight=None))
_make_window(mock_tk, snap)
assert any("Live shutdown config unavailable." in t for t in _texts(mock_tk))
assert (f"{g.SHUTDOWN} {g.FAIL}", _PALETTE.warning) in _colored(mock_tk)
def test_shows_rest_of_week_and_next_week_preview(self, mock_tk: MagicMock) -> None:
"""Shows rest of week and next week preview."""
"""Rest of week and next week are rows of times, muted, no labels."""
snap = _snapshot()
_make_window(mock_tk, snap)
texts = _texts(mock_tk)
assert any("Rest of week:" in t for t in texts)
assert any("Next week (speculative):" in t for t in texts)
row = " ".join(["21:00"] * 7)
assert _colored(mock_tk).count((row, _PALETTE.muted)) == 2
assert not any("two separate systems" in t for t in _texts(mock_tk))

View File

@ -5,6 +5,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker import _glyphs as g
from screen_locker._status_view_verify import PhoneCheckOutcome
from screen_locker._workout_credit import WorkoutCreditResult
from screen_locker.status_view import (
@ -20,6 +21,8 @@ from screen_locker.tests._status_view_helpers import (
if TYPE_CHECKING:
from pathlib import Path
import pytest
class TestPhoneCheckResultRendering:
"""PhoneCheckResultRendering."""
@ -28,17 +31,17 @@ class TestPhoneCheckResultRendering:
"""No result shows nothing."""
snap = _snapshot()
_make_window(mock_tk, snap)
assert not any("Phone check" in t for t in _texts(mock_tk))
assert not any(f"{g.RUN}{g.FAIL}" in t for t in _texts(mock_tk))
def test_verified_result_shown_in_green(self, mock_tk: MagicMock) -> None:
"""Verified result shown in green."""
window = _make_window(mock_tk, _snapshot())
window._phone_check_result = ("verified", "Workout verified!")
window._phone_check_result = ("verified", "verified glyphs")
window.render(_snapshot())
calls = [
c
for c in mock_tk.Label.call_args_list
if "Phone check" in c.kwargs.get("text", "")
if c.kwargs.get("text") == "verified glyphs"
]
assert calls
assert calls[-1].kwargs.get("fg") == window._colors.palette.success
@ -46,12 +49,11 @@ class TestPhoneCheckResultRendering:
def test_non_verified_result_shown_in_orange(self, mock_tk: MagicMock) -> None:
"""Non verified result shown in orange."""
window = _make_window(mock_tk, _snapshot())
window._phone_check_result = ("no_phone", "Phone not connected")
failed = f"{g.LIFT}{g.FAIL} {g.RUN}{g.FAIL}"
window._phone_check_result = ("no_phone", failed)
window.render(_snapshot())
calls = [
c
for c in mock_tk.Label.call_args_list
if "Phone check" in c.kwargs.get("text", "")
c for c in mock_tk.Label.call_args_list if c.kwargs.get("text") == failed
]
assert calls
assert calls[-1].kwargs.get("fg") == window._colors.palette.warning
@ -65,12 +67,7 @@ class TestButtons:
) -> None:
"""Renders check phone refresh close."""
_make_window(mock_tk, _snapshot(), log_file=temp_log_file)
assert _button_texts(mock_tk) == {
"Check Phone",
"Log Manual Workout",
"Refresh",
"Close",
}
assert _button_texts(mock_tk) == {g.PHONE, g.FORM, g.RETRY, g.CLOSE}
class TestRefreshAndCheckPhoneFlow:
@ -124,9 +121,9 @@ class TestRefreshAndCheckPhoneFlow:
mock_handle.assert_not_called()
def test_failed_check_shows_combined_message_and_rerenders(
self, mock_tk: MagicMock
self, mock_tk: MagicMock, caplog: pytest.LogCaptureFixture
) -> None:
"""Neither source verified → show both messages, apply no credit."""
"""Neither source verified → both fail glyphs, both reasons logged."""
window = _make_window(mock_tk, _snapshot())
with patch(
"screen_locker._status_view_verify.gather_status", return_value=_snapshot()
@ -136,8 +133,10 @@ class TestRefreshAndCheckPhoneFlow:
)
assert window._phone_check_result == (
"no_phone",
"StrongLifts: no lifts · RunnerUp: no run",
f"{g.LIFT}{g.FAIL} {g.RUN}{g.FAIL}",
)
warned = [r.getMessage() for r in caplog.records if r.levelname == "WARNING"]
assert any("no lifts" in m and "no run" in m for m in warned)
assert window._credit_message is None
mock_gather.assert_called_once()
@ -174,8 +173,7 @@ class TestRefreshAndCheckPhoneFlow:
assert window._phone_check_result is None
message = window._credit_message
assert message is not None
assert "StrongLifts verified: StrongLifts ok" in message
assert "Shutdown time +2h later!" in message
assert message.splitlines() == [f"{g.LIFT} {g.OK}", f"{g.SHUTDOWN} +2h"]
def test_runnerup_verified_credits_using_runnerup_message(
self, mock_tk: MagicMock, temp_log_file: Path
@ -210,7 +208,7 @@ class TestRefreshAndCheckPhoneFlow:
}
message = window._credit_message
assert message is not None
assert "RunnerUp verified: RunnerUp 5.0 km" in message
assert message == f"{g.RUN} {g.OK}"
class TestMakeBareVerifier:

View File

@ -6,6 +6,7 @@ from unittest.mock import MagicMock, patch
import pytest
from screen_locker import _glyphs as g
from screen_locker._status_view_verify import (
_backfill_week_and_apply_bonus,
)
@ -46,7 +47,7 @@ class TestBackfillWeekAndApplyBonus:
):
message = _backfill_week_and_apply_bonus(verifier)
assert message == "Auto-filled 1 workout from earlier this week."
assert message == f"{g.RETRY}{g.LIFT} +1"
verifier._scan_and_fill_week_runnerup.assert_called_once_with(
verifier.log_file, on_ingested=verifier._credit_ingested_workout
)
@ -65,9 +66,7 @@ class TestBackfillWeekAndApplyBonus:
message = _backfill_week_and_apply_bonus(verifier)
# prev 4 + 1 RunnerUp fill already credited = 5; 7 - 5 = 2 surplus.
assert message == (
"Auto-filled 2 workouts from earlier this week. +2h shutdown time."
)
assert message == f"{g.RETRY}{g.LIFT} +2 {g.SHUTDOWN} +2h"
verifier._adjust_shutdown_time_by.assert_called_once_with(120)
def test_stronglifts_fill_below_minimum_earns_no_surplus(self) -> None:
@ -82,5 +81,5 @@ class TestBackfillWeekAndApplyBonus:
):
message = _backfill_week_and_apply_bonus(verifier)
assert message == "Auto-filled 1 workout from earlier this week."
assert message == f"{g.RETRY}{g.LIFT} +1"
verifier._adjust_shutdown_time_by.assert_not_called()

View File

@ -4,6 +4,7 @@ from __future__ import annotations
from unittest.mock import MagicMock, patch
from screen_locker import _glyphs as g
from screen_locker._status_view_verify import (
PhoneCheckOutcome,
_verify_phone_then_runnerup,
@ -68,8 +69,6 @@ class TestVerifyPhoneThenRunnerup:
result = _verify_phone_then_runnerup(verifier)
assert result.credited_type is None
assert (
result.week_fill_message == "Auto-filled 1 workout from earlier this week."
)
assert result.week_fill_message == f"{g.RETRY}{g.LIFT} +1"
# The RunnerUp fill is credited by the shared callback, not here.
verifier._adjust_shutdown_time_by.assert_not_called()

View File

@ -5,6 +5,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker import _glyphs as g
from screen_locker.status_view import (
StatusWindow,
main,
@ -93,21 +94,21 @@ class TestTemperatureSectionRendering:
window = _make_window(mock_tk, _snapshot())
window._temp_result = None
window.render(_snapshot())
assert any("Checking Warsaw temperature" in t for t in _texts(mock_tk))
assert f"{g.HEAT} {g.WAIT}" in _texts(mock_tk)
def test_shows_resolved_temperature(self, mock_tk: MagicMock) -> None:
"""Shows resolved temperature."""
window = _make_window(mock_tk, _snapshot())
window._temp_result = _temp_check(temp_celsius=22.0)
window.render(_snapshot())
assert any("Warsaw: 22" in t for t in _texts(mock_tk))
assert f"{g.HEAT} 22°C < 33°C" in _texts(mock_tk)
def test_flags_would_trigger_heat_skip_when_hot(self, mock_tk: MagicMock) -> None:
"""Flags would trigger heat skip when hot."""
window = _make_window(mock_tk, _snapshot())
window._temp_result = _temp_check(temp_celsius=35.0)
window.render(_snapshot())
assert any("Would trigger heat-skip today." in t for t in _texts(mock_tk))
assert f"{g.HEAT} 35°C ≥ 33°C {g.SKIP}" in _texts(mock_tk)
def test_does_not_flag_heat_skip_when_below_threshold(
self, mock_tk: MagicMock
@ -116,21 +117,28 @@ class TestTemperatureSectionRendering:
window = _make_window(mock_tk, _snapshot())
window._temp_result = _temp_check(temp_celsius=22.0)
window.render(_snapshot())
assert not any("Would trigger heat-skip today." in t for t in _texts(mock_tk))
assert not any(g.SKIP in t for t in _texts(mock_tk) if t.startswith(g.HEAT))
def test_shows_timeout_message(self, mock_tk: MagicMock) -> None:
"""Shows timeout message."""
def test_shows_timeout_message(
self, mock_tk: MagicMock, caplog: pytest.LogCaptureFixture
) -> None:
"""A timeout shows the clock-fail glyph and logs the timeout."""
window = _make_window(mock_tk, _snapshot())
window._temp_result = _temp_check(temp_celsius=None, timed_out=True)
window.render(_snapshot())
assert any("timed out" in t for t in _texts(mock_tk))
assert f"{g.HEAT} {g.CLOCK}{g.FAIL}" in _texts(mock_tk)
assert any(
"timed out" in r.getMessage()
for r in caplog.records
if r.levelname == "WARNING"
)
def test_shows_failure_message_when_not_timed_out(self, mock_tk: MagicMock) -> None:
"""Shows failure message when not timed out."""
window = _make_window(mock_tk, _snapshot())
window._temp_result = _temp_check(temp_celsius=None, timed_out=False)
window.render(_snapshot())
assert any("failed (network/API error)" in t for t in _texts(mock_tk))
assert f"{g.HEAT} {g.FAIL}" in _texts(mock_tk)
class TestTemperatureCheckFlow:

View File

@ -0,0 +1,146 @@
"""The lock screens' glyphs (textgate): what each state paints, and what it logs.
Every sentence these screens used to paint now goes to the log at WARNING,
so each test checks both halves: the glyph on screen, the reason in the log.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker import _glyphs as g
from screen_locker import _ui_flows
from screen_locker._source_health import SourceFinding
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
import pytest
def _labels(mock_tk: MagicMock) -> list[tuple[str, str]]:
"""(text, fg) of every Label, in call order."""
return [
(c.kwargs.get("text", ""), c.kwargs.get("fg", ""))
for c in mock_tk.Label.call_args_list
]
def _warned(caplog: pytest.LogCaptureFixture) -> str:
"""Every WARNING message of the test, joined."""
return "\n".join(r.getMessage() for r in caplog.records if r.levelname == "WARNING")
class TestRetryScreen:
"""``_show_retry_and_sick``: barbell-fail, status glyph, sync faults."""
def test_too_short_paints_its_glyph_and_logs_the_reason(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A too-short session shows the short-clock glyph; its reason is logged."""
monkeypatch.setattr(_ui_flows, "collect_source_findings", list)
locker = create_locker(mock_tk, tmp_path)
locker._handle_startup_phone_result("too_short", "only 12 min")
labels = _labels(mock_tk)
palette = locker._colors.palette
assert (f"{g.LIFT} {g.FAIL}", palette.danger) in labels
assert (g.SHORT, palette.warning) in labels
assert "only 12 min" in _warned(caplog)
assert not any("only 12 min" in text for text, _fg in labels)
def test_no_status_paints_no_status_glyph(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Called without a status (the penalty timer's end), no status glyph."""
monkeypatch.setattr(_ui_flows, "collect_source_findings", list)
locker = create_locker(mock_tk, tmp_path)
locker._show_retry_and_sick("phone gone")
texts = [text for text, _fg in _labels(mock_tk)]
assert not any(text in g.STATUS_GLYPH.values() for text in texts)
assert g.FAIL not in texts
def test_each_sync_finding_is_one_glyph_and_logged(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Two unreadable sources: two sync-fail glyphs; the prose goes to the log."""
findings = [
SourceFinding("firebase", "firebase unreadable", "401"),
SourceFinding("mirror", "mirror stale", "9 days"),
]
monkeypatch.setattr(_ui_flows, "collect_source_findings", lambda: findings)
locker = create_locker(mock_tk, tmp_path)
locker._show_retry_and_sick("x", status="stale")
assert (
f"{g.SYNC}{g.FAIL} " * 2,
locker._colors.palette.warning,
) in _labels(mock_tk)
assert "firebase unreadable" in _warned(caplog)
assert "mirror stale" in _warned(caplog)
class TestAcceptedScreen:
"""``_paint_accepted``: source glyph + tick, wait dots, then unlock."""
def test_verified_lift_paints_tick_and_schedules_unlock(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
"""A verified lift paints barbell + tick in success, then the wait dots."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(locker.root, "after", MagicMock())
locker._handle_startup_phone_result("verified", "Workout A")
labels = _labels(mock_tk)
assert (f"{g.LIFT} {g.OK}", locker._colors.palette.success) in labels
assert g.WAIT in [text for text, _fg in labels]
assert not any("Workout A" in text for text, _fg in labels)
assert locker.workout_data["source"] == "Workout A"
delay, callback = locker.root.after.call_args.args
assert delay > 0
assert callback.__name__ == "unlock_screen"
def test_manual_save_paints_the_form_glyph(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
"""A saved manual entry paints form + tick, never the entry's source."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(locker.root, "after", MagicMock())
with patch.object(locker, "unlock_screen"):
locker._on_manual_workout_saved({"source": "table tennis at Solec"})
texts = [text for text, _fg in _labels(mock_tk)]
assert f"{g.FORM} {g.OK}" in texts
assert not any("Solec" in t for t in texts)
class TestGlyphHelpers:
"""The pure helpers in ``_glyphs``."""
def test_dots_fills_up_to_total_and_keeps_the_real_count(self) -> None:
"""Dots never exceed the total; the numbers stay exact."""
assert g.dots(2, 4) == "●●○○ 2/4"
assert g.dots(6, 4) == "●●●● 6/4"
assert g.dots(-1, 3) == "○○○ -1/3"
def test_status_glyph_falls_back_to_fail(self) -> None:
"""A status with no glyph shows the plain fail mark."""
assert g.status_glyph("too_short") == g.SHORT
assert g.status_glyph("brand_new_status") == g.FAIL
def test_entry_glyphs_maps_known_and_unknown_types(self) -> None:
"""Known types get their glyph; an unknown one shows a tick, in order."""
assert g.entry_glyphs(("runnerup_verified", "mystery")) == f"{g.RUN} {g.OK}"
assert not g.entry_glyphs(())

View File

@ -5,6 +5,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker import _glyphs as g
from screen_locker._compliance_predicates import is_relaxed_day_skipped_today
from screen_locker.tests.conftest import (
create_locker,
@ -69,9 +70,7 @@ class TestStartRelaxedDayFlow:
locker._start_relaxed_day_flow()
skip_cmds = [
c.kwargs["command"]
for c in mock_button.call_args_list
if "Skip" in str(c.args)
c.kwargs["command"] for c in mock_button.call_args_list if g.SKIP in c.args
]
assert locker._skip_relaxed_day in skip_cmds
@ -120,7 +119,7 @@ class TestStartRelaxedDayFlow:
log_cmds = [
c.kwargs["command"]
for c in mock_button.call_args_list
if "Log" in str(c.args)
if f"{g.GO} {g.LIFT}" in c.args
]
assert locker._start_relaxed_phone_check in log_cmds
@ -233,5 +232,5 @@ class TestHandleRelaxedPhoneResult:
button_texts = {
call.kwargs.get("text") for call in mock_tk.Button.call_args_list
}
assert "TRY AGAIN" in button_texts
assert "Close (Skip)" in button_texts
assert g.RETRY in button_texts
assert g.SKIP in button_texts

View File

@ -34,7 +34,7 @@ class TestRelaxedDayAlreadySkippedBranch:
# script_dir.parent/"log.json" resolves to tmp_path/"log.json" -- NOT
# tmp_path/"screen_locker"/"log.json".
log_file = tmp_path / "log.json"
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
write_signed_entry(log_file, today, {"type": "relaxed_day_skip"})
with (

View File

@ -0,0 +1,20 @@
"""What counts as a painted word for ``verify_text_free``.
Content is allowed (textgate-rework R4): numbers, dates, symbols, glyphs, and
a unit symbol written right after its number (``31°C``, ``5 km``,
``40 min``). Everything else with two or more letters in a row is chrome
someone wrote around the content, and the check fails on it.
"""
from __future__ import annotations
import re
# A unit symbol glued to (or one space after) the number it measures.
_UNIT_AFTER_NUMBER = re.compile(r"(?<=\d)\s?(?:kg|km|min|h|ms)\b")
_WORD = re.compile(r"[A-Za-z]{2,}")
def words_in(text: str) -> list[str]:
"""Return every chrome word in *text* (empty list when text-free)."""
return _WORD.findall(_UNIT_AFTER_NUMBER.sub("", text))

View File

@ -0,0 +1,85 @@
"""Screens ``verify_text_free`` paints beyond the fit check's list.
The fit check measures only the screens that can overflow. The text check has
to see every screen kuhy can look at: the verified/unlock screens, the
checking screens and the status window (resizable, so absent from the fit
check). Each build paints into ``surface.content`` like the fit check's.
"""
from __future__ import annotations
import threading
from typing import TYPE_CHECKING
from screen_locker._status_data import gather_status
from screen_locker._temperature import TemperatureCheck
from screen_locker._unlock_view import UnlockViewMixin
from screen_locker._workout_credit import WorkoutCreditResult
from screen_locker.status_view import StatusWindow
from scripts.verify_screen_fits import ScreenHost
if TYPE_CHECKING:
from collections.abc import Callable
from types import SimpleNamespace
class _Host(UnlockViewMixin, ScreenHost):
"""ScreenHost plus the unlock view, with every reward line switched on."""
def _apply_workout_credit(self) -> WorkoutCreditResult:
return WorkoutCreditResult(
shutdown_adjusted=True,
extra_bonus_delta=60,
weekly_count=5,
already_counted_today=False,
)
def _verify_runnerup_workout(self) -> tuple[str, str]:
"""Stand-in for the RunnerUp check: never reads a phone.
Blocks briefly so the waiting screen is what gets checked, not the
failure screen a finished future would route to straight away.
"""
threading.Event().wait(2)
return ("not_verified", "x")
def paint_manual_saved(self) -> None:
"""The real confirmation screen (ScreenHost stubs the hook out)."""
super(ScreenHost, self)._on_manual_workout_saved({"source": "x"})
def _host_paint(method: str, *args: object) -> Callable[[object], None]:
def build(surface: object) -> None:
host = _Host(surface)
host.root.after = lambda *_a, **_k: None # no unlock timer, no close
getattr(host, method)(*args)
return build
def _status_window(surface: SimpleNamespace) -> None:
"""The real status window over today's on-disk state (read-only)."""
StatusWindow(
surface.content.winfo_toplevel(),
gather_status(),
on_refresh=lambda: None,
temperature_fetcher=lambda _city: TemperatureCheck(
temp_celsius=21.0, timed_out=False
),
).root.update_idletasks()
def extra_paints() -> list[tuple[str, Callable[[object], None]]]:
"""Every screen the fit check does not paint, as (name, build)."""
return [
("unlock", _host_paint("unlock_screen")),
("verified", _host_paint("_handle_startup_phone_result", "verified", "x")),
("too-short", _host_paint("_handle_startup_phone_result", "too_short", "x")),
(
"clock-tampered",
_host_paint("_handle_startup_phone_result", "clock_tampered", "x"),
),
("runnerup-check", _host_paint("_handle_startup_phone_result", "stale", "x")),
("manual-saved", _host_paint("paint_manual_saved")),
("status-window", _status_window),
]

View File

@ -56,19 +56,21 @@ class _DemoHooks:
def build_surface(self, parent: tk.Misc, _surface: object) -> None:
"""Draw the status line and the release/reacquire buttons."""
# textgate: glyphs only, colours as the second channel. Was "DEMO
# LOCK — local grab, VT switching still enabled" / "Press “Start
# workout”. While the app holds the screen, press Ctrl+Shift+Q to
# escape." / "Start workout" / "✕ Close demo (or press Escape)".
# The escape chord stays visible: it is what the user must press.
tk.Label(
parent,
text="DEMO LOCK — local grab, VT switching still enabled",
text="▣",
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."
),
text="Ctrl+Shift+Q",
font=("TkDefaultFont", 12),
bg="#1B1D21",
fg="#9AA0A6",
@ -76,7 +78,7 @@ class _DemoHooks:
self.status.pack(pady=8)
tk.Button(
parent,
text="Start workout",
text="▶",
font=("TkDefaultFont", 14, "bold"),
bg="#3B82F6",
fg="#FFFFFF",
@ -86,7 +88,7 @@ class _DemoHooks:
).pack(pady=16)
tk.Button(
parent,
text="✕ Close demo (or press Escape)",
text="✕",
bg="#EF4444",
fg="#FFFFFF",
command=self._close,
@ -128,7 +130,7 @@ def main() -> int:
if workout_app_binary() is None:
return 1
root = tk.Tk()
root.title("Workout handoff demo")
root.title("")
# Local grab + VT switching enabled: every escape hatch stays open.
config = LockConfig(mode="hard", grab=GrabPolicy(kind="local", disable_vt=False))
hooks = _DemoHooks()

View File

@ -31,7 +31,7 @@ from typing import TYPE_CHECKING
from gatelock import LockConfig, measure_fit, report_fit
from screen_locker._constants import MANUAL_WORKOUT_REFLECTION_MIN_CHARS
from screen_locker._manual_workout_date import REJECTED_GLYPH
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
from screen_locker._surface_group import FrameGroup
from screen_locker._ui_flows import UIFlowsMixin
@ -147,12 +147,7 @@ class ScreenHost(
not fitting.
"""
self._show_manual_workout_form()
self._mw_error_label.config(
text=(
"Start time must look like HH:MM, and every reflection needs "
f"at least {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} characters."
)
)
self._mw_error_label.config(text=REJECTED_GLYPH)
def paint_sick_refused(self) -> None:
"""Paint the screen shown when today cannot be marked sick."""

140
scripts/verify_text_free.py Executable file
View File

@ -0,0 +1,140 @@
#!/usr/bin/env python3
"""Assert no locker screen paints a word (textgate: zero visible text).
kuhy's rule: anything he sees carries no text unless he asked for it. The
``textgate scan`` only sees string literals passed to known keywords, so it
misses every ``self._label("...")`` / ``self._text(f"...")`` call -- the
whole locker UI. This check paints every screen for real (Xvfb, the same
``ScreenHost`` the fit check uses), walks the widget tree, and fails on any
2+ letter word that is not content (see ``_text_free_rules``).
cd ~/src/screen-locker && python3 -m scripts.verify_text_free [--shots DIR]
``--shots DIR`` also saves one PNG per screen (ImageMagick ``import``), so
the same run is the before/after evidence.
"""
from __future__ import annotations
import logging
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tkinter as tk
from types import SimpleNamespace
from scripts._fit_extra_screens import EXTRA_SCREENS
from scripts._text_free_rules import words_in
from scripts._text_free_screens import extra_paints
from scripts._xvfb_reexec import reexec_under_xvfb
from scripts.verify_screen_fits import SCREENS, ScreenHost
_logger = logging.getLogger(__name__)
INNER_ENV = "_TEXT_FREE_CHECK_INNER"
_SIZE = (1366, 768)
# Screens whose words come from a package this repo does not own: reported,
# not failed, so the gate stays meaningful for screen-locker's own text.
EXTERNAL: dict[str, str] = {
"sick-keep-panel": "sickdays.gui.KeepPanel (kuhyx/utils, sickdays)",
}
_TYPED = frozenset({"Entry", "Spinbox", "Text", "TEntry", "TSpinbox", "TCombobox"})
def _widget_texts(widget: tk.Misc) -> list[str]:
"""Every painted string under *widget*: label/button text and menus."""
out: list[str] = []
for child in widget.winfo_children():
out += _widget_texts(child)
# What the user typed is content. (Tk abbreviates options, so an Entry's
# cget("text") would answer its textvariable's *name*.)
if widget.winfo_class() in _TYPED:
return out
# Ask only for options the widget has: no try/except, nothing swallowed.
options = set(widget.keys())
text = str(widget.cget("text")) if "text" in options else ""
var = str(widget.cget("textvariable")) if "textvariable" in options else ""
if var:
text = f"{text} {widget.getvar(var)}"
if widget.winfo_class() == "Menu":
last = widget.index("end")
for i in range(0 if last is None else int(last) + 1):
if widget.type(i) not in {"separator", "tearoff"}:
text += " " + str(widget.entrycget(i, "label"))
return [text, *out] if text.strip() else out
def _shoot(win: tk.Toplevel, path: Path) -> None:
"""Save *win* as a PNG; a failed shot is logged, never fatal."""
win.update()
tool = shutil.which("import")
if tool is None:
_logger.warning("no ImageMagick import on PATH: %s not saved", path)
return
result = subprocess.run(
[tool, "-window", str(win.winfo_id()), str(path)],
capture_output=True,
text=True,
check=False,
)
if result.returncode:
_logger.warning("screenshot %s failed: %s", path, result.stderr.strip())
def _paint_all(root: tk.Tk, shots: Path | None) -> dict[str, list[str]]:
"""Paint each screen in its own window; map screen -> offending words."""
builds = [
(s.name, lambda surface, p=s.paint: p(ScreenHost(surface))) for s in SCREENS
]
builds += list(EXTRA_SCREENS)
builds += extra_paints()
bad: dict[str, list[str]] = {}
for name, build in builds:
win = tk.Toplevel(root)
win.geometry(f"{_SIZE[0]}x{_SIZE[1]}")
frame = tk.Frame(win, bg="#211D1B")
frame.pack(fill="both", expand=True)
build(SimpleNamespace(content=frame))
win.update_idletasks()
words = [w for t in _widget_texts(win) for w in words_in(t)]
if words:
bad[name] = words
if shots is not None:
_shoot(win, shots / f"{name}.png")
win.destroy()
return bad
def main(argv: list[str] | None = None) -> int:
"""Paint every screen; exit 1 listing each one that still shows words."""
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
args = sys.argv[1:] if argv is None else argv
if os.environ.get(INNER_ENV) != "1":
os.environ["_TEXT_FREE_ARGS"] = "\x1f".join(args)
return reexec_under_xvfb(inner_env=INNER_ENV, module="scripts.verify_text_free")
args = [a for a in os.environ.get("_TEXT_FREE_ARGS", "").split("\x1f") if a]
shots = Path(args[args.index("--shots") + 1]) if "--shots" in args else None
if shots is not None:
shots.mkdir(parents=True, exist_ok=True)
root = tk.Tk()
root.withdraw()
bad = _paint_all(root, shots)
root.destroy()
for name, owner in EXTERNAL.items():
if name in bad:
_logger.warning(
"external %s (%s): %s", name, owner, " ".join(bad.pop(name))
)
if not bad:
_logger.info("OK: no locker screen paints a word.")
return 0
for name, words in bad.items():
_logger.error("%s: %s", name, " ".join(words))
_logger.error("%d screen(s) still paint words.", len(bad))
return 1
if __name__ == "__main__":
sys.exit(main())

View File

@ -192,7 +192,8 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Workout Tracker',
// textgate: no title. Was 'Workout Tracker'; the recents card shows
// the launcher icon and the manifest label (android:label) already.
debugShowCheckedModeBanner: false,
theme: buildAppTheme(),
home: const HomeScreen(),
@ -200,7 +201,8 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
// ribbon on every screen, in the error colour, on the sandbox only.
builder: (context, child) => Sandbox.enabled
? Banner(
message: 'SANDBOX',
// Was 'SANDBOX': the red corner ribbon alone marks it.
message: '',
location: BannerLocation.topEnd,
color: Theme.of(context).colorScheme.error,
child: child,

View File

@ -200,23 +200,10 @@ DateTime? parsePauseDate(Object? raw) {
return parsed;
}
const _months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
/// `11 Oct`: how a pause's end date is shown.
String formatShortDate(DateTime d) => '${d.day} ${_months[d.month - 1]}';
/// `11.10`: how a pause's end date is shown (textgate: numerals, no month
/// word; was `11 Oct`).
String formatShortDate(DateTime d) =>
'${d.day}.${d.month.toString().padLeft(2, '0')}';
/// `3:00`: how a rest length is shown.
String formatRest(int secs) =>

View File

@ -125,15 +125,19 @@ ProgressionTarget targetAfterFailure(ProgressionInputs s) {
}
}
/// Short label for moving from [from] to [to]: `25 kg`, `13 reps`,
/// `25 kg × 6`, or `same` when the rule has nowhere left to go.
/// What [describeTargetChange] returns when the rule has nowhere to go.
const kNoTargetChange = '=';
/// Short label for moving from [from] to [to]: `25 kg`, `×13` (reps),
/// `25 kg × 6`, or [kNoTargetChange]. textgate: numerals and symbols only
/// (was `13 reps` / `same`).
String describeTargetChange(ProgressionInputs from, ProgressionTarget to) {
final weightChanged = to.weight != from.weight;
final repsChanged = to.reps != from.reps;
if (weightChanged && repsChanged) return '${_kg(to.weight)} kg × ${to.reps}';
if (weightChanged) return '${_kg(to.weight)} kg';
if (repsChanged) return '${to.reps} reps';
return 'same';
if (repsChanged) return '×${to.reps}';
return kNoTargetChange;
}
/// `25` for 25.0, `27.5` for 27.5 — no trailing `.0` noise in tight rows.

View File

@ -198,9 +198,11 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
return Scaffold(
appBar: AppBar(
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text(
'Advanced sync (GitHub)',
style: TextStyle(color: colorScheme.onSurface),
// textgate: was "Advanced sync (GitHub)".
title: Icon(
Icons.code,
color: colorScheme.onSurface,
semanticLabel: 'Advanced sync (GitHub)',
),
iconTheme: IconThemeData(color: colorScheme.onSurface),
),
@ -209,25 +211,20 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
: ListView(
padding: const EdgeInsets.all(16),
children: [
Text(
'Authorize in your browser -- no token to paste. '
'Syncs to $syncRepoOwner/$syncRepoName.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
const SizedBox(height: 12),
// textgate: the explanation sentence above is gone.
if (_syncStatus != null) ...[
_SyncStatusBadge(text: _syncStatus!, kind: _syncStatusKind),
const SizedBox(height: 12),
],
Align(
alignment: Alignment.centerLeft,
child: ElevatedButton.icon(
child: ElevatedButton(
onPressed: _connectGitHub,
icon: const Icon(Icons.login),
label: const Text('Connect GitHub'),
child: const Icon(
Icons.login,
size: 20,
semanticLabel: 'Connect GitHub',
),
),
),
const SizedBox(height: 12),

View File

@ -19,6 +19,12 @@ class _SyncStatusBadge extends StatelessWidget {
_SyncStatusKind.error => colorScheme.error,
_SyncStatusKind.pending => colorScheme.onSurfaceVariant,
};
// textgate: the status sentence is spoken only; the pill shows the
// state glyph in the state colour.
return Semantics(label: text, excludeSemantics: true, child: _pill(color));
}
Widget _pill(Color color) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
@ -42,17 +48,6 @@ class _SyncStatusBadge extends StatelessWidget {
color: color,
size: 16,
),
const SizedBox(width: 10),
Expanded(
child: Text(
text,
style: TextStyle(
color: color,
fontSize: AppTextSize.label,
fontWeight: FontWeight.w600,
),
),
),
],
),
);
@ -80,17 +75,23 @@ class _SyncTokenField extends StatelessWidget {
// inputDecorationTheme (theme.dart) — only the field-specific
// hint/padding need setting here.
decoration: InputDecoration(
hintText: 'GitHub PAT',
hintStyle: TextStyle(color: colorScheme.onSurfaceVariant),
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 10,
),
prefixIcon: const Icon(
Icons.vpn_key,
semanticLabel: 'GitHub PAT',
),
),
),
),
const SizedBox(width: 8),
ElevatedButton(onPressed: onSave, child: const Text('Save')),
ElevatedButton(
onPressed: onSave,
child: const Icon(Icons.save, semanticLabel: 'Save'),
),
],
);
}
@ -140,19 +141,17 @@ class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
final colorScheme = Theme.of(context).colorScheme;
return AlertDialog(
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text(
'Authorize on GitHub',
style: TextStyle(color: colorScheme.onSurface),
// Was "Authorize on GitHub" / "Enter this code on GitHub:" /
// "Waiting for authorization…": key glyph, the code, a spinner.
title: Icon(
Icons.vpn_key,
color: colorScheme.onSurface,
semanticLabel: 'Authorize on GitHub',
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Enter this code on GitHub:',
style: TextStyle(color: colorScheme.onSurfaceVariant),
),
const SizedBox(height: 8),
SelectableText(
widget.device.userCode,
style: TextStyle(
@ -163,38 +162,39 @@ class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
),
const SizedBox(height: 16),
if (_error == null)
Row(
children: [
const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 12),
Expanded(
child: Text(
'Waiting for authorization…',
style: TextStyle(color: colorScheme.onSurfaceVariant),
),
),
],
const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
semanticsLabel: 'Waiting for authorization…',
),
)
else
Text(_error!, style: TextStyle(color: colorScheme.error)),
// textgate: the failure is spoken only.
Icon(
Icons.error_outline,
color: colorScheme.error,
semanticLabel: _error,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(
'Cancel',
style: TextStyle(color: colorScheme.onSurfaceVariant),
child: Icon(
Icons.close,
color: colorScheme.onSurfaceVariant,
semanticLabel: 'Cancel',
),
),
FilledButton.icon(
// Was "Open GitHub & copy code".
FilledButton(
onPressed: _openPage,
icon: const Icon(Icons.open_in_new),
label: const Text('Open GitHub & copy code'),
child: const Icon(
Icons.open_in_new,
semanticLabel: 'Open GitHub & copy code',
),
),
],
);

View File

@ -6,6 +6,7 @@ library;
import 'dart:async';
import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:math';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter/material.dart';
@ -161,7 +162,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
return Scaffold(
appBar: AppBar(
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text('Progress', style: TextStyle(color: colorScheme.onSurface)),
title: const Icon(Icons.timeline, size: 20, semanticLabel: 'Progress'),
iconTheme: IconThemeData(color: colorScheme.onSurface),
),
body: _loading
@ -172,12 +173,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
_syncedRows.isEmpty &&
_plannedRows.isEmpty &&
_runs.isEmpty
? Center(
child: Text(
'No workouts yet.',
style: TextStyle(color: colorScheme.onSurfaceVariant),
),
)
? const _EmptyHistory()
: ListView(
padding: const EdgeInsets.all(12),
children: [
@ -209,18 +205,21 @@ class _HistoryScreenState extends State<HistoryScreen> {
_RunsStrip(runs: _runs, onOpen: _openRun),
const SizedBox(height: 16),
],
const _SectionLabel('TOTAL VOLUME (2-session rolling avg, kg)'),
const _SectionLabel(
Icons.stacked_line_chart,
'TOTAL VOLUME (2-session rolling avg, kg)',
),
const SizedBox(height: 6),
_WeightChart(points: _rollingAvg2(_totalVolumePoints(_rows))),
const SizedBox(height: 16),
_calendar(_allWorkoutDates(_rows, _syncedRows, _runs)),
const SizedBox(height: 16),
const _SectionLabel('ALL SESSIONS'),
const _SectionLabel(Icons.list, 'ALL SESSIONS'),
const SizedBox(height: 8),
..._rows.map((row) => _AllSessionTile(row: row)),
if (_syncedRows.isNotEmpty) ...[
const SizedBox(height: 16),
const _SectionLabel('SYNCED FROM PC'),
const _SectionLabel(Icons.computer, 'SYNCED FROM PC'),
const SizedBox(height: 8),
..._syncedRows.map((row) => _SyncedWorkoutTile(payload: row)),
],
@ -231,13 +230,14 @@ class _HistoryScreenState extends State<HistoryScreen> {
_ProgressStatsCard(state: _selectedState!),
const SizedBox(height: 12),
],
const _SectionLabel('WEIGHT OVER TIME'),
const _SectionLabel(Icons.show_chart, 'WEIGHT OVER TIME'),
const SizedBox(height: 6),
_WeightChart(points: _exerciseWeightPoints(_rows, name)),
const SizedBox(height: 16),
_calendar(_exerciseDates(_rows, name)),
const SizedBox(height: 16),
_SectionLabel(name.toUpperCase()),
// The picker above already names the exercise: a list glyph here.
_SectionLabel(Icons.list, name),
const SizedBox(height: 8),
..._sessionsForExercise(
_rows,

View File

@ -7,24 +7,44 @@ part of 'history_screen.dart';
// ── Shared sub-widgets ──────────────────────────────────────────────────────
/// A section heading as a glyph (textgate: was an all-caps word heading;
/// the words survive as [spoken], the glyph's semantic label).
class _SectionLabel extends StatelessWidget {
const _SectionLabel(this.text);
const _SectionLabel(this.icon, this.spoken);
final String text;
final IconData icon;
final String spoken;
@override
Widget build(BuildContext context) {
return Text(
text,
style: TextStyle(
return Align(
alignment: Alignment.centerLeft,
child: Icon(
icon,
size: 18,
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
letterSpacing: 1.3,
semanticLabel: spoken,
),
);
}
}
/// The empty history: a large muted history glyph (textgate: was "No
/// workouts yet.").
class _EmptyHistory extends StatelessWidget {
const _EmptyHistory();
@override
Widget build(BuildContext context) => Center(
child: Icon(
Icons.history,
size: 48,
color: Theme.of(context).colorScheme.outlineVariant,
semanticLabel: 'No workouts yet.',
),
);
}
class _ExercisePicker extends StatelessWidget {
const _ExercisePicker({
required this.names,
@ -49,15 +69,18 @@ class _ExercisePicker extends StatelessWidget {
.map(
(n) => DropdownMenuItem(
value: n,
child: Text(
n,
style: TextStyle(
color: n == _kTotal
? colorScheme.onSurfaceVariant
: colorScheme.onSurface,
fontStyle: n == _kTotal ? FontStyle.italic : FontStyle.normal,
),
),
// textgate: the all-workouts entry is a sum glyph (was
// "Total (all workouts)"); exercise names are content.
child: n == _kTotal
? Align(
alignment: Alignment.centerLeft,
child: Icon(
Icons.functions,
color: colorScheme.onSurfaceVariant,
semanticLabel: _kTotal,
),
)
: Text(n, style: TextStyle(color: colorScheme.onSurface)),
),
)
.toList(),
@ -162,7 +185,8 @@ class _StreakRow extends StatelessWidget {
const SizedBox(width: 8),
Expanded(
child: Text(
'${threshold - shown} more to $direction $actionLabel',
// textgate: was "2 more to ↑ 25 kg".
'${threshold - shown} $direction $actionLabel',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
@ -187,9 +211,11 @@ class _WeightChart extends StatelessWidget {
return Container(
height: 80,
alignment: Alignment.center,
child: Text(
'Not enough data for chart',
style: TextStyle(color: colorScheme.onSurfaceVariant),
// textgate: was "Not enough data for chart".
child: Icon(
Icons.show_chart,
color: colorScheme.outlineVariant,
semanticLabel: 'Not enough data for chart',
),
);
}

View File

@ -5,7 +5,6 @@
// these are `part` files.
part of 'history_screen.dart';
class _ChartPainter extends CustomPainter {
_ChartPainter(
this.points, {
@ -25,22 +24,8 @@ class _ChartPainter extends CustomPainter {
static const _bottomPad = 22.0; // room for X-axis dates
static const _hPad = 8.0;
static const _months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
static String _shortDate(DateTime d) => '${_months[d.month - 1]} ${d.day}';
// textgate: numeric day.month on the axis (was "Aug 15").
static String _shortDate(DateTime d) => formatShortDate(d);
@override
void paint(Canvas canvas, Size size) {

View File

@ -17,7 +17,7 @@ extension _HistoryPlanned on _HistoryScreenState {
/// when there are none.
List<Widget> _plannedSection() => [
if (_plannedRows.isNotEmpty) ...[
const _SectionLabel('PLANNED (not done yet)'),
const _SectionLabel(Icons.event, 'PLANNED (not done yet)'),
const SizedBox(height: 8),
..._plannedRows.map(
(row) => _PlannedWorkoutTile(
@ -40,19 +40,33 @@ extension _HistoryPlanned on _HistoryScreenState {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Delete planned workout?'),
// Was "Delete planned workout?" / "<source> on <date> at <time>.
// It will not be credited." -- now the bin glyph plus the entry's
// own data (source, date, time).
title: Icon(
Icons.delete_outline,
color: Theme.of(context).colorScheme.error,
semanticLabel: 'Delete planned workout?',
),
content: Text(
'${payload['source'] ?? 'Manual workout'} on $date at '
'${payload['start_time']}. It will not be credited.',
[
'${payload['source'] ?? ''}',
date,
'${payload['start_time']}',
].where((part) => part.isNotEmpty).join(' · '),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('KEEP'),
child: const Icon(Icons.close, semanticLabel: 'KEEP'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('DELETE'),
child: Icon(
Icons.delete_outline,
color: Theme.of(context).colorScheme.error,
semanticLabel: 'DELETE',
),
),
],
),
@ -62,11 +76,16 @@ extension _HistoryPlanned on _HistoryScreenState {
// loaded, and a delete confirmed after midnight would cancel a workout
// that is now today's -- one the PC may already have credited.
if (!_isPlanned(payload, dayKey((widget.clock ?? DateTime.now)()))) {
// Was "Not deleted — <date> has started, so it is no longer a
// planned workout.": a blocked glyph next to the date.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Not deleted — $date has started, so it is no longer '
'a planned workout.',
content: Row(
children: [
const Icon(Icons.block, semanticLabel: 'Not deleted'),
const SizedBox(width: 8),
Text(date),
],
),
),
);
@ -81,9 +100,20 @@ extension _HistoryPlanned on _HistoryScreenState {
});
if (!mounted) return;
if (!result.pushed) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Not deleted — ${result.reason}')));
// Was "Not deleted — <reason>"; the reason goes to the log instead.
developer.log(
'History: planned $id not deleted: ${result.reason}',
level: 900,
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Icon(
Icons.cloud_off,
color: Theme.of(context).colorScheme.error,
semanticLabel: 'Not deleted',
),
),
);
return;
}
await _load();
@ -123,7 +153,9 @@ class _PlannedWorkoutTile extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${payload['date']} $time · Planned',
// textgate: was "<date> <time> · Planned"; the event
// glyph and the section glyph already say planned.
'${payload['date']} $time',
style: TextStyle(
color: colorScheme.onSurface,
fontWeight: FontWeight.bold,
@ -141,8 +173,11 @@ class _PlannedWorkoutTile extends StatelessWidget {
),
),
IconButton(
tooltip: 'Delete planned workout',
icon: Icon(Icons.delete_outline, color: colorScheme.error),
icon: Icon(
Icons.delete_outline,
color: colorScheme.error,
semanticLabel: 'Delete planned workout',
),
onPressed: onDelete,
),
],

View File

@ -13,10 +13,12 @@ class _SyncedWorkoutTile extends StatelessWidget {
final colorScheme = Theme.of(context).colorScheme;
final kind = '${payload['kind']}';
final isRun = kind == 'runnerup_verified';
final label = isRun ? 'Run' : 'Manual';
final semanticLabel = isRun ? 'Run' : 'Manual';
final detail = '${payload['source'] ?? ''}';
return Container(
// Tests find a tile by date and kind; nothing paints the kind word.
key: ValueKey('synced-${payload['date']}-$semanticLabel'),
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
decoration: BoxDecoration(
@ -32,14 +34,16 @@ class _SyncedWorkoutTile extends StatelessWidget {
isRun ? Icons.directions_run : Icons.edit_note,
color: colorScheme.onSurfaceVariant,
size: 20,
semanticLabel: semanticLabel,
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// textgate: was "<date> · Run|Manual"; the glyph says which.
Text(
'${payload['date']} · $label',
'${payload['date']}',
style: TextStyle(
color: colorScheme.onSurface,
fontWeight: FontWeight.bold,
@ -104,8 +108,9 @@ class _AllSessionTile extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// textgate: was "Workout A · <date>".
Text(
'Workout $type · $date',
'$type · $date',
style: TextStyle(
color: colorScheme.onSurface,
fontWeight: FontWeight.bold,
@ -191,17 +196,29 @@ class _ExerciseSessionTile extends StatelessWidget {
),
),
const SizedBox(height: 2),
Text(
'${weight ?? '?'}kg · $doneSets/$targetSets sets'
' · ${warmupDone ? '⬤ warmup' : '○ no warmup'}',
style: mutedStyle,
// textgate: was "20kg · 3/3 sets · ⬤ warmup" / "reps: 5, 5"
// / "workout: 30m 00s". Now numbers behind glyphs; the warmup
// is a filled or hollow sun.
Row(
children: [
Text(
'${weight ?? '?'}kg · $doneSets/$targetSets ',
style: mutedStyle,
),
Icon(
warmupDone ? Icons.wb_sunny : Icons.wb_sunny_outlined,
size: 14,
color: mutedStyle.color,
semanticLabel: warmupDone ? 'warmup' : 'no warmup',
),
],
),
if (repsSummary.isNotEmpty) ...[
const SizedBox(height: 2),
Text('reps: $repsSummary', style: mutedStyle),
_GlyphLine(Icons.repeat, repsSummary, mutedStyle),
],
const SizedBox(height: 2),
Text('workout: $dur', style: mutedStyle),
_GlyphLine(Icons.timer, dur, mutedStyle),
],
),
),
@ -210,3 +227,22 @@ class _ExerciseSessionTile extends StatelessWidget {
);
}
}
/// A small glyph followed by a number line (textgate: replaces a word
/// prefix such as "reps:" or "workout:").
class _GlyphLine extends StatelessWidget {
const _GlyphLine(this.icon, this.text, this.style);
final IconData icon;
final String text;
final TextStyle style;
@override
Widget build(BuildContext context) => Row(
children: [
Icon(icon, size: 14, color: style.color),
const SizedBox(width: 4),
Text(text, style: style),
],
);
}

View File

@ -149,10 +149,7 @@ class _HomeScreenState extends State<HomeScreen> {
return Scaffold(
appBar: AppBar(
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text(
'Workout Tracker',
style: TextStyle(color: colorScheme.onSurface),
),
// textgate: no title (was "Workout Tracker"); the app is the app.
actions: [
IconButton(
key: const Key('home_run'),
@ -164,8 +161,11 @@ class _HomeScreenState extends State<HomeScreen> {
onPressed: _openRun,
),
IconButton(
icon: Icon(Icons.edit_note, color: colorScheme.onSurface),
tooltip: 'Log manual workout',
icon: Icon(
Icons.edit_note,
color: colorScheme.onSurface,
semanticLabel: 'Log manual workout',
),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => const ManualWorkoutScreen(),
@ -173,15 +173,21 @@ class _HomeScreenState extends State<HomeScreen> {
),
),
IconButton(
tooltip: 'History',
icon: Icon(Icons.history, color: colorScheme.onSurface),
icon: Icon(
Icons.history,
color: colorScheme.onSurface,
semanticLabel: 'History',
),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const HistoryScreen()),
),
),
IconButton(
tooltip: 'Settings',
icon: Icon(Icons.settings, color: colorScheme.onSurface),
icon: Icon(
Icons.settings,
color: colorScheme.onSurface,
semanticLabel: 'Settings',
),
onPressed: () async {
await Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()),

View File

@ -35,44 +35,45 @@ class _WorkoutCard extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (doneToday && !hasActiveSession) ...[
Row(
children: [
Icon(Icons.check_circle, color: status.success, size: 18),
const SizedBox(width: 8),
Text(
'Done for today!',
style: TextStyle(
color: status.success,
fontWeight: FontWeight.bold,
fontSize: AppTextSize.body,
),
// textgate: was "Done for today!" / "Next: Workout A" /
// "Workout A in progress". Now the plan letter plus a state
// glyph; colour is the second channel (success / warning).
Row(
children: [
if (doneToday && !hasActiveSession)
Icon(
Icons.check_circle,
key: const Key('home_done_today'),
color: status.success,
semanticLabel: 'Done for today',
)
else if (hasActiveSession)
Icon(
Icons.timelapse,
key: const Key('home_in_progress'),
color: status.warning,
semanticLabel: 'Workout $type in progress',
)
else
Icon(
Icons.arrow_forward,
key: const Key('home_next'),
color: colorScheme.onSurface,
semanticLabel: 'Next: Workout $type',
),
const SizedBox(width: 8),
Text(
type,
style: TextStyle(
color: hasActiveSession
? status.warning
: colorScheme.onSurface,
fontSize: AppTextSize.subtitle,
fontWeight: FontWeight.bold,
),
],
),
const SizedBox(height: 6),
Text(
'Next: Workout $type',
style: TextStyle(
color: colorScheme.onSurface,
fontSize: AppTextSize.body,
fontWeight: FontWeight.bold,
),
),
] else ...[
Text(
hasActiveSession
? 'Workout $type in progress'
: 'Next: Workout $type',
style: TextStyle(
color: hasActiveSession
? status.warning
: colorScheme.onSurface,
fontSize: AppTextSize.subtitle,
fontWeight: FontWeight.bold,
),
),
],
],
),
const SizedBox(height: 10),
...exercises.map(
(e) => Text(
@ -93,13 +94,10 @@ class _WorkoutCard extends StatelessWidget {
padding: buttonPadding,
),
onPressed: onResume,
child: Text(
'Resume Workout',
style: TextStyle(
color: colorScheme.onPrimary,
fontSize: AppTextSize.body,
fontWeight: FontWeight.bold,
),
child: Icon(
Icons.play_arrow,
color: colorScheme.onPrimary,
semanticLabel: 'Resume Workout',
),
),
)
@ -114,13 +112,10 @@ class _WorkoutCard extends StatelessWidget {
padding: buttonPadding,
),
onPressed: onStart,
child: Text(
'Start Workout $type',
style: TextStyle(
color: colorScheme.onPrimary,
fontSize: AppTextSize.body,
fontWeight: FontWeight.bold,
),
child: Icon(
Icons.play_arrow,
color: colorScheme.onPrimary,
semanticLabel: 'Start Workout $type',
),
),
),

View File

@ -10,26 +10,37 @@ part of 'manual_workout_screen.dart';
extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
/// The budget as seen from the selected date: the fullest 7- and 30-day
/// windows around it, planned entries included.
Widget _budgetBanner(ManualBudget budget) => Text(
'Manual around ${dayKey(_date)}: '
'${budget.week}/$kManualWorkoutBudgetPer7Days per 7 days · '
'${budget.month}/$kManualWorkoutBudgetPer30Days per 30 days',
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontSize: AppTextSize.body,
),
///
/// textgate: was "Manual around DATE: 0/2 per 7 days · 0/10 per 30
/// days"; now the counts with their window length in days.
Widget _budgetBanner(ManualBudget budget) => Row(
key: const Key('mw_budget'),
children: [
Icon(
Icons.event_repeat,
size: 18,
color: Theme.of(context).colorScheme.primary,
semanticLabel: 'Manual-workout budget',
),
const SizedBox(width: AppSpacing.sm),
Text(
'${budget.week}/$kManualWorkoutBudgetPer7Days ⋅ 7d '
'${budget.month}/$kManualWorkoutBudgetPer30Days ⋅ 30d',
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontSize: AppTextSize.body,
),
),
],
);
/// "today", "tomorrow" or "in N days" for the selected date.
/// `+0` for today, `+1` for tomorrow, `+N` (textgate: was "today" /
/// "tomorrow" / "in N days").
String _relativeDay() {
// Rounded, not truncated: across a DST change two local midnights are
// 23 or 25 hours apart.
final days = (_date.difference(_today()).inHours / 24).round();
return switch (days) {
0 => 'today',
1 => 'tomorrow',
_ => 'in $days days',
};
return '+$days';
}
/// The workout date and the button that changes it.
@ -39,7 +50,8 @@ extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
children: [
Expanded(
child: Text(
'Workout date: ${dayKey(_date)} (${_relativeDay()})',
// textgate: was "Workout date: DATE (today)".
'${dayKey(_date)} ${_relativeDay()}',
key: const Key('mw_date'),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
@ -50,25 +62,32 @@ extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
TextButton(
key: const Key('mw_pick_date'),
onPressed: _submitting ? null : _pickDate,
child: const Text('CHANGE DATE'),
child: const Icon(
Icons.calendar_today,
size: 20,
semanticLabel: 'CHANGE DATE',
),
),
],
),
);
Widget _section(String title) => Padding(
padding: const EdgeInsets.only(top: 16, bottom: 4),
child: Text(
title,
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontSize: AppTextSize.subtitle,
fontWeight: FontWeight.bold,
),
),
/// A divider between field groups (textgate: was a word heading such as
/// "Basics" or "Reflection").
Widget _section() => Padding(
padding: const EdgeInsets.only(top: 12, bottom: 4),
child: Divider(color: Theme.of(context).colorScheme.primary),
);
Widget _text(String key, String label, {int lines = 1}) => Padding(
/// A field marked by [icon]; [semanticsLabel] (the old floating label) is
/// spoken only. [hint] is a numeral-only placeholder.
Widget _text(
String key,
IconData icon,
String semanticsLabel, {
int lines = 1,
String? hint,
}) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: TextField(
key: Key('mw_$key'),
@ -78,14 +97,68 @@ extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
// filled/fillColor/border inherit from the shared inputDecorationTheme
// (theme.dart) — only the field-specific label needs setting here.
decoration: InputDecoration(
labelText: label,
labelStyle: TextStyle(
hintText: hint,
prefixIcon: Icon(
icon,
color: Theme.of(context).colorScheme.onSurfaceVariant,
semanticLabel: semanticsLabel,
),
),
),
);
List<Widget> _basicFields() => [
_text(
'start_time',
Icons.play_circle_outline,
'Start time (HH:MM)',
hint: '--:--',
),
_text(
'end_time',
Icons.stop_circle_outlined,
'End time (HH:MM)',
hint: '--:--',
),
];
List<Widget> _logisticsFields() => [
_text('location_name', Icons.place, 'Location name'),
_text('transport_method', Icons.directions_bus, 'How did you get there?'),
_text('cost', Icons.payments, 'Cost (e.g. 40 PLN)'),
_text('reservation_phone', Icons.phone, 'Reservation phone (optional)'),
];
List<Widget> _detailFields() => [
_text('techniques_practiced', Icons.psychology, 'Techniques (optional)'),
_text('warm_up_minutes', Icons.wb_sunny, 'Warm-up (optional)'),
_text('pain_or_injury', Icons.healing, 'Pain or injury (optional)'),
];
List<Widget> _reflectionFields() => [
_text('went_well', Icons.thumb_up, 'What went well', lines: 3),
_text('to_improve', Icons.trending_up, 'What to improve', lines: 3),
_text('overall_feeling', Icons.mood, 'Overall feeling', lines: 3),
];
List<Widget> _sportFields() {
if (_sport == kSportTableTennis) {
return [
_text('matches_won', Icons.emoji_events, 'Matches won'),
_text('matches_lost', Icons.emoji_events_outlined, 'Matches lost'),
_text('sets_won', Icons.add_circle_outline, 'Sets won'),
_text('sets_lost', Icons.remove_circle_outline, 'Sets lost'),
_text('racket', Icons.sports_tennis, 'Racket used'),
_text('balls', Icons.sports_baseball, 'Balls used'),
];
}
return [
_text('activity_type_other', Icons.sports, 'What sport/activity'),
_text('activity_details', Icons.notes, 'What was done', lines: 3),
_text('equipment', Icons.backpack, 'Equipment (optional)'),
];
}
/// Reads [key]'s field as an int, treating blank or unparsable as 0.
int _int(String key) => int.tryParse(_fields[key]!.text.trim()) ?? 0;

View File

@ -124,9 +124,11 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
return Scaffold(
appBar: AppBar(
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text(
'Log Manual Workout',
style: TextStyle(color: colorScheme.onSurface),
// textgate: was "Log Manual Workout".
title: Icon(
Icons.edit_note,
color: colorScheme.onSurface,
semanticLabel: 'Log Manual Workout',
),
),
body: !_budgetLoaded
@ -139,47 +141,49 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
_dateRow(),
_budgetBanner(budget),
if (exhausted)
// textgate: was "Manual-workout budget exhausted for a
// window containing <date> — pick another date."
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'Manual-workout budget exhausted for a window '
'containing ${dayKey(_date)} — pick another date.',
style: TextStyle(color: colorScheme.error),
child: Icon(
Icons.block,
key: const Key('mw_exhausted'),
size: 40,
color: colorScheme.error,
semanticLabel:
'Manual-workout budget exhausted — '
'pick another date.',
),
)
else ...[
_section('Basics'),
_section(),
_sportDropdown(),
_text('start_time', 'Start time (HH:MM)'),
_text('end_time', 'End time (HH:MM)'),
_section('Location & logistics'),
_text('location_name', 'Location name'),
_text('transport_method', 'How did you get there?'),
_text('cost', 'Cost (e.g. 40 PLN)'),
_text('reservation_phone', 'Reservation phone (optional)'),
_section('Activity details'),
..._basicFields(),
_section(),
..._logisticsFields(),
_section(),
..._sportFields(),
_rpeSlider(),
_text('techniques_practiced', 'Techniques (optional)'),
_text('warm_up_minutes', 'Warm-up (optional)'),
_text('pain_or_injury', 'Pain or injury (optional)'),
_section('Reflection'),
_text('went_well', 'What went well', lines: 3),
_text('to_improve', 'What to improve', lines: 3),
_text('overall_feeling', 'Overall feeling', lines: 3),
..._detailFields(),
_section(),
..._reflectionFields(),
if (_error != null)
// textgate: the refusal reason is spoken only; painted
// as an error glyph.
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(
_error!,
style: TextStyle(color: colorScheme.error),
child: Icon(
Icons.error_outline,
key: const Key('mw_error'),
color: colorScheme.error,
semanticLabel: _error,
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: ElevatedButton(
onPressed: _submitting ? null : _submit,
child: const Text('SUBMIT'),
child: const Icon(Icons.save, semanticLabel: 'SUBMIT'),
),
),
],
@ -188,24 +192,6 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
);
}
List<Widget> _sportFields() {
if (_sport == kSportTableTennis) {
return [
_text('matches_won', 'Matches won'),
_text('matches_lost', 'Matches lost'),
_text('sets_won', 'Sets won'),
_text('sets_lost', 'Sets lost'),
_text('racket', 'Racket used'),
_text('balls', 'Balls used'),
];
}
return [
_text('activity_type_other', 'What sport/activity'),
_text('activity_details', 'What was done', lines: 3),
_text('equipment', 'Equipment (optional)'),
];
}
Widget _sportDropdown() => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: DropdownButton<String>(
@ -214,8 +200,17 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
isExpanded: true,
items: [
// textgate: sport glyphs; the names are spoken only.
for (final entry in kSportLabels.entries)
DropdownMenuItem(value: entry.key, child: Text(entry.value)),
DropdownMenuItem(
value: entry.key,
child: Icon(
entry.key == kSportTableTennis
? Icons.sports_tennis
: Icons.sports,
semanticLabel: entry.value,
),
),
],
onChanged: (value) {
if (value != null) setState(() => _sport = value);
@ -227,8 +222,16 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
// textgate: was "RPE 5"; an effort glyph and the number.
Icon(
Icons.speed,
color: Theme.of(context).colorScheme.onSurface,
semanticLabel: 'RPE',
),
const SizedBox(width: 4),
Text(
'RPE ${_rpe.round()}',
'${_rpe.round()}',
key: const Key('mw_rpe'),
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
),
Expanded(

View File

@ -7,6 +7,7 @@
library;
import 'dart:async';
import 'dart:developer';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
@ -53,7 +54,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _soundEnabled = true;
// Set after a Sync settings visit restores progression; the banner stays.
String? _progressionStatus;
/// Exercises the last sync-settings visit restored; null until one did.
int? _restoredCount;
@override
void initState() {
@ -125,10 +127,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
ProgressionSyncService().pullProgression)();
if (!mounted) return;
if (restored.changed) {
setState(
() => _progressionStatus =
'Restored ${restored.count} exercise(s) from Firebase.',
);
setState(() => _restoredCount = restored.count);
await _load();
}
}
@ -178,11 +177,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
await (widget.progressionPusher ??
ProgressionSyncService().pushProgression)();
if (!mounted || pushed.changed) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Saved on this phone, not synced: ${pushed.reason}'),
),
);
_flagUnsynced(pushed.reason);
}
/// Shows a deloaded target everywhere this screen holds a copy of it.
@ -228,7 +223,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_SoundSection(enabled: _soundEnabled, onChanged: _setSound),
const SizedBox(height: 20),
_SyncSection(
progressionStatus: _progressionStatus,
restoredCount: _restoredCount,
onOpenSyncSettings: () => unawaited(_openSyncSettings()),
onOpenGitHubMirror: () => unawaited(_openGitHubMirror()),
),

View File

@ -23,26 +23,29 @@ extension _SettingsScreenActions on _SettingsScreenState {
context: context,
builder: (_) => AlertDialog(
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text(
'Reset to defaults?',
style: TextStyle(color: colorScheme.onSurface),
),
content: Text(
'All weights and thresholds will be reset. '
'Streak counters will be cleared.',
style: TextStyle(color: colorScheme.onSurfaceVariant),
// Was "Reset to defaults?" / "All weights and thresholds will be
// reset. Streak counters will be cleared.".
title: Icon(
Icons.restart_alt,
color: colorScheme.error,
semanticLabel: 'Reset to defaults?',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text(
'Cancel',
style: TextStyle(color: colorScheme.onSurfaceVariant),
child: Icon(
Icons.close,
color: colorScheme.onSurfaceVariant,
semanticLabel: 'Cancel',
),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: Text('Reset', style: TextStyle(color: colorScheme.error)),
child: Icon(
Icons.restart_alt,
color: colorScheme.error,
semanticLabel: 'Reset',
),
),
],
),
@ -83,4 +86,20 @@ extension _SettingsScreenActions on _SettingsScreenState {
),
);
}
/// Flags an exercise edit that stayed on this phone (the push did not
/// happen). Was "Saved on this phone, not synced: `reason`"; the reason
/// now goes to the log, the screen shows the glyph.
void _flagUnsynced(String reason) {
log('Settings: saved on this phone, not synced: $reason', level: 900);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Icon(
Icons.cloud_off,
color: Theme.of(context).colorScheme.error,
semanticLabel: 'Saved on this phone, not synced',
),
),
);
}
}

View File

@ -21,9 +21,17 @@ extension _SettingsScreenDeload on _SettingsScreenState {
if (!mounted) return null;
final next = result.state;
if (next == null) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(result.reason)));
// Was the refusal reason as a sentence; it goes to the log instead.
log('Settings: deload of $name refused: ${result.reason}', level: 900);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Icon(
Icons.block,
color: Theme.of(context).colorScheme.error,
semanticLabel: 'Deload failed',
),
),
);
return null;
}
SandboxLog.event('manual deload', {

View File

@ -25,20 +25,11 @@ class _ExercisesSection extends StatelessWidget {
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _SectionHeader('PER EXERCISE'),
const SizedBox(height: 4),
Text(
'Progression, warmup, rest and injury pause. '
'Same settings as the workout tile.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
// textgate: the helper sentence under the heading is gone.
const _SectionHeader(Icons.tune, 'PER EXERCISE'),
const SizedBox(height: 12),
...orderedNames.map((name) {
final s = states[name];
@ -57,29 +48,50 @@ class _ExerciseSettingsRow extends StatelessWidget {
final ExerciseState state;
final VoidCallback onTap;
String get _summary {
// textgate: was "kg · ↑3 ↓2 · rest 3:00 / 5:00 · warmup 1:00" (or
// "no warmup"). Now the mode glyph (or rep range), the thresholds, a
// timer glyph before the rests, and a sun glyph before the warmup rest
// (absent when there is no warmup).
Widget _summary(Color color) {
final s = state;
final mode = switch (s.mode) {
ProgressionMode.weight => 'kg',
ProgressionMode.reps => 'reps',
ProgressionMode.doubleProgression => '${s.repsLow}→${s.repsHigh} reps',
final style = TextStyle(color: color, fontSize: AppTextSize.caption);
final modeIcon = switch (s.mode) {
ProgressionMode.weight => Icons.fitness_center,
ProgressionMode.reps => Icons.repeat,
ProgressionMode.doubleProgression => null,
};
final warmup = s.hasWarmup
? 'warmup ${formatRest(s.restWarmupSecs)}'
: 'no warmup';
return '$mode · ↑${s.successThreshold} ↓${s.failThreshold} · '
'rest ${formatRest(s.restSuccessSecs)} / '
'${formatRest(s.restFailSecs)} · $warmup';
return Row(
key: const Key('exercise_settings_summary'),
children: [
if (modeIcon == null)
Text('${s.repsLow}→${s.repsHigh}', style: style)
else
Icon(modeIcon, size: 14, color: color),
Text(' ↑${s.successThreshold} ↓${s.failThreshold} ', style: style),
Icon(Icons.timer, size: 14, color: color),
Text(
' ${formatRest(s.restSuccessSecs)} / ${formatRest(s.restFailSecs)}',
style: style,
),
if (s.hasWarmup) ...[
const SizedBox(width: 8),
Icon(Icons.wb_sunny, size: 14, color: color),
Text(' ${formatRest(s.restWarmupSecs)}', style: style),
],
],
);
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final until = state.isPausedAt(DateTime.now()) ? state.pausedUntil : null;
// Spoken only: excludeSemantics hides the painted children from it.
final semanticsLabel = '${state.name} exercise settings';
return Semantics(
container: true,
button: true,
label: '${state.name} exercise settings',
label: semanticsLabel,
excludeSemantics: true,
child: InkWell(
onTap: onTap,
@ -106,21 +118,26 @@ class _ExerciseSettingsRow extends StatelessWidget {
),
),
const SizedBox(height: 4),
Text(
_summary,
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
_summary(colorScheme.onSurfaceVariant),
if (until != null) ...[
const SizedBox(height: 4),
Text(
'Paused — back on ${formatShortDate(until)}',
style: TextStyle(
color: colorScheme.error,
fontSize: AppTextSize.caption,
),
// textgate: was "Paused — back on 11 Oct".
Row(
children: [
Icon(
Icons.pause_circle_outline,
size: 14,
color: colorScheme.error,
),
const SizedBox(width: 4),
Text(
formatShortDate(until),
style: TextStyle(
color: colorScheme.error,
fontSize: AppTextSize.caption,
),
),
],
),
],
],

View File

@ -26,20 +26,11 @@ class _WeightsSection extends StatelessWidget {
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _SectionHeader('WEIGHTS'),
const SizedBox(height: 4),
Text(
'Override current working weight. '
'Resets streak counters. Rounded to 2.5 kg.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
// textgate: the helper sentence under the heading is gone.
const _SectionHeader(Icons.fitness_center, 'WEIGHTS'),
const SizedBox(height: 12),
...orderedNames.map((name) {
final w = weights[name];
@ -74,21 +65,11 @@ class _RepsSection extends StatelessWidget {
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _SectionHeader('TARGET REPS'),
const SizedBox(height: 4),
Text(
'Override target reps per set. Resets streak counters. '
'Progression only ever raises reps, so this is the only way '
'to lower one.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
// textgate: the helper sentence under the heading is gone.
const _SectionHeader(Icons.repeat, 'TARGET REPS'),
const SizedBox(height: 12),
...orderedNames.map((name) {
final r = reps[name];

View File

@ -20,7 +20,7 @@ class _PcLinkSection extends StatefulWidget {
class _PcLinkSectionState extends State<_PcLinkSection> {
final TextEditingController _host = TextEditingController();
bool? _paired;
String? _status;
({bool ok, String spoken})? _status;
@override
void initState() {
@ -44,32 +44,39 @@ class _PcLinkSectionState extends State<_PcLinkSection> {
Future<void> _save() async {
final host = _host.text.trim();
if (!isValidPcHost(host)) {
setState(() => _status = 'Not an IPv4 address or hostname: "$host".');
setState(
() => _status = (
ok: false,
spoken: 'Not an IPv4 address or hostname: "$host".',
),
);
return;
}
await PcPairing.saveHost(host);
SandboxLog.event('pc host saved', {'host': host});
setState(() => _status = 'Workouts are now sent to $host:$kPcPokePort.');
setState(
() => _status = (
ok: true,
spoken: 'Workouts are now sent to $host:$kPcPokePort.',
),
);
}
static String _pairedSemanticsLabel(bool? paired) => switch (paired) {
null => 'PC paired: checking…',
true => 'PC paired ✓',
false => 'PC paired ✗ — run scripts/pair_phone.sh on the PC',
};
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final status = Theme.of(context).extension<AppStatusColors>()!;
final paired = _paired;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _SectionHeader('PC LINK'),
const SizedBox(height: AppSpacing.xs),
Text(
'A finished workout is sent straight to the PC on the home Wi-Fi, '
'so the credit lands in a second. Sync still delivers it otherwise.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
// textgate: the explanation sentence under the heading is gone.
const _SectionHeader(Icons.computer, 'PC LINK'),
const SizedBox(height: AppSpacing.sm),
Row(
children: [
@ -78,9 +85,10 @@ class _PcLinkSectionState extends State<_PcLinkSection> {
key: const Key('pc-host'),
controller: _host,
keyboardType: TextInputType.url,
// Was labelText 'PC address'.
decoration: const InputDecoration(
isDense: true,
labelText: 'PC address',
prefixIcon: Icon(Icons.computer, semanticLabel: 'PC address'),
),
),
),
@ -90,32 +98,32 @@ class _PcLinkSectionState extends State<_PcLinkSection> {
onPressed: () => unawaited(_save()),
// Distinct label: the sandbox section has its own "Save", and
// two identical labels cannot be driven by element.
child: const Text('Save', semanticsLabel: 'Save PC address'),
child: const Icon(Icons.save, semanticLabel: 'Save PC address'),
),
],
),
const SizedBox(height: AppSpacing.sm),
Text(
switch (paired) {
null => 'PC paired: checking…',
true => 'PC paired ✓',
false => 'PC paired ✗ — run scripts/pair_phone.sh on the PC',
},
key: const Key('pc-paired'),
style: TextStyle(
// textgate: was "PC paired: checking…" / "PC paired ✓" / "PC
// paired ✗ — run scripts/pair_phone.sh on the PC". Now a link glyph
// (hourglass while checking, broken link when unpaired) in the
// success / warning colour.
Align(
alignment: Alignment.centerLeft,
child: Icon(
switch (paired) {
null => Icons.hourglass_empty,
true => Icons.link,
false => Icons.link_off,
},
key: const Key('pc-paired'),
size: 20,
color: paired ?? false ? status.success : status.warning,
fontSize: AppTextSize.caption,
semanticLabel: _pairedSemanticsLabel(paired),
),
),
if (_status != null) ...[
if (_status case final s?) ...[
const SizedBox(height: AppSpacing.xs),
Text(
_status!,
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
_StatusGlyph(ok: s.ok, spoken: s.spoken),
],
],
);

View File

@ -4,19 +4,23 @@
// See history_screen_charts.dart for the full reasoning.
part of 'settings_screen.dart';
/// A section heading as a glyph (textgate: was an all-caps word; the word
/// survives as [spoken], the glyph's semantic label).
class _SectionHeader extends StatelessWidget {
const _SectionHeader(this.text);
const _SectionHeader(this.icon, this.spoken);
final String text;
final IconData icon;
final String spoken;
@override
Widget build(BuildContext context) {
return Text(
text,
style: TextStyle(
return Align(
alignment: Alignment.centerLeft,
child: Icon(
icon,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
letterSpacing: 1.4,
semanticLabel: spoken,
),
);
}
@ -56,7 +60,8 @@ class _RepsRow extends StatelessWidget {
SizedBox(
width: 72,
child: Text(
'$reps reps',
// textgate: was "12 reps"; the section's repeat glyph says it.
'×$reps',
textAlign: TextAlign.center,
style: TextStyle(
color: colorScheme.onSurface,
@ -104,9 +109,8 @@ class _WeightRow extends StatelessWidget {
),
_StepperButton(
icon: Icons.remove,
onTap: () => onChanged(
(weight - kWeightIncrement).clamp(0.0, 999.0),
),
onTap: () =>
onChanged((weight - kWeightIncrement).clamp(0.0, 999.0)),
),
// Fixed-width container supports up to "999.9kg" (7 chars).
SizedBox(
@ -155,3 +159,27 @@ class _StepperButton extends StatelessWidget {
);
}
}
/// An action's outcome as a glyph: a tick (success colour) or a warning
/// sign (warning colour). textgate: replaces a painted status sentence;
/// the sentence survives as [spoken], the glyph's semantic label.
class _StatusGlyph extends StatelessWidget {
const _StatusGlyph({required this.ok, required this.spoken, super.key});
final bool ok;
final String spoken;
@override
Widget build(BuildContext context) {
final status = Theme.of(context).extension<AppStatusColors>()!;
return Align(
alignment: Alignment.centerLeft,
child: Icon(
ok ? Icons.check_circle : Icons.error_outline,
size: 18,
color: ok ? status.success : status.warning,
semanticLabel: spoken,
),
);
}
}

View File

@ -18,7 +18,7 @@ class _SandboxSectionState extends State<_SandboxSection> {
late final TextEditingController _rest = TextEditingController(
text: '${Sandbox.restSecs}',
);
String? _status;
({bool ok, String spoken})? _status;
@override
void dispose() {
@ -26,9 +26,9 @@ class _SandboxSectionState extends State<_SandboxSection> {
super.dispose();
}
void _report(String status) {
void _report(String status, {bool ok = true}) {
SandboxLog.event('sandbox settings', {'status': status});
setState(() => _status = status);
setState(() => _status = (ok: ok, spoken: status));
}
Future<void> _wipe() async {
@ -53,7 +53,10 @@ class _SandboxSectionState extends State<_SandboxSection> {
Future<void> _saveRest() async {
final secs = int.tryParse(_rest.text.trim());
if (secs == null || secs < 1) {
_report('Rest length must be a whole number of seconds, 1 or more.');
_report(
'Rest length must be a whole number of seconds, 1 or more.',
ok: false,
);
return;
}
await StorageService.instance.setSandboxRestSecs(secs);
@ -73,38 +76,36 @@ class _SandboxSectionState extends State<_SandboxSection> {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _SectionHeader('SANDBOX'),
const SizedBox(height: 4),
Text(
'This install is the sandbox: its own data, no sync (only the '
'signed sandbox poke to the PC LINK address, which the PC never '
'credits), no LAN server. Nothing here can reach the daily build.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
// textgate: the explanation paragraph under the heading is gone.
const _SectionHeader(Icons.science, 'SANDBOX'),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ElevatedButton.icon(
ElevatedButton(
onPressed: () => unawaited(_wipe()),
icon: const Icon(Icons.delete_sweep),
label: const Text('Wipe sandbox data'),
child: Icon(
Icons.delete_sweep,
color: colorScheme.error,
semanticLabel: 'Wipe sandbox data',
),
),
ElevatedButton.icon(
ElevatedButton(
onPressed: () => unawaited(_markTodayNotDone()),
icon: const Icon(Icons.undo),
label: const Text('Mark today not done'),
child: const Icon(
Icons.undo,
semanticLabel: 'Mark today not done',
),
),
],
),
const SizedBox(height: 12),
Row(
children: [
const Expanded(child: Text('Rest length (seconds)')),
// Was "Rest length (seconds)"; the field shows the number.
const Icon(Icons.timer, semanticLabel: 'Rest length (seconds)'),
const Spacer(),
SizedBox(
width: 72,
child: TextField(
@ -112,16 +113,14 @@ class _SandboxSectionState extends State<_SandboxSection> {
controller: _rest,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
decoration: const InputDecoration(
isDense: true,
hintText: 'seconds',
),
decoration: const InputDecoration(isDense: true),
),
),
const SizedBox(width: 8),
TextButton(
onPressed: () => unawaited(_saveRest()),
child: const Text('Save'),
// Spoken label distinct from the PC LINK "Save PC address".
child: const Icon(Icons.save, semanticLabel: 'Save'),
),
],
),
@ -146,14 +145,12 @@ class _SandboxSectionState extends State<_SandboxSection> {
),
],
),
if (_status != null) ...[
if (_status case final s?) ...[
const SizedBox(height: 8),
Text(
_status!,
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
_StatusGlyph(
key: const Key('sandbox-status'),
ok: s.ok,
spoken: s.spoken,
),
],
],

View File

@ -13,13 +13,13 @@ part of 'settings_screen.dart';
/// The SYNC section: progression status line plus the two sync routes.
class _SyncSection extends StatelessWidget {
const _SyncSection({
required this.progressionStatus,
required this.restoredCount,
required this.onOpenSyncSettings,
required this.onOpenGitHubMirror,
});
/// Last progression-sync outcome, or null when there is nothing to report.
final String? progressionStatus;
/// Exercises the last progression pull restored, or null when none did.
final int? restoredCount;
/// Opens the Firebase sync settings screen.
final VoidCallback onOpenSyncSettings;
@ -33,15 +33,29 @@ class _SyncSection extends StatelessWidget {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _SectionHeader('SYNC'),
const _SectionHeader(Icons.sync, 'SYNC'),
const SizedBox(height: 4),
if (progressionStatus != null) ...[
Text(
progressionStatus!,
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
// textgate: was "Restored N exercise(s) from Firebase."; now a
// download glyph and the count, in the success colour.
if (restoredCount != null) ...[
Row(
key: const Key('settings_restored'),
children: [
Icon(
Icons.cloud_download,
size: 18,
color: Theme.of(context).extension<AppStatusColors>()!.success,
semanticLabel: 'Restored from Firebase',
),
const SizedBox(width: 6),
Text(
'$restoredCount',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
],
),
const SizedBox(height: 8),
],
@ -50,14 +64,12 @@ class _SyncSection extends StatelessWidget {
color: colorScheme.surfaceContainerHigh,
child: Column(
children: [
// textgate: was "Sync settings" / "Firebase sync".
ListTile(
title: Text(
'Sync settings',
style: TextStyle(color: colorScheme.onSurface),
),
subtitle: Text(
'Firebase sync',
style: TextStyle(color: colorScheme.onSurfaceVariant),
leading: Icon(
Icons.cloud,
color: colorScheme.onSurface,
semanticLabel: 'Sync settings',
),
trailing: Icon(
Icons.chevron_right,
@ -69,14 +81,14 @@ class _SyncSection extends StatelessWidget {
height: 1,
color: colorScheme.onSurfaceVariant.withValues(alpha: 0.2),
),
// textgate: was "Advanced sync (GitHub)" / "Cutover mirror —
// not recommended": a code glyph, muted as the not-recommended
// route.
ListTile(
title: Text(
'Advanced sync (GitHub)',
style: TextStyle(color: colorScheme.onSurface),
),
subtitle: Text(
'Cutover mirror — not recommended',
style: TextStyle(color: colorScheme.onSurfaceVariant),
leading: Icon(
Icons.code,
color: colorScheme.onSurfaceVariant,
semanticLabel: 'Advanced sync (GitHub)',
),
trailing: Icon(
Icons.chevron_right,
@ -107,42 +119,35 @@ class _OfflineBackupSection extends StatelessWidget {
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _SectionHeader('OFFLINE BACKUP'),
const SizedBox(height: 4),
Text(
storageGranted
? 'Granted. Progression is also written to '
'$kBackupPath, so it survives a reinstall even '
'with no network.'
: 'Optional. Progression is restored from Firebase on '
'a fresh install, so this is a second, offline '
'copy — not a requirement. Granting it also keeps '
'a readable snapshot at $kBackupPath.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
// textgate: the explanation paragraph under the heading is gone.
const _SectionHeader(Icons.sd_storage, 'OFFLINE BACKUP'),
const SizedBox(height: 12),
if (storageGranted)
const Row(
// Was "Storage permission granted": storage glyph + green tick.
Row(
children: [
Icon(Icons.check_circle, size: 20),
SizedBox(width: 8),
Expanded(child: Text('Storage permission granted')),
const Icon(Icons.sd_storage, size: 20),
const SizedBox(width: 4),
Icon(
Icons.check_circle,
size: 20,
color: Theme.of(context).extension<AppStatusColors>()!.success,
semanticLabel: 'Storage permission granted',
),
],
)
else
Align(
alignment: Alignment.centerLeft,
child: ElevatedButton.icon(
child: ElevatedButton(
onPressed: onGrantStorage,
icon: const Icon(Icons.sd_storage),
label: const Text('Grant storage permission'),
child: const Icon(
Icons.sd_storage,
semanticLabel: 'Grant storage permission',
),
),
),
DataTransferButtons(
@ -176,16 +181,14 @@ class _SettingsAppBar extends StatelessWidget implements PreferredSizeWidget {
final colorScheme = Theme.of(context).colorScheme;
return AppBar(
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text('Settings', style: TextStyle(color: colorScheme.onSurface)),
title: const Icon(Icons.settings, size: 20, semanticLabel: 'Settings'),
iconTheme: IconThemeData(color: colorScheme.onSurface),
actions: [
const RunnerUpImportBadge(),
TextButton(
IconButton(
onPressed: loading ? null : onReset,
child: Text(
'Reset defaults',
style: TextStyle(color: colorScheme.error),
),
color: colorScheme.error,
icon: const Icon(Icons.restart_alt, semanticLabel: 'Reset defaults'),
),
],
);

View File

@ -25,7 +25,7 @@ class _SoundSection extends StatelessWidget {
child: SwitchListTile(
value: enabled,
onChanged: onChanged,
title: Text('Sound', style: TextStyle(color: colorScheme.onSurface)),
title: const Icon(Icons.volume_up, size: 20, semanticLabel: 'Sound'),
),
);
}

View File

@ -200,7 +200,16 @@ extension _WorkoutScreenBreaks on _WorkoutScreenState {
ExerciseState? _deloadRefused(String why) {
log('WorkoutScreen: deload not applied — $why', level: 900);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(why)));
// Was the refusal reason as a sentence; it stays in the log above.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Icon(
Icons.block,
color: Theme.of(context).colorScheme.error,
semanticLabel: 'Deload refused',
),
),
);
}
return null;
}

View File

@ -13,21 +13,28 @@ extension _WorkoutScreenDialogs on _WorkoutScreenState {
context: context,
builder: (_) => AlertDialog(
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text(
'Finish workout?',
style: TextStyle(color: colorScheme.onSurface),
// Was "Finish workout?" with Cancel / Finish buttons.
title: Icon(
Icons.done_all,
color: status.success,
semanticLabel: 'Finish workout?',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text(
'Cancel',
style: TextStyle(color: colorScheme.onSurfaceVariant),
child: Icon(
Icons.close,
color: colorScheme.onSurfaceVariant,
semanticLabel: 'Cancel',
),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: Text('Finish', style: TextStyle(color: status.success)),
child: Icon(
Icons.done_all,
color: status.success,
semanticLabel: 'Finish',
),
),
],
),
@ -42,25 +49,29 @@ extension _WorkoutScreenDialogs on _WorkoutScreenState {
context: context,
builder: (_) => AlertDialog(
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text(
'Reset workout?',
style: TextStyle(color: colorScheme.onSurface),
),
content: Text(
'All progress will be lost.',
style: TextStyle(color: colorScheme.onSurfaceVariant),
// Was "Reset workout?" / "All progress will be lost." with
// Cancel / Reset buttons: the reset glyph in the error colour.
title: Icon(
Icons.restart_alt,
color: colorScheme.error,
semanticLabel: 'Reset workout? All progress will be lost.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text(
'Cancel',
style: TextStyle(color: colorScheme.onSurfaceVariant),
child: Icon(
Icons.close,
color: colorScheme.onSurfaceVariant,
semanticLabel: 'Cancel',
),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: Text('Reset', style: TextStyle(color: colorScheme.error)),
child: Icon(
Icons.restart_alt,
color: colorScheme.error,
semanticLabel: 'Reset',
),
),
],
),

View File

@ -123,9 +123,10 @@ extension _WorkoutScreenIntents on _WorkoutScreenState {
if (result.needsPermissionWarning && mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Notifications are off — the rest timer still runs and still '
'sounds, but there will be no status-bar countdown.',
content: Icon(
Icons.notifications_off,
size: 20,
semanticLabel: 'Notifications are off',
),
duration: Duration(seconds: 6),
),

View File

@ -39,37 +39,56 @@ class BreakNotificationCopy {
/// and testable without a device.
abstract final class BreakNotificationText {
/// Renders the notification for [snapshot] as of [now].
///
/// Symbols and numbers only (textgate). The same glyphs as the alert
/// notifications in break_service_port_flutter.dart: [doneGlyph] for a
/// finished workout, [breakOverGlyph] when the rest is up.
static BreakNotificationCopy render(BreakSnapshot snapshot, DateTime now) {
if (snapshot.finished) {
return const BreakNotificationCopy(
'Workout complete',
'Open the app to save it.',
);
// Was "Workout complete" / "Open the app to save it."
return const BreakNotificationCopy(doneGlyph, '');
}
return BreakNotificationCopy(
_title(snapshot, now),
_body(snapshot),
);
return BreakNotificationCopy(_title(snapshot, now), _body(snapshot));
}
/// Finished workout (all sets, or the workout itself).
static const doneGlyph = '✅';
/// The rest period is over.
static const breakOverGlyph = '⏰';
/// A rest period is counting down.
static const breakGlyph = '⏱';
/// Lifting: no rest running.
static const liftGlyph = '🏋';
/// Name of every notification channel: the app's proper noun only
/// (textgate settled decision 4), the same as `MaterialApp.title`.
static const channelName = 'Workout Tracker';
// Was "Workout A · lift" / "Workout A · break over" / "Workout A · break
// 1:47".
static String _title(BreakSnapshot s, DateTime now) {
final prefix = 'Workout ${s.workoutType}';
final prefix = '$liftGlyph ${s.workoutType}';
if (!s.hasBreak) {
return '$prefix · lift';
return prefix;
}
final clock = BreakClock(
endTime: DateTime.fromMillisecondsSinceEpoch(s.breakEndMs),
durationSecs: s.breakDurationSecs,
);
final remaining = clock.remainingSecsAt(now);
if (remaining <= 0) return '$prefix · break over';
return '$prefix · break ${formatMmSs(remaining)}';
if (remaining <= 0) return '$prefix · $breakOverGlyph';
return '$prefix · $breakGlyph ${formatMmSs(remaining)}';
}
// Was "Every set is done — finish the workout." / "Next: Squat — set 3/5
// \n5 reps @ 40 kg". The exercise name is user content.
static String _body(BreakSnapshot s) {
if (!s.hasNextSet) return 'Every set is done — finish the workout.';
return 'Next: ${s.nextExName} — set ${s.nextSetNumber}/${s.nextTotalSets}\n'
'${s.nextReps} reps @ ${formatWeight(s.nextWeight)} kg';
if (!s.hasNextSet) return doneGlyph;
return '→ ${s.nextExName} ${s.nextSetNumber}/${s.nextTotalSets}\n'
'${s.nextReps} × ${formatWeight(s.nextWeight)} kg';
}
/// Formats [totalSecs] as `m:ss`, e.g. 107 -> `1:47`.

View File

@ -30,6 +30,9 @@ const kBreakEndSilentChannelId = 'break_end_silent_v1';
/// Notification id of the terminal "workout complete" message.
const kWorkoutDoneNotificationId = 8802;
/// Name of every notification channel here: the app's proper noun.
const String _kChannelName = BreakNotificationText.channelName;
/// The real [BreakServicePort], running inside the foreground-service isolate.
class FlutterBreakServicePort implements BreakServicePort {
/// Creates a port. Cheap: nothing happens until [ensureIsolateReady].
@ -64,7 +67,9 @@ class FlutterBreakServicePort implements BreakServicePort {
?.createNotificationChannel(
const AndroidNotificationChannel(
kBreakEndChannelId,
'Break finished',
// Channel names are the app name only (textgate settled
// decision 4). Was 'Break finished' / 'Break finished, no tone'.
_kChannelName,
description: 'Sounds when a rest period between sets is over.',
importance: Importance.max,
sound: RawResourceAndroidNotificationSound('break_end'),
@ -77,7 +82,7 @@ class FlutterBreakServicePort implements BreakServicePort {
?.createNotificationChannel(
const AndroidNotificationChannel(
kBreakEndSilentChannelId,
'Break finished, no tone',
_kChannelName,
importance: Importance.max,
playSound: false,
),
@ -110,12 +115,13 @@ class FlutterBreakServicePort implements BreakServicePort {
}
await _notifications.show(
id: kBreakEndNotificationId,
title: 'Break over',
body: 'Back to the bar.',
// Was "Break over" / "Back to the bar.".
title: BreakNotificationText.breakOverGlyph,
body: '',
notificationDetails: NotificationDetails(
android: AndroidNotificationDetails(
sound ? kBreakEndChannelId : kBreakEndSilentChannelId,
sound ? 'Break finished' : 'Break finished, no tone',
_kChannelName,
playSound: sound,
importance: Importance.max,
priority: Priority.max,
@ -134,12 +140,13 @@ class FlutterBreakServicePort implements BreakServicePort {
Future<void> finishAndStop() async {
await _notifications.show(
id: kWorkoutDoneNotificationId,
title: 'Workout complete',
body: 'Open the app to save it.',
// Was "Workout complete" / "Open the app to save it.".
title: BreakNotificationText.doneGlyph,
body: '',
notificationDetails: const NotificationDetails(
android: AndroidNotificationDetails(
kBreakEndChannelId,
'Break finished',
_kChannelName,
importance: Importance.high,
priority: Priority.high,
),

View File

@ -7,6 +7,7 @@ import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/break_intent_store.dart';
import 'package:workout_app/services/break_notification_text.dart';
import 'package:workout_app/services/break_service_port.dart';
import 'package:workout_app/services/break_service_port_flutter.dart';
import 'package:workout_app/services/break_task_handler.dart';
@ -21,7 +22,8 @@ import 'package:workout_app/services/foreground_break_client.dart';
const kWorkoutOngoingChannelId = 'workout_ongoing_v1';
/// Button labels, parallel to [BreakNotificationAction.inButtonOrder].
const _buttonLabels = ['✓ Done', '− 1 rep', 'Skip break'];
/// Symbols only; was ['✓ Done', '− 1 rep', 'Skip break'].
const _buttonLabels = ['✓', '−1', '⏭'];
/// Entry point the plugin calls in the background isolate.
// coverage:ignore-start
@ -57,8 +59,7 @@ class _BreakServiceTaskHandler extends TaskHandler {
void onRepeatEvent(DateTime timestamp) => _handler.tick(timestamp);
@override
void onReceiveData(Object data) =>
_handler.receiveData(data, DateTime.now());
void onReceiveData(Object data) => _handler.receiveData(data, DateTime.now());
@override
void onNotificationButtonPressed(String id) =>
@ -92,7 +93,9 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: kWorkoutOngoingChannelId,
channelName: 'Workout in progress',
// App name only (textgate settled decision 4); was 'Workout in
// progress'.
channelName: BreakNotificationText.channelName,
channelDescription:
'Shows the rest countdown and the next set while a workout '
'runs. Kept silent on purpose: the break-end alert has its own '
@ -130,8 +133,10 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
}
final result = await FlutterForegroundTask.startService(
serviceTypes: [ForegroundServiceTypes.dataSync],
notificationTitle: 'Workout ${snapshot.workoutType}',
notificationText: 'Starting…',
// Same prefix as BreakNotificationText; was 'Workout A' / 'Starting…'.
notificationTitle:
'${BreakNotificationText.liftGlyph} ${snapshot.workoutType}',
notificationText: '…',
notificationButtons: [
for (final (i, id) in BreakNotificationAction.inButtonOrder.indexed)
NotificationButton(id: id, text: _buttonLabels[i]),

View File

@ -4,6 +4,7 @@ library;
import 'dart:io' show Platform;
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:workout_app/services/break_notification_text.dart';
import 'package:workout_app/services/foreground_run_client.dart';
/// Channel the ongoing run notification lives on.
@ -72,7 +73,8 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: kRunOngoingChannelId,
channelName: '\u{1F3C3}',
// App name only (textgate settled decision 4); was the runner emoji.
channelName: BreakNotificationText.channelName,
onlyAlertOnce: true,
),
iosNotificationOptions: const IOSNotificationOptions(),

View File

@ -98,28 +98,35 @@ class BreakBanner extends StatelessWidget {
visible: active,
child: TextButton(
onPressed: onSkip,
child: Text('Skip', style: TextStyle(color: colorScheme.primary)),
child: Icon(
Icons.skip_next,
color: colorScheme.primary,
semanticLabel: 'Skip',
),
),
),
_slot(
visible: !finished,
child: TextButton(
onPressed: onReset,
child: Text('Reset', style: TextStyle(color: colorScheme.error)),
child: Icon(
Icons.restart_alt,
color: colorScheme.error,
semanticLabel: 'Reset',
),
),
),
_slot(
visible: !finished,
child: TextButton(
onPressed: canFinish ? onFinish : null,
child: Text(
'Finish',
style: TextStyle(
color: canFinish
? status.success
: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.bold,
),
// Muted while finishing is not allowed yet, as the old label.
child: Icon(
Icons.done_all,
color: canFinish
? status.success
: colorScheme.onSurfaceVariant,
semanticLabel: 'Finish',
),
),
),

View File

@ -27,21 +27,16 @@ class WorkoutCalendar extends StatelessWidget {
/// Called when the user taps the next-month chevron.
final VoidCallback onNextMonth;
static const _weekHeaders = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
static const _monthNames = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
// textgate: weekday headers are dots (weekend dots hollow) and the
// month header is `08.2026`; the old words are spoken only.
static const _weekdaySemanticsLabels = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
String _dateKey(int year, int m, int day) =>
@ -81,7 +76,7 @@ class WorkoutCalendar extends StatelessWidget {
onPressed: onPrevMonth,
),
Text(
'${_monthNames[m - 1]} $year',
'${m.toString().padLeft(2, '0')}.$year',
style: TextStyle(
color: colorScheme.onSurface,
fontWeight: FontWeight.bold,
@ -103,22 +98,29 @@ class WorkoutCalendar extends StatelessWidget {
// Day-of-week headers
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: _weekHeaders
.map(
(h) => SizedBox(
width: 30,
child: Text(
h,
textAlign: TextAlign.center,
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
fontWeight: FontWeight.bold,
children: [
for (var i = 0; i < 7; i++)
SizedBox(
width: 30,
child: Semantics(
label: _weekdaySemanticsLabels[i],
child: Center(
child: Container(
width: 6,
height: 6,
decoration: BoxDecoration(
shape: BoxShape.circle,
// Weekend: hollow ring; weekday: filled dot.
color: i >= 5 ? null : colorScheme.onSurfaceVariant,
border: Border.all(
color: colorScheme.onSurfaceVariant,
),
),
),
),
),
)
.toList(),
),
],
),
const SizedBox(height: 4),
// Day grid

View File

@ -89,14 +89,15 @@ class _ExerciseSettingsSheetState extends State<ExerciseSettingsSheet> {
setState(() => _s = next);
}
// Numbers and symbols only. Was "+X kg per step; +1 rep once at the Y kg
// cap" / "+1 rep per step; the weight never changes" / "+1 rep per step
// up to N, then +X kg and back to M".
String get _modeHint => switch (_s.mode) {
ProgressionMode.weight =>
'+$kWeightIncrement kg per step; +1 rep once at the '
'${_s.maxWeight} kg cap',
ProgressionMode.reps => '+1 rep per step; the weight never changes',
'+$kWeightIncrement kg · ${_s.maxWeight} kg ⇒ +1',
ProgressionMode.reps => '+1',
ProgressionMode.doubleProgression =>
'+1 rep per step up to ${_s.repsHigh}, then +$kWeightIncrement kg '
'and back to ${_s.repsLow}',
'+1 … ${_s.repsHigh} ⇒ +$kWeightIncrement kg, ${_s.repsLow}',
};
@override
@ -130,15 +131,16 @@ class _ExerciseSettingsSheetState extends State<ExerciseSettingsSheet> {
segments: const [
ButtonSegment(
value: ProgressionMode.weight,
label: Text('Weight'),
// Was 'Weight' / 'Reps' / 'Reps→kg'.
label: Icon(Icons.fitness_center, semanticLabel: 'Weight'),
),
ButtonSegment(
value: ProgressionMode.reps,
label: Text('Reps'),
label: Icon(Icons.repeat, semanticLabel: 'Reps'),
),
ButtonSegment(
value: ProgressionMode.doubleProgression,
label: Text('Reps→kg'),
label: Icon(Icons.trending_up, semanticLabel: 'Reps→kg'),
),
],
selected: {_s.mode},
@ -160,12 +162,14 @@ class _ExerciseSettingsSheetState extends State<ExerciseSettingsSheet> {
maintainAnimation: true,
maintainState: true,
child: _SettingRow(
label: '+kg at',
// Was "+kg at [N] reps, restart at [M]".
label: '+',
icon: Icons.fitness_center,
name: 'Top reps',
value: _s.repsHigh,
min: _s.repsLow + 1,
max: _maxRepsHigh,
suffix: 'reps, restart at',
suffix: '↺',
trailing: _Stepper(
name: 'Restart reps',
value: _s.repsLow,
@ -179,17 +183,22 @@ class _ExerciseSettingsSheetState extends State<ExerciseSettingsSheet> {
const SizedBox(height: 4),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Warmup set'),
// Was 'Warmup set'; the sun matches the warmup rest row.
title: const Align(
alignment: Alignment.centerLeft,
child: Icon(Icons.wb_sunny, semanticLabel: 'Warmup set'),
),
value: _s.hasWarmup,
onChanged: (v) => _update(_s.copyWith(hasWarmup: v)),
),
_SettingRow(
label: '↑ after',
// Was "↑ after [N] wins, ↓ after [M]".
label: '↑',
name: 'Wins needed',
value: _s.successThreshold,
min: 1,
max: 5,
suffix: 'wins, ↓ after',
suffix: '↓',
trailing: _Stepper(
name: 'Fails allowed',
value: _s.failThreshold,

View File

@ -18,16 +18,16 @@ class _DeloadRow extends StatelessWidget {
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final change = describeTargetChange(state, targetAfterFailure(state));
final canDeload = change != 'same';
final canDeload = change != kNoTargetChange;
return SizedBox(
height: 40,
child: Row(
children: [
// Was "Deload <target> → <change>" / "Deload nothing lower to
// go to": the down-trend glyph is the button, the numbers stay.
Expanded(
child: Text(
canDeload
? 'Deload ${_target(state)} → $change'
: 'Deload nothing lower to go to',
canDeload ? '${_target(state)} → $change' : '—',
style: TextStyle(
color: colorScheme.onSurface,
fontSize: AppTextSize.label,
@ -37,7 +37,11 @@ class _DeloadRow extends StatelessWidget {
),
TextButton(
onPressed: canDeload ? onDeload : null,
child: const Text('Deload now'),
child: Icon(
Icons.trending_down,
color: canDeload ? colorScheme.error : null,
semanticLabel: 'Deload now',
),
),
],
),
@ -62,26 +66,33 @@ Future<bool> _confirmDeload(BuildContext context, ExerciseState s) async {
context: context,
builder: (dialogContext) => AlertDialog(
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text(
'Deload ${s.name}?',
style: TextStyle(color: colorScheme.onSurface),
// Was "Deload <name>?" / "<target> → <change>\n\nStreaks reset. Only
// finished workouts raise it again.": glyph + the numbers.
title: Icon(
Icons.trending_down,
color: colorScheme.error,
semanticLabel: 'Deload ${s.name}?',
),
content: Text(
'${_target(s)} → $change\n\n'
'Streaks reset. Only finished workouts raise it again.',
'${_target(s)} → $change',
style: TextStyle(color: colorScheme.onSurfaceVariant),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(
'Cancel',
style: TextStyle(color: colorScheme.onSurfaceVariant),
child: Icon(
Icons.close,
color: colorScheme.onSurfaceVariant,
semanticLabel: 'Cancel',
),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: Text('Deload', style: TextStyle(color: colorScheme.error)),
child: Icon(
Icons.trending_down,
color: colorScheme.error,
semanticLabel: 'Deload',
),
),
],
),

View File

@ -35,7 +35,7 @@ class _RestRows extends StatelessWidget {
children: [
Row(
children: [
Text('Rest ✓', style: style),
Text('✓', style: style),
const SizedBox(width: 8),
_stepper(
'Success rest',
@ -60,7 +60,7 @@ class _RestRows extends StatelessWidget {
maintainState: true,
child: Row(
children: [
Text('Warmup rest', style: style),
Text('☀', style: style),
const SizedBox(width: 8),
_stepper(
'Warmup rest',

View File

@ -14,10 +14,14 @@ class _SettingRow extends StatelessWidget {
required this.suffix,
required this.trailing,
required this.onChanged,
this.icon,
});
final String label;
/// Optional glyph painted right after [label] (e.g. `+` then a weight).
final IconData? icon;
/// Semantic name of the leading stepper.
final String name;
final int value;
@ -36,6 +40,8 @@ class _SettingRow extends StatelessWidget {
return Row(
children: [
Text(label, style: style),
if (icon != null)
Icon(icon, size: AppTextSize.label, color: style.color),
const SizedBox(width: 8),
_Stepper(
name: name,
@ -174,7 +180,13 @@ class _PauseRow extends StatelessWidget {
child: Row(
children: until == null
? [
Text('Pause for', style: style),
// Was "Pause for [N] days": a calendar for the day count,
// the pause glyph only on the button.
Icon(
Icons.calendar_today,
size: 18,
color: colorScheme.onSurfaceVariant,
),
const SizedBox(width: 8),
_Stepper(
name: 'Pause days',
@ -184,23 +196,37 @@ class _PauseRow extends StatelessWidget {
onChanged: onDaysChanged,
),
const SizedBox(width: 8),
Text('days', style: style),
const Spacer(),
TextButton(onPressed: onPause, child: const Text('Pause')),
TextButton(
onPressed: onPause,
child: const Icon(
Icons.pause,
size: 20,
semanticLabel: 'Pause',
),
),
]
: [
// textgate: was "Paused — back on 11 Oct".
Icon(
Icons.pause_circle_outline,
size: 18,
color: colorScheme.error,
semanticLabel: 'Paused',
),
const SizedBox(width: 8),
Text(
'Paused — back on ${formatShortDate(until)}',
style: style,
),
Icon(Icons.arrow_forward, size: 16, color: colorScheme.error),
const SizedBox(width: 4),
Text(formatShortDate(until), style: style),
const Spacer(),
TextButton(onPressed: onResume, child: const Text('Resume')),
TextButton(
onPressed: onResume,
child: const Icon(
Icons.play_arrow,
size: 20,
semanticLabel: 'Resume',
),
),
],
),
);

View File

@ -20,18 +20,22 @@ class _ModeChip extends StatelessWidget {
static const double width = 64;
String get _text => switch (state.mode) {
ProgressionMode.weight => 'kg',
ProgressionMode.reps => 'reps',
ProgressionMode.doubleProgression => '${state.repsLow}→${state.repsHigh}',
// textgate: was 'kg' / 'reps'. The same mode glyphs as the settings
// sheet's segmented control; double progression keeps its rep range.
IconData? get _modeIcon => switch (state.mode) {
ProgressionMode.weight => Icons.fitness_center,
ProgressionMode.reps => Icons.repeat,
ProgressionMode.doubleProgression => null,
};
@override
Widget build(BuildContext context) {
// Spoken only: excludeSemantics hides the painted children from it.
final semanticsLabel = '${state.name} progression settings';
return Semantics(
container: true,
button: true,
label: '${state.name} progression settings',
label: semanticsLabel,
excludeSemantics: true,
child: InkWell(
onTap: onTap,
@ -50,12 +54,17 @@ class _ModeChip extends StatelessWidget {
Icon(Icons.tune, size: 13, color: color),
const SizedBox(width: 3),
Flexible(
child: Text(
_text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: color, fontSize: AppTextSize.caption),
),
child: _modeIcon == null
? Text(
'${state.repsLow}→${state.repsHigh}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: color,
fontSize: AppTextSize.caption,
),
)
: Icon(_modeIcon, size: 14, color: color),
),
],
),
@ -202,16 +211,24 @@ class _PausedRow extends StatelessWidget {
height: ExerciseTile.setRowHeight,
child: Row(
children: [
Icon(Icons.pause_circle_outline, size: 20, color: color),
const SizedBox(width: 8),
Expanded(
child: Text(
'Paused — back on ${formatShortDate(until)} · counts as failed',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: color, fontSize: AppTextSize.label),
),
// textgate: was "Paused — back on 11 Oct · counts as failed".
// Now: pause glyph, the return date, and the failed-set cross.
Icon(
Icons.pause_circle_outline,
size: 20,
color: color,
semanticLabel: 'Paused — counts as failed',
),
const SizedBox(width: 8),
Icon(Icons.arrow_forward, size: 16, color: color),
const SizedBox(width: 4),
Text(
formatShortDate(until),
key: const Key('paused_until'),
style: TextStyle(color: color, fontSize: AppTextSize.label),
),
const SizedBox(width: 8),
Icon(Icons.close, size: 16, color: color),
],
),
);

Some files were not shown because too many files have changed in this diff Show More