mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-29 16:33:21 +01:00
Compare commits
No commits in common. "83a5c6b4bcc6d1724f9fc1d4ba2ec455923808e6" and "e08a520019a3ff0481cb578c06bf51b7e9637359" have entirely different histories.
83a5c6b4bc
...
e08a520019
@ -298,13 +298,6 @@ repos:
|
|||||||
files: '^screen_locker/.*\.py$'
|
files: '^screen_locker/.*\.py$'
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
require_serial: true
|
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
|
- id: flutter-analyze
|
||||||
name: flutter analyze (workout app)
|
name: flutter analyze (workout app)
|
||||||
# env -u GIT_DIR: git exports it to hooks, and flutter shells out to
|
# env -u GIT_DIR: git exports it to hooks, and flutter shells out to
|
||||||
|
|||||||
@ -0,0 +1,464 @@
|
|||||||
|
<!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 & 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<void> _tapReal(WidgetTester tester, Finder f) async {
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await tester.tap(f);
|
||||||
|
await Future<void>.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>
|
||||||
@ -0,0 +1,686 @@
|
|||||||
|
<!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 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 > 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># 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>
|
||||||
@ -0,0 +1,686 @@
|
|||||||
|
<!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 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 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 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 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 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 km now
|
||||||
|
passes too. The interactive demo and quiz below still use the old 5.0 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>
|
||||||
51
docs/explanations/index.html
Normal file
51
docs/explanations/index.html
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
<!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>
|
||||||
@ -34,12 +34,7 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
_logger: Final = logging.getLogger(__name__)
|
_logger: Final = logging.getLogger(__name__)
|
||||||
|
|
||||||
# textgate: glyphs + numbers (colour emoji are safe in the notification
|
TITLE: Final = "Workout credited \N{FLEXED BICEPS}"
|
||||||
# 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
|
_NOTIFY_TIMEOUT_SECONDS: Final = 5
|
||||||
_MINUTES_PER_HOUR: Final = 60.0
|
_MINUTES_PER_HOUR: Final = 60.0
|
||||||
|
|
||||||
@ -67,7 +62,7 @@ def credit_body(
|
|||||||
after: tuple[int, int, int] | None,
|
after: tuple[int, int, int] | None,
|
||||||
gaming_minutes: int | None,
|
gaming_minutes: int | None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""``⏻ 23:00 (+2h) · 🎮 7.0h`` -- whichever parts are known.
|
"""``Shutdown 23:00 (+2h) · gaming 7.0h`` -- whichever parts are known.
|
||||||
|
|
||||||
``before``/``after`` are the shutdown config around the credit; the delta
|
``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``.
|
is tonight's actual move, so a capped or rest-day credit shows ``+0h``.
|
||||||
@ -81,14 +76,14 @@ def credit_body(
|
|||||||
else:
|
else:
|
||||||
day = date.fromisoformat(today_str())
|
day = date.fromisoformat(today_str())
|
||||||
tonight = tonight_minutes(after, day)
|
tonight = tonight_minutes(after, day)
|
||||||
text = f"{_SHUTDOWN} {hhmm(tonight)}"
|
text = f"Shutdown {hhmm(tonight)}"
|
||||||
if before is not None:
|
if before is not None:
|
||||||
moved = max(0, tonight - tonight_minutes(before, day))
|
moved = max(0, tonight - tonight_minutes(before, day))
|
||||||
text += f" (+{span(moved)})"
|
text += f" (+{span(moved)})"
|
||||||
parts.append(text)
|
parts.append(text)
|
||||||
if gaming_minutes is not None:
|
if gaming_minutes is not None:
|
||||||
parts.append(f"{_GAMING} {gaming_minutes / _MINUTES_PER_HOUR:.1f}h")
|
parts.append(f"gaming {gaming_minutes / _MINUTES_PER_HOUR:.1f}h")
|
||||||
return " \N{MIDDLE DOT} ".join(parts) or "\N{CHECK MARK}"
|
return " \N{MIDDLE DOT} ".join(parts) or "Credit applied (details unavailable)"
|
||||||
|
|
||||||
|
|
||||||
def send_notification(title: str, body: str) -> bool:
|
def send_notification(title: str, body: str) -> bool:
|
||||||
|
|||||||
@ -1,98 +0,0 @@
|
|||||||
"""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)
|
|
||||||
@ -42,35 +42,39 @@ def build_heat_skip_content(
|
|||||||
outer = tk.Frame(parent, bg=_COLORS.palette.bg)
|
outer = tk.Frame(parent, bg=_COLORS.palette.bg)
|
||||||
outer.place(relx=0.5, rely=0.5, anchor="center")
|
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(
|
tk.Label(
|
||||||
outer,
|
outer,
|
||||||
text="\u25b2",
|
text="\u2600 Too hot to workout?",
|
||||||
font=_COLORS.font("display", bold=True, family=_FONT),
|
font=_COLORS.font("body", bold=True, family=_FONT),
|
||||||
bg=_COLORS.palette.bg,
|
bg=_COLORS.palette.bg,
|
||||||
fg=_COLORS.palette.warning,
|
fg=_COLORS.palette.warning,
|
||||||
).pack(pady=(0, _COLORS.space("sm")))
|
).pack(pady=(0, _COLORS.space("sm")))
|
||||||
|
|
||||||
tk.Label(
|
tk.Label(
|
||||||
outer,
|
outer,
|
||||||
# The city name was dropped too: the reading is what matters.
|
text=(
|
||||||
text=f"{temp:.0f}\u00b0C \u2265 {HEAT_SKIP_TEMP_THRESHOLD}\u00b0C",
|
f"{HEAT_SKIP_CITY}: {temp:.0f}\u00b0C"
|
||||||
|
f" (threshold: {HEAT_SKIP_TEMP_THRESHOLD}\u00b0C)"
|
||||||
|
),
|
||||||
font=_COLORS.font("body", family=_FONT),
|
font=_COLORS.font("body", family=_FONT),
|
||||||
bg=_COLORS.palette.bg,
|
bg=_COLORS.palette.bg,
|
||||||
fg=_COLORS.palette.warning,
|
fg=_COLORS.palette.muted,
|
||||||
).pack(pady=_COLORS.space("xs"))
|
).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 = tk.Frame(outer, bg=_COLORS.palette.bg)
|
||||||
btn_frame.pack(pady=_COLORS.space("lg"))
|
btn_frame.pack(pady=_COLORS.space("lg"))
|
||||||
|
|
||||||
# Was "Skip workout" (warning fill) / "No, I'll workout" (neutral fill).
|
|
||||||
skip_button = tk.Button(
|
skip_button = tk.Button(
|
||||||
btn_frame,
|
btn_frame,
|
||||||
name="skip",
|
text="Skip workout",
|
||||||
text="\u21b7",
|
|
||||||
command=on_skip,
|
command=on_skip,
|
||||||
bg=_COLORS.palette.warning,
|
bg=_COLORS.palette.warning,
|
||||||
fg=_COLORS.palette.on_fill,
|
fg=_COLORS.palette.on_fill,
|
||||||
@ -85,8 +89,7 @@ def build_heat_skip_content(
|
|||||||
|
|
||||||
decline_button = tk.Button(
|
decline_button = tk.Button(
|
||||||
btn_frame,
|
btn_frame,
|
||||||
name="decline",
|
text="No, I'll workout",
|
||||||
text="▶",
|
|
||||||
command=on_decline,
|
command=on_decline,
|
||||||
bg=_COLORS.palette.field_bg,
|
bg=_COLORS.palette.field_bg,
|
||||||
fg=_COLORS.palette.fg,
|
fg=_COLORS.palette.fg,
|
||||||
@ -127,7 +130,7 @@ class HeatSkipMixin:
|
|||||||
# Use the root itself (not a Toplevel) so we can go fullscreen.
|
# Use the root itself (not a Toplevel) so we can go fullscreen.
|
||||||
# This window is destroyed before the main GateRoot is created.
|
# This window is destroyed before the main GateRoot is created.
|
||||||
root = tk.Tk()
|
root = tk.Tk()
|
||||||
root.title("")
|
root.title("Extreme Heat")
|
||||||
root.configure(bg=_COLORS.palette.bg)
|
root.configure(bg=_COLORS.palette.bg)
|
||||||
root.attributes("-fullscreen", True)
|
root.attributes("-fullscreen", True)
|
||||||
root.attributes("-topmost", True)
|
root.attributes("-topmost", True)
|
||||||
|
|||||||
@ -32,7 +32,6 @@ from screen_locker._manual_workout_checks import (
|
|||||||
from screen_locker._manual_workout_types import (
|
from screen_locker._manual_workout_types import (
|
||||||
MANUAL_WORKOUT_TYPE,
|
MANUAL_WORKOUT_TYPE,
|
||||||
SPORT_CHOICES,
|
SPORT_CHOICES,
|
||||||
SPORT_GLYPHS,
|
|
||||||
SPORT_LABELS,
|
SPORT_LABELS,
|
||||||
SPORT_OTHER,
|
SPORT_OTHER,
|
||||||
SPORT_TABLE_TENNIS,
|
SPORT_TABLE_TENNIS,
|
||||||
@ -45,7 +44,6 @@ from screen_locker._manual_workout_types import (
|
|||||||
__all__ = [
|
__all__ = [
|
||||||
"MANUAL_WORKOUT_TYPE",
|
"MANUAL_WORKOUT_TYPE",
|
||||||
"SPORT_CHOICES",
|
"SPORT_CHOICES",
|
||||||
"SPORT_GLYPHS",
|
|
||||||
"SPORT_LABELS",
|
"SPORT_LABELS",
|
||||||
"SPORT_OTHER",
|
"SPORT_OTHER",
|
||||||
"SPORT_TABLE_TENNIS",
|
"SPORT_TABLE_TENNIS",
|
||||||
|
|||||||
@ -13,7 +13,6 @@ the form shows a "scheduled" screen that returns to the host's cancelled hook
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
@ -30,16 +29,6 @@ from screen_locker._ui_widgets import disable_paste
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from screen_locker._manual_workout import ManualWorkoutDraft
|
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:
|
class ManualWorkoutDateMixin:
|
||||||
"""Date row, budget gate and future-dated submission of the manual form."""
|
"""Date row, budget gate and future-dated submission of the manual form."""
|
||||||
@ -70,10 +59,9 @@ class ManualWorkoutDateMixin:
|
|||||||
)
|
)
|
||||||
entry.pack(side="right", padx=self._colors.space("xs"))
|
entry.pack(side="right", padx=self._colors.space("xs"))
|
||||||
disable_paste(entry)
|
disable_paste(entry)
|
||||||
# Was "Workout date (today to +7 days):" -- a day square + the range.
|
|
||||||
tk.Label(
|
tk.Label(
|
||||||
row,
|
row,
|
||||||
text="□ +0…+7",
|
text="Workout date (today to +7 days):",
|
||||||
font=self._colors.font("label"),
|
font=self._colors.font("label"),
|
||||||
fg=self._colors.palette.fg,
|
fg=self._colors.palette.fg,
|
||||||
bg=self._colors.palette.bg,
|
bg=self._colors.palette.bg,
|
||||||
@ -92,45 +80,37 @@ class ManualWorkoutDateMixin:
|
|||||||
if error is None and not future:
|
if error is None and not future:
|
||||||
error = budget_error(self.log_file, date)
|
error = budget_error(self.log_file, date)
|
||||||
if error is not None:
|
if error is not None:
|
||||||
self._mw_reject(error)
|
self._mw_error_label.config(text=error)
|
||||||
return True
|
return True
|
||||||
if not future:
|
if not future:
|
||||||
return False
|
return False
|
||||||
result = schedule_future_workout(self.log_file, draft, date)
|
result = schedule_future_workout(self.log_file, draft, date)
|
||||||
if not result.scheduled:
|
if not result.scheduled:
|
||||||
self._mw_reject(result.reason)
|
self._mw_error_label.config(text=result.reason)
|
||||||
return True
|
return True
|
||||||
_logger.info("Manual workout scheduled for %s: %s", date, result.reason)
|
self._show_manual_workout_scheduled(result.reason)
|
||||||
self._show_manual_workout_scheduled(date)
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def _mw_reject(self, reason: str) -> None:
|
def _show_manual_workout_scheduled(self, reason: str) -> None:
|
||||||
"""Show the form's fail mark; the reason goes to the log (textgate)."""
|
"""Confirm a future entry and go back; it does NOT unlock anything."""
|
||||||
_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()
|
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(
|
self._label(
|
||||||
SCHEDULED_GLYPH,
|
"✓ Workout Scheduled",
|
||||||
role="display",
|
role="display",
|
||||||
scale=1.3,
|
scale=1.3,
|
||||||
color=self._colors.palette.success,
|
color=self._colors.palette.success,
|
||||||
pad="lg",
|
pad="lg",
|
||||||
)
|
)
|
||||||
self._text(date, role="subtitle", color=self._colors.palette.success)
|
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,
|
||||||
|
)
|
||||||
row = self._button_row()
|
row = self._button_row()
|
||||||
self._button(
|
self._button(
|
||||||
row,
|
row,
|
||||||
BACK_GLYPH,
|
"OK",
|
||||||
bg=self._colors.palette.accent,
|
bg=self._colors.palette.accent,
|
||||||
command=self._on_manual_workout_cancelled,
|
command=self._on_manual_workout_cancelled,
|
||||||
width=12,
|
width=12,
|
||||||
|
|||||||
@ -23,24 +23,12 @@ from screen_locker import _manual_workout
|
|||||||
from screen_locker._constants import (
|
from screen_locker._constants import (
|
||||||
MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
|
MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
|
||||||
)
|
)
|
||||||
from screen_locker._manual_workout_date import (
|
from screen_locker._manual_workout_date import ManualWorkoutDateMixin
|
||||||
BACK_GLYPH,
|
|
||||||
REJECTED_GLYPH,
|
|
||||||
ManualWorkoutDateMixin,
|
|
||||||
)
|
|
||||||
from screen_locker._manual_workout_sport_fields import ManualWorkoutSportFieldsMixin
|
from screen_locker._manual_workout_sport_fields import ManualWorkoutSportFieldsMixin
|
||||||
from screen_locker._manual_workout_widgets import ManualWorkoutFormWidgetsMixin
|
from screen_locker._manual_workout_widgets import ManualWorkoutFormWidgetsMixin
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_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 = {
|
_SPORT_LABEL_TO_CODE = {
|
||||||
label: code for code, label in _manual_workout.SPORT_LABELS.items()
|
label: code for code, label in _manual_workout.SPORT_LABELS.items()
|
||||||
}
|
}
|
||||||
@ -56,11 +44,12 @@ class ManualWorkoutDialogMixin(
|
|||||||
def _show_manual_workout_form(self) -> None:
|
def _show_manual_workout_form(self) -> None:
|
||||||
"""Render the manual-workout evidence form, or a budget-exhausted note."""
|
"""Render the manual-workout evidence form, or a budget-exhausted note."""
|
||||||
self.clear_container()
|
self.clear_container()
|
||||||
# textgate: glyphs, colours second. Was "Log Manual Workout" heading /
|
self._label("Log Manual Workout", color=self._colors.palette.accent, pad="xs")
|
||||||
# "Manual-workout budget exhausted for this window." / "BACK".
|
|
||||||
self._label(FORM_GLYPH, color=self._colors.palette.accent, pad="xs")
|
|
||||||
if self._mw_budget_closed():
|
if self._mw_budget_closed():
|
||||||
self._label(EXHAUSTED_GLYPH, color=self._colors.palette.danger, pad="xs")
|
self._text(
|
||||||
|
"Manual-workout budget exhausted for this window.",
|
||||||
|
color=self._colors.palette.danger,
|
||||||
|
)
|
||||||
self._text(
|
self._text(
|
||||||
_manual_workout.budget_summary(self.log_file),
|
_manual_workout.budget_summary(self.log_file),
|
||||||
color=self._colors.palette.muted,
|
color=self._colors.palette.muted,
|
||||||
@ -68,7 +57,7 @@ class ManualWorkoutDialogMixin(
|
|||||||
row = self._button_row()
|
row = self._button_row()
|
||||||
self._button(
|
self._button(
|
||||||
row,
|
row,
|
||||||
BACK_GLYPH,
|
"BACK",
|
||||||
bg=self._colors.palette.field_bg,
|
bg=self._colors.palette.field_bg,
|
||||||
command=self._on_manual_workout_cancelled,
|
command=self._on_manual_workout_cancelled,
|
||||||
width=12,
|
width=12,
|
||||||
@ -98,23 +87,24 @@ class ManualWorkoutDialogMixin(
|
|||||||
self._mw_rpe_var = tk.IntVar(value=5)
|
self._mw_rpe_var = tk.IntVar(value=5)
|
||||||
self._mw_text_widgets: dict[str, tk.Text] = {}
|
self._mw_text_widgets: dict[str, tk.Text] = {}
|
||||||
|
|
||||||
# textgate: every prompt is a glyph; optional fields are in
|
self._mw_section(form, "Basics")
|
||||||
# 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_sport_row(form)
|
||||||
self._mw_vars["start_time"] = self._mw_entry(form, "◷▶", focus=True)
|
self._mw_vars["start_time"] = self._mw_entry(
|
||||||
self._mw_vars["end_time"] = self._mw_entry(form, "◷■")
|
form, "Start time (HH:MM):", focus=True
|
||||||
|
)
|
||||||
|
self._mw_vars["end_time"] = self._mw_entry(form, "End time (HH:MM):")
|
||||||
|
|
||||||
self._mw_section(form)
|
self._mw_section(form, "Location & logistics")
|
||||||
self._mw_vars["location_name"] = self._mw_entry(form, "⌖")
|
self._mw_vars["location_name"] = self._mw_entry(form, "Location name:")
|
||||||
self._mw_vars["transport_method"] = self._mw_entry(form, "⇄")
|
self._mw_vars["transport_method"] = self._mw_entry(
|
||||||
self._mw_vars["cost"] = self._mw_entry(form, "¤")
|
form, "How did you get there?"
|
||||||
self._mw_vars["reservation_phone"] = self._mw_entry(form, "(▯#)")
|
)
|
||||||
|
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_section(form, "Activity details")
|
||||||
# Both sport sub-frames occupy the same full-width grid slot; only the
|
# Both sport sub-frames occupy the same full-width grid slot; only the
|
||||||
# selected one is shown (see _on_mw_sport_changed).
|
# selected one is shown (see _on_mw_sport_changed).
|
||||||
act_row = self._mw_next_full_row(form)
|
act_row = self._mw_next_full_row(form)
|
||||||
@ -134,22 +124,33 @@ class ManualWorkoutDialogMixin(
|
|||||||
self._build_table_tennis_fields(self._mw_tt_frame)
|
self._build_table_tennis_fields(self._mw_tt_frame)
|
||||||
self._build_other_sport_fields(self._mw_other_frame)
|
self._build_other_sport_fields(self._mw_other_frame)
|
||||||
self._mw_rpe_row(form)
|
self._mw_rpe_row(form)
|
||||||
# Was "Techniques/focus areas practiced (optional):", "Warm-up
|
self._mw_vars["techniques_practiced"] = self._mw_entry(
|
||||||
# duration (optional):", "Pain or injury notes (optional, ...)".
|
form, "Techniques/focus areas practiced (optional):"
|
||||||
self._mw_vars["techniques_practiced"] = self._mw_entry(form, "(◎)")
|
)
|
||||||
self._mw_vars["warm_up_minutes"] = self._mw_entry(form, "(∿)")
|
self._mw_vars["warm_up_minutes"] = self._mw_entry(
|
||||||
self._mw_vars["pain_or_injury"] = self._mw_entry(form, "(↯)")
|
form, "Warm-up duration (optional):"
|
||||||
|
)
|
||||||
|
self._mw_vars["pain_or_injury"] = self._mw_entry(
|
||||||
|
form, "Pain or injury notes (optional, default none):"
|
||||||
|
)
|
||||||
self._on_mw_sport_changed(
|
self._on_mw_sport_changed(
|
||||||
_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
|
_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Was "Reflection", "What went well / What to improve / Overall
|
self._mw_section(form, "Reflection")
|
||||||
# feeling about the session (min N chars):".
|
self._mw_text_widgets["went_well"] = self._mw_textbox(
|
||||||
self._mw_section(form)
|
form,
|
||||||
least = f"≥{MANUAL_WORKOUT_REFLECTION_MIN_CHARS}"
|
f"What went well (min {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} 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["to_improve"] = self._mw_textbox(
|
||||||
self._mw_text_widgets["overall_feeling"] = self._mw_textbox(form, f"~ {least}")
|
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):",
|
||||||
|
)
|
||||||
|
|
||||||
self._mw_error_label = self._text(
|
self._mw_error_label = self._text(
|
||||||
"", role="label", color=self._colors.palette.danger, pad="xs"
|
"", role="label", color=self._colors.palette.danger, pad="xs"
|
||||||
@ -157,14 +158,14 @@ class ManualWorkoutDialogMixin(
|
|||||||
button_row = self._button_row()
|
button_row = self._button_row()
|
||||||
self._button(
|
self._button(
|
||||||
button_row,
|
button_row,
|
||||||
SUBMIT_GLYPH,
|
"SUBMIT",
|
||||||
bg=self._colors.palette.accent,
|
bg=self._colors.palette.accent,
|
||||||
command=self._submit_manual_workout_form,
|
command=self._submit_manual_workout_form,
|
||||||
width=12,
|
width=12,
|
||||||
).pack(side="left", padx=self._colors.space("sm"))
|
).pack(side="left", padx=self._colors.space("sm"))
|
||||||
self._button(
|
self._button(
|
||||||
button_row,
|
button_row,
|
||||||
BACK_GLYPH,
|
"BACK",
|
||||||
bg=self._colors.palette.field_bg,
|
bg=self._colors.palette.field_bg,
|
||||||
command=self._on_manual_workout_cancelled,
|
command=self._on_manual_workout_cancelled,
|
||||||
width=12,
|
width=12,
|
||||||
@ -211,9 +212,7 @@ class ManualWorkoutDialogMixin(
|
|||||||
)
|
)
|
||||||
error = _manual_workout.validate_manual_workout(draft)
|
error = _manual_workout.validate_manual_workout(draft)
|
||||||
if error is not None:
|
if error is not None:
|
||||||
# textgate: the reason is logged; the form shows the fail mark.
|
self._mw_error_label.config(text=error)
|
||||||
_logger.warning("Manual workout form rejected: %s", error)
|
|
||||||
self._mw_error_label.config(text=REJECTED_GLYPH)
|
|
||||||
return
|
return
|
||||||
if self._mw_handled_by_date(draft):
|
if self._mw_handled_by_date(draft):
|
||||||
return
|
return
|
||||||
|
|||||||
@ -49,11 +49,17 @@ class ManualWorkoutSportFieldsMixin:
|
|||||||
value=_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
|
value=_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
|
||||||
)
|
)
|
||||||
row = tk.Frame(parent, bg=self._colors.palette.bg)
|
row = tk.Frame(parent, bg=self._colors.palette.bg)
|
||||||
# textgate: the "Sport:" caption is gone; the radio row is the cue.
|
tk.Label(
|
||||||
for code, label in _manual_workout.SPORT_LABELS.items():
|
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():
|
||||||
tk.Radiobutton(
|
tk.Radiobutton(
|
||||||
row,
|
row,
|
||||||
text=_manual_workout.SPORT_GLYPHS[code],
|
text=label,
|
||||||
value=label,
|
value=label,
|
||||||
variable=self._mw_sport_var,
|
variable=self._mw_sport_var,
|
||||||
# Radiobutton's command takes no argument -- bind the label.
|
# Radiobutton's command takes no argument -- bind the label.
|
||||||
@ -91,25 +97,25 @@ class ManualWorkoutSportFieldsMixin:
|
|||||||
|
|
||||||
def _build_table_tennis_fields(self, parent: tk.Widget) -> None:
|
def _build_table_tennis_fields(self, parent: tk.Widget) -> None:
|
||||||
"""Build the table-tennis-specific score/equipment fields."""
|
"""Build the table-tennis-specific score/equipment fields."""
|
||||||
# textgate: was "Matches won/lost:", "Sets won/lost:", "Racket used:",
|
self._mw_int_vars["matches_won"] = self._mw_int_field(parent, "Matches won:")
|
||||||
# "Balls used:". Match / set glyph + win / loss mark.
|
self._mw_int_vars["matches_lost"] = self._mw_int_field(parent, "Matches lost:")
|
||||||
self._mw_int_vars["matches_won"] = self._mw_int_field(parent, "◍✓")
|
self._mw_int_vars["sets_won"] = self._mw_int_field(parent, "Sets won:")
|
||||||
self._mw_int_vars["matches_lost"] = self._mw_int_field(parent, "◍✗")
|
self._mw_int_vars["sets_lost"] = self._mw_int_field(parent, "Sets lost:")
|
||||||
self._mw_int_vars["sets_won"] = self._mw_int_field(parent, "▤✓")
|
self._mw_vars["racket"] = self._mw_entry(parent, "Racket used:")
|
||||||
self._mw_int_vars["sets_lost"] = self._mw_int_field(parent, "▤✗")
|
self._mw_vars["balls"] = self._mw_entry(parent, "Balls used:")
|
||||||
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:
|
def _build_other_sport_fields(self, parent: tk.Widget) -> None:
|
||||||
"""Build the generic "other sport" fields."""
|
"""Build the generic "other sport" fields."""
|
||||||
# Was "What sport/activity:" / "What was done (min N chars):" /
|
self._mw_vars["activity_type_other"] = self._mw_entry(
|
||||||
# "Equipment used (optional):"; optional fields are in parentheses.
|
parent, "What sport/activity:"
|
||||||
self._mw_vars["activity_type_other"] = self._mw_entry(parent, "✱")
|
)
|
||||||
self._mw_text_widgets["activity_details"] = self._mw_textbox(
|
self._mw_text_widgets["activity_details"] = self._mw_textbox(
|
||||||
parent,
|
parent,
|
||||||
f"✱≡ ≥{MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS}",
|
f"What was done (min {MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS} chars):",
|
||||||
|
)
|
||||||
|
self._mw_vars["equipment"] = self._mw_entry(
|
||||||
|
parent, "Equipment used (optional):"
|
||||||
)
|
)
|
||||||
self._mw_vars["equipment"] = self._mw_entry(parent, "(⊡)")
|
|
||||||
|
|
||||||
def _current_mw_sport(self) -> str:
|
def _current_mw_sport(self) -> str:
|
||||||
"""Return the internal sport code for the currently-selected label."""
|
"""Return the internal sport code for the currently-selected label."""
|
||||||
|
|||||||
@ -37,12 +37,6 @@ SPORT_LABELS: dict[str, str] = {
|
|||||||
SPORT_TABLE_TENNIS: "Table tennis",
|
SPORT_TABLE_TENNIS: "Table tennis",
|
||||||
SPORT_OTHER: "Other",
|
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:
|
def _today_iso() -> str:
|
||||||
@ -139,16 +133,12 @@ def budget_summary(
|
|||||||
*,
|
*,
|
||||||
today: str | None = None,
|
today: str | None = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""One-line UI summary of the manual-workout budget: glyph and numbers.
|
"""One-line UI summary string for the manual-workout budget."""
|
||||||
|
|
||||||
``≡ 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)
|
week = count_in_window(log_file, 7, today=today)
|
||||||
month = count_in_window(log_file, 30, today=today)
|
month = count_in_window(log_file, 30, today=today)
|
||||||
return (
|
return (
|
||||||
f"≡ {week}/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS} · "
|
f"Manual: {week}/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS}w · "
|
||||||
f"{month}/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}"
|
f"{month}/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}m"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -66,10 +66,17 @@ class ManualWorkoutFormWidgetsMixin:
|
|||||||
counters[id(parent)] = idx + 2
|
counters[id(parent)] = idx + 2
|
||||||
return idx // 2
|
return idx // 2
|
||||||
|
|
||||||
def _mw_section(self, parent: tk.Widget) -> None:
|
def _mw_section(self, parent: tk.Widget, title: str) -> None:
|
||||||
"""Add a full-width rule between form sections (was a heading)."""
|
"""Add a full-width section heading inside the form."""
|
||||||
rule = tk.Frame(parent, bg=self._colors.palette.accent, height=2)
|
label = tk.Label(
|
||||||
self._mw_grid(parent, rule, full=True)
|
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_entry(
|
def _mw_entry(
|
||||||
self, parent: tk.Widget, label: str, *, focus: bool = False
|
self, parent: tk.Widget, label: str, *, focus: bool = False
|
||||||
@ -183,8 +190,10 @@ class ManualWorkoutFormWidgetsMixin:
|
|||||||
row = tk.Frame(parent, bg=self._colors.palette.bg)
|
row = tk.Frame(parent, bg=self._colors.palette.bg)
|
||||||
tk.Label(
|
tk.Label(
|
||||||
row,
|
row,
|
||||||
# Was "RPE — perceived exertion (1-10):": effort bars + range.
|
text=(
|
||||||
text=f"▁▃▅▇ {MANUAL_WORKOUT_RPE_MIN}-{MANUAL_WORKOUT_RPE_MAX}",
|
f"RPE — perceived exertion "
|
||||||
|
f"({MANUAL_WORKOUT_RPE_MIN}-{MANUAL_WORKOUT_RPE_MAX}):"
|
||||||
|
),
|
||||||
font=self._colors.font("label"),
|
font=self._colors.font("label"),
|
||||||
fg=self._colors.palette.fg,
|
fg=self._colors.palette.fg,
|
||||||
bg=self._colors.palette.bg,
|
bg=self._colors.palette.bg,
|
||||||
|
|||||||
@ -6,19 +6,14 @@ mixins, so the class's public surface is unchanged.
|
|||||||
|
|
||||||
Every method here is display-only: it reads the snapshot it is handed and
|
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.
|
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 __future__ import annotations
|
||||||
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._earned import hhmm
|
from screen_locker._earned import hhmm
|
||||||
from screen_locker._sync_status import gather_sync_status
|
from screen_locker._sync_status import format_sync_line, gather_sync_status
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
@ -35,46 +30,56 @@ if TYPE_CHECKING:
|
|||||||
class StatusSectionsMixin:
|
class StatusSectionsMixin:
|
||||||
"""Renders each section of the status window from a snapshot."""
|
"""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:
|
def _section_today(self, parent: tk.Widget, day: DayStatus) -> None:
|
||||||
"""Render today's outcome (was "✓ Today (Wed Nov 11): phone_verified")."""
|
"""Render today's outcome."""
|
||||||
del parent
|
del parent
|
||||||
mark = g.OK if day.counted else (g.SICK if day.is_sick_day else g.FAIL)
|
mark = "✓" if day.counted else ("😷" if day.is_sick_day else "—")
|
||||||
self._label(
|
entry_str = ", ".join(day.entry_types) or (
|
||||||
f"{mark} {self._day_cell(day)}",
|
"sick day" if day.is_sick_day else "no entry yet"
|
||||||
role="title",
|
)
|
||||||
|
self._text(
|
||||||
|
f"{mark} Today ({day.label}): {entry_str}",
|
||||||
|
role="body",
|
||||||
color=self._colors.palette.success
|
color=self._colors.palette.success
|
||||||
if day.counted
|
if day.counted
|
||||||
else self._colors.palette.warning,
|
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:
|
def _section_week(self, parent: tk.Widget, week: WeeklySummary) -> None:
|
||||||
"""Render this ISO week: dots + count, then one cell per day.
|
"""Render this ISO week's per-day breakdown and totals."""
|
||||||
|
|
||||||
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
|
del parent
|
||||||
enough = week.remaining <= 0
|
self._label(
|
||||||
self._text(
|
f"This Week: {week.counted_count}/{week.minimum}", role="body", pad="sm"
|
||||||
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(
|
def _section_streak(
|
||||||
self, parent: tk.Widget, streak: int, week_rewards: tuple[str, ...] = ()
|
self, parent: tk.Widget, streak: int, week_rewards: tuple[str, ...] = ()
|
||||||
@ -82,23 +87,29 @@ class StatusSectionsMixin:
|
|||||||
"""Render the consecutive 5+-workout-week streak and this week's reward.
|
"""Render the consecutive 5+-workout-week streak and this week's reward.
|
||||||
|
|
||||||
Display only, and exactly the stored values (``extra_benefits_state``):
|
Display only, and exactly the stored values (``extra_benefits_state``):
|
||||||
a streak of 0 is shown as 0, never padded or rounded up. Nothing here
|
a streak of 0 is said plainly, never padded or rounded up. Nothing here
|
||||||
grants time or relaxes a lock. Was "🔥 N-week streak (5+ workouts a
|
grants time or relaxes a lock. The early-bird extension is not shown:
|
||||||
week)" / "No streak yet: ..." and the reward sentences.
|
it no longer changes anything (wake-alarm owns early bird).
|
||||||
"""
|
"""
|
||||||
del parent
|
del parent
|
||||||
self._text(
|
self._label("Workout streak", role="body", pad="sm")
|
||||||
f"{g.STREAK * min(streak, 10)} {streak}" if streak else f"{g.STREAK} 0",
|
if streak > 0:
|
||||||
role="body",
|
self._text(
|
||||||
color=self._colors.palette.success
|
f"🔥 {streak}-week streak (5+ workouts a week)",
|
||||||
if streak
|
role="body",
|
||||||
else self._colors.palette.muted,
|
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,
|
||||||
|
)
|
||||||
for message in week_rewards:
|
for message in week_rewards:
|
||||||
# A reset is news, not a celebration: it must not be painted green.
|
# A reset is news, not a celebration: it must not be painted green.
|
||||||
lost = message.startswith("Streak reset")
|
lost = message.startswith("Streak reset")
|
||||||
self._text(
|
self._text(
|
||||||
f"{g.STREAK}{g.FAIL}" if lost else f"{g.STREAK}{g.GIFT}",
|
message,
|
||||||
role="body",
|
role="body",
|
||||||
color=self._colors.palette.warning
|
color=self._colors.palette.warning
|
||||||
if lost
|
if lost
|
||||||
@ -108,30 +119,32 @@ class StatusSectionsMixin:
|
|||||||
def _section_lock_explanation(
|
def _section_lock_explanation(
|
||||||
self, parent: tk.Widget, expl: LockExplanation
|
self, parent: tk.Widget, expl: LockExplanation
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Render whether the lock fired today and the stage that decided it.
|
"""Render why the lock did/didn't fire today, plus its evaluation trace."""
|
||||||
|
|
||||||
Was "Why the lock did/didn't fire" over the stage's sentence.
|
|
||||||
"""
|
|
||||||
del parent
|
del parent
|
||||||
square = g.LOCK if expl.fired else g.UNLOCK
|
self._label("Why the lock did/didn't fire", role="body", pad="sm")
|
||||||
self._text(
|
self._text(
|
||||||
f"{square} {g.STAGE_GLYPH.get(expl.stage, '')}".rstrip(),
|
expl.reason,
|
||||||
role="title",
|
role="body",
|
||||||
color=self._colors.palette.danger
|
color=self._colors.palette.danger
|
||||||
if expl.fired
|
if expl.fired
|
||||||
else self._colors.palette.success,
|
else self._colors.palette.success,
|
||||||
)
|
)
|
||||||
if expl.auto_upgrade.would_attempt:
|
if expl.auto_upgrade.would_attempt:
|
||||||
self._text(g.RETRY, role="label", color=self._colors.palette.warning)
|
self._text(
|
||||||
|
f"Pending auto-upgrade: {expl.auto_upgrade.reason}",
|
||||||
|
role="label",
|
||||||
|
color=self._colors.palette.warning,
|
||||||
|
)
|
||||||
|
|
||||||
def _section_manual_workout_budget(
|
def _section_manual_workout_budget(
|
||||||
self, parent: tk.Widget, manual: ManualWorkoutBudgetStatus
|
self, parent: tk.Widget, manual: ManualWorkoutBudgetStatus
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Render rolling manual-workout budget usage (7-day, then 30-day)."""
|
"""Render rolling manual-workout budget usage."""
|
||||||
del parent
|
del parent
|
||||||
|
self._label("Manual Workout Budget", role="body", pad="sm")
|
||||||
self._text(
|
self._text(
|
||||||
f"{g.FORM} {manual.used_7d}/{manual.budget_7d} · "
|
f"{manual.used_7d}/{manual.budget_7d} week · "
|
||||||
f"{manual.used_30d}/{manual.budget_30d}",
|
f"{manual.used_30d}/{manual.budget_30d} month",
|
||||||
role="body",
|
role="body",
|
||||||
color=self._colors.palette.danger
|
color=self._colors.palette.danger
|
||||||
if manual.exhausted
|
if manual.exhausted
|
||||||
@ -139,7 +152,7 @@ class StatusSectionsMixin:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def _section_sync_backend(self, parent: tk.Widget) -> None:
|
def _section_sync_backend(self, parent: tk.Widget) -> None:
|
||||||
"""Render whether this machine's sync is healthy, and its peer count.
|
"""Render which backend this machine syncs through.
|
||||||
|
|
||||||
Read from local state only (see :mod:`screen_locker._sync_status`), so
|
Read from local state only (see :mod:`screen_locker._sync_status`), so
|
||||||
opening or refreshing the window never makes a network call. Coloured
|
opening or refreshing the window never makes a network call. Coloured
|
||||||
@ -149,8 +162,9 @@ class StatusSectionsMixin:
|
|||||||
"""
|
"""
|
||||||
del parent
|
del parent
|
||||||
status = gather_sync_status()
|
status = gather_sync_status()
|
||||||
|
self._label("Sync backend", role="body", pad="sm")
|
||||||
self._text(
|
self._text(
|
||||||
f"{g.SYNC} {g.OK if status.healthy else g.FAIL} {status.peer_count}",
|
format_sync_line(status),
|
||||||
role="body",
|
role="body",
|
||||||
color=self._colors.palette.muted
|
color=self._colors.palette.muted
|
||||||
if status.healthy
|
if status.healthy
|
||||||
@ -160,25 +174,41 @@ class StatusSectionsMixin:
|
|||||||
def _section_shutdown(
|
def _section_shutdown(
|
||||||
self, parent: tk.Widget, shutdown: ShutdownProjection
|
self, parent: tk.Widget, shutdown: ShutdownProjection
|
||||||
) -> None:
|
) -> 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
|
del parent
|
||||||
|
self._label("Shutdown Time", role="body", pad="sm")
|
||||||
if shutdown.tonight is not None:
|
if shutdown.tonight is not None:
|
||||||
mon_wed, thu_sun, _morning = shutdown.tonight
|
mon_wed, thu_sun, _morning = shutdown.tonight
|
||||||
self._text(f"{g.SHUTDOWN} {hhmm(mon_wed)} · {hhmm(thu_sun)}", role="title")
|
self._text(
|
||||||
|
f"Live config — Mon-Wed {hhmm(mon_wed)}, Thu-Sun {hhmm(thu_sun)}",
|
||||||
|
role="body",
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
self._text(
|
self._text(
|
||||||
f"{g.SHUTDOWN} {g.FAIL}",
|
"Live shutdown config unavailable.",
|
||||||
role="title",
|
role="body",
|
||||||
color=self._colors.palette.warning,
|
color=self._colors.palette.warning,
|
||||||
)
|
)
|
||||||
for days in (shutdown.rest_of_week, shutdown.next_week_preview):
|
# Rest-of-week/next-week/explanation are speculative annotations, not
|
||||||
self._text(
|
# the section's primary content -- a deliberate caption-sized
|
||||||
" ".join(hhmm(d.minutes) for d in days),
|
# exception to the 16px floor, all sharing one muted tone instead of
|
||||||
role="caption",
|
# three unrelated ad hoc grays.
|
||||||
color=self._colors.palette.muted,
|
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
|
||||||
|
)
|
||||||
|
|||||||
@ -11,12 +11,10 @@ from __future__ import annotations
|
|||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import date
|
from datetime import date
|
||||||
import logging
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
import earned_time
|
import earned_time
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._day import today_str
|
from screen_locker._day import today_str
|
||||||
from screen_locker._earned import extra_minutes, span
|
from screen_locker._earned import extra_minutes, span
|
||||||
from screen_locker._status_data import gather_status
|
from screen_locker._status_data import gather_status
|
||||||
@ -31,9 +29,6 @@ if TYPE_CHECKING:
|
|||||||
from screen_locker._workout_credit import WorkoutCreditResult
|
from screen_locker._workout_credit import WorkoutCreditResult
|
||||||
|
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class PhoneCheckOutcome:
|
class PhoneCheckOutcome:
|
||||||
"""Result of the "Check Phone" button's verify-then-backfill chain.
|
"""Result of the "Check Phone" button's verify-then-backfill chain.
|
||||||
@ -78,9 +73,7 @@ def _backfill_week_and_apply_bonus(verifier: ScreenLocker) -> str | None:
|
|||||||
workout above the weekly minimum); it is a separate source with its own
|
workout above the weekly minimum); it is a separate source with its own
|
||||||
dedup and is out of scope for the RunnerUp credit fix.
|
dedup and is out of scope for the RunnerUp credit fix.
|
||||||
|
|
||||||
Returns a glyph summary if anything was filled, else ``None``:
|
Returns a human-readable 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)
|
prev_count = count_weekly_workouts(verifier.log_file)
|
||||||
filled = verifier._scan_and_fill_week_runnerup(
|
filled = verifier._scan_and_fill_week_runnerup(
|
||||||
@ -100,9 +93,10 @@ def _backfill_week_and_apply_bonus(verifier: ScreenLocker) -> str | None:
|
|||||||
filled += sl_filled
|
filled += sl_filled
|
||||||
if not filled:
|
if not filled:
|
||||||
return None
|
return None
|
||||||
message = f"{g.RETRY}{g.LIFT} +{filled}"
|
plural = "workout" if filled == 1 else "workouts"
|
||||||
|
message = f"Auto-filled {filled} {plural} from earlier this week."
|
||||||
if bonus > 0:
|
if bonus > 0:
|
||||||
message += f" {g.SHUTDOWN} +{span(bonus)}"
|
message += f" +{span(bonus)} shutdown time."
|
||||||
return message
|
return message
|
||||||
|
|
||||||
|
|
||||||
@ -190,8 +184,10 @@ class PhoneCheckMixin:
|
|||||||
if outcome.credited_type == "runnerup_verified"
|
if outcome.credited_type == "runnerup_verified"
|
||||||
else outcome.phone_message
|
else outcome.phone_message
|
||||||
)
|
)
|
||||||
source_glyph = (
|
source_label = (
|
||||||
g.RUN if outcome.credited_type == "runnerup_verified" else g.LIFT
|
"RunnerUp"
|
||||||
|
if outcome.credited_type == "runnerup_verified"
|
||||||
|
else "StrongLifts"
|
||||||
)
|
)
|
||||||
verifier = self.verifier_factory(self.log_file)
|
verifier = self.verifier_factory(self.log_file)
|
||||||
verifier.workout_data = {
|
verifier.workout_data = {
|
||||||
@ -200,27 +196,24 @@ class PhoneCheckMixin:
|
|||||||
}
|
}
|
||||||
credit = verifier._apply_workout_credit()
|
credit = verifier._apply_workout_credit()
|
||||||
self._credit_message = "\n".join(
|
self._credit_message = "\n".join(
|
||||||
self._credit_result_lines(f"{source_glyph} {g.OK}", credit)
|
self._credit_result_lines(f"{source_label} verified: {message}", credit)
|
||||||
)
|
)
|
||||||
elif outcome.week_fill_message is not None:
|
elif outcome.week_fill_message is not None:
|
||||||
self._credit_message = outcome.week_fill_message
|
self._credit_message = outcome.week_fill_message
|
||||||
else:
|
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 = (
|
self._phone_check_result = (
|
||||||
outcome.status,
|
outcome.status,
|
||||||
f"{g.LIFT}{g.FAIL} {g.RUN}{g.FAIL}",
|
(
|
||||||
|
f"StrongLifts: {outcome.phone_message} · "
|
||||||
|
f"RunnerUp: {outcome.runnerup_message}"
|
||||||
|
),
|
||||||
)
|
)
|
||||||
self.render(gather_status())
|
self.render(gather_status())
|
||||||
|
|
||||||
def _credit_result_lines(
|
def _credit_result_lines(
|
||||||
self, header: str, credit: WorkoutCreditResult
|
self, header: str, credit: WorkoutCreditResult
|
||||||
) -> list[str]:
|
) -> list[str]:
|
||||||
"""Glyph outcome lines for an applied workout credit (no words).
|
"""Human-readable outcome lines for an applied workout credit.
|
||||||
|
|
||||||
Shared by the "Check Phone" verify path and the "Log Manual Workout"
|
Shared by the "Check Phone" verify path and the "Log Manual Workout"
|
||||||
path so both report the reward identically: the base +2h shutdown push
|
path so both report the reward identically: the base +2h shutdown push
|
||||||
@ -230,11 +223,12 @@ class PhoneCheckMixin:
|
|||||||
"""
|
"""
|
||||||
lines = [header]
|
lines = [header]
|
||||||
if credit.already_counted_today:
|
if credit.already_counted_today:
|
||||||
# Was "(Already recorded today — no additional credit.)".
|
lines.append("(Already recorded today — no additional credit.)")
|
||||||
lines.append(f"{g.OK}{g.OK} {g.GIFT}0")
|
|
||||||
return lines
|
return lines
|
||||||
if credit.shutdown_adjusted:
|
if credit.shutdown_adjusted:
|
||||||
lines.append(f"{g.SHUTDOWN} {g.GIFT}{span(120)}")
|
lines.append("Shutdown time +2h later!")
|
||||||
if credit.extra_bonus_delta > 0:
|
if credit.extra_bonus_delta > 0:
|
||||||
lines.append(f"{g.LIFT} {g.GIFT}{span(credit.extra_bonus_delta)}")
|
lines.append(
|
||||||
|
f"Extra workout today! +{span(credit.extra_bonus_delta)} tonight"
|
||||||
|
)
|
||||||
return lines
|
return lines
|
||||||
|
|||||||
@ -15,10 +15,8 @@ writes to ``log.json``. Host class must provide:
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import TYPE_CHECKING
|
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._constants import HEAT_SKIP_CITY, HEAT_SKIP_TEMP_THRESHOLD
|
||||||
from screen_locker._temperature import HARD_TIMEOUT_SECONDS, submit_background
|
from screen_locker._temperature import HARD_TIMEOUT_SECONDS, submit_background
|
||||||
|
|
||||||
@ -27,45 +25,54 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
from screen_locker._temperature import TemperatureCheck
|
from screen_locker._temperature import TemperatureCheck
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class TemperatureStatusMixin:
|
class TemperatureStatusMixin:
|
||||||
"""Provides the background Warsaw-temperature fetch/poll/render."""
|
"""Provides the background Warsaw-temperature fetch/poll/render."""
|
||||||
|
|
||||||
def _section_temperature(self, parent: tk.Widget) -> None:
|
def _section_temperature(self, parent: tk.Widget) -> None:
|
||||||
"""Render the live temperature against the heat-skip threshold.
|
"""Render the live Warsaw temperature.
|
||||||
|
|
||||||
The same reading the real locker's heat-skip check would see,
|
The same reading the real locker's heat-skip check would see,
|
||||||
fetched in the background. textgate: was "Warsaw Temperature" and a
|
fetched in the background.
|
||||||
sentence per state; now ``▲`` with the reading (or wait / clock-fail /
|
|
||||||
fail glyphs), danger-coloured with ``↷`` when it would heat-skip.
|
|
||||||
"""
|
"""
|
||||||
del parent
|
del parent
|
||||||
|
self._label("Warsaw Temperature", role="body", pad="sm")
|
||||||
result = self._temp_result
|
result = self._temp_result
|
||||||
palette = self._colors.palette
|
|
||||||
if result is None:
|
if result is None:
|
||||||
self._text(f"{g.HEAT} {g.WAIT}", role="body", color=palette.muted)
|
self._text(
|
||||||
|
"Checking Warsaw temperature…",
|
||||||
|
role="caption",
|
||||||
|
color=self._colors.palette.muted,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
if result.timed_out:
|
if result.timed_out:
|
||||||
_logger.warning(
|
|
||||||
"Temperature check timed out after ~%ds", int(HARD_TIMEOUT_SECONDS)
|
|
||||||
)
|
|
||||||
self._text(
|
self._text(
|
||||||
f"{g.HEAT} {g.CLOCK}{g.FAIL}", role="body", color=palette.warning
|
f"Warsaw temperature check timed out after ~"
|
||||||
|
f"{int(HARD_TIMEOUT_SECONDS)}s — network may be down.",
|
||||||
|
role="caption",
|
||||||
|
color=self._colors.palette.warning,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
if result.temp_celsius is None:
|
if result.temp_celsius is None:
|
||||||
self._text(f"{g.HEAT} {g.FAIL}", role="body", color=palette.warning)
|
self._text(
|
||||||
|
"Warsaw temperature check failed (network/API error).",
|
||||||
|
role="caption",
|
||||||
|
color=self._colors.palette.warning,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
hot = result.temp_celsius >= HEAT_SKIP_TEMP_THRESHOLD
|
hot = result.temp_celsius >= HEAT_SKIP_TEMP_THRESHOLD
|
||||||
relation = "≥" if hot else "<"
|
|
||||||
self._text(
|
self._text(
|
||||||
f"{g.HEAT} {result.temp_celsius:.0f}°C {relation} "
|
f"Warsaw: {result.temp_celsius:.0f}°C (heat-skip threshold "
|
||||||
f"{HEAT_SKIP_TEMP_THRESHOLD}°C" + (f" {g.SKIP}" if hot else ""),
|
f"{HEAT_SKIP_TEMP_THRESHOLD}°C)",
|
||||||
role="body",
|
role="caption",
|
||||||
color=palette.danger if hot else palette.muted,
|
color=self._colors.palette.warning if hot else self._colors.palette.muted,
|
||||||
)
|
)
|
||||||
|
if hot:
|
||||||
|
self._text(
|
||||||
|
"Would trigger heat-skip today.",
|
||||||
|
role="caption",
|
||||||
|
color=self._colors.palette.danger,
|
||||||
|
)
|
||||||
|
|
||||||
def _start_temperature_check(self) -> None:
|
def _start_temperature_check(self) -> None:
|
||||||
"""Submit a background Warsaw-temperature fetch and start polling it.
|
"""Submit a background Warsaw-temperature fetch and start polling it.
|
||||||
|
|||||||
@ -1,18 +1,10 @@
|
|||||||
"""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 __future__ import annotations
|
||||||
|
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
import logging
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker import _manual_workout
|
from screen_locker import _manual_workout
|
||||||
from screen_locker._source_health import collect_source_findings, explain_findings
|
from screen_locker._source_health import collect_source_findings, explain_findings
|
||||||
from screen_locker._ui_flows_lockout import LockoutFlowMixin
|
from screen_locker._ui_flows_lockout import LockoutFlowMixin
|
||||||
@ -22,8 +14,6 @@ from screen_locker._ui_flows_sick_panel import SickPanelFlowMixin
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
|
class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
|
||||||
"""Mixin providing UI flow logic for the screen locker.
|
"""Mixin providing UI flow logic for the screen locker.
|
||||||
@ -38,16 +28,15 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
|
|||||||
Split from :meth:`_start_phone_check` so the fit check
|
Split from :meth:`_start_phone_check` so the fit check
|
||||||
(``scripts/verify_screen_fits.py``) can measure this screen without
|
(``scripts/verify_screen_fits.py``) can measure this screen without
|
||||||
starting a background thread that talks to a phone over adb.
|
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.clear_container()
|
||||||
self._label(
|
self._label(
|
||||||
f"{g.PHONE} {g.LIFT}",
|
"Checking phone...",
|
||||||
role="display",
|
role="display",
|
||||||
color=self._colors.palette.warning,
|
color=self._colors.palette.warning,
|
||||||
pad="lg",
|
pad="lg",
|
||||||
)
|
)
|
||||||
self._text(g.WAIT, role="display", color=self._colors.palette.muted)
|
self._text("Looking for today's workout in StrongLifts...", role="body")
|
||||||
|
|
||||||
def _start_phone_check(self) -> None:
|
def _start_phone_check(self) -> None:
|
||||||
"""Check phone for today's workout immediately at startup."""
|
"""Check phone for today's workout immediately at startup."""
|
||||||
@ -65,39 +54,23 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
|
|||||||
else:
|
else:
|
||||||
self.root.after(500, self._poll_phone_check)
|
self.root.after(500, self._poll_phone_check)
|
||||||
|
|
||||||
def _show_retry_and_sick(self, message: str, *, status: str = "") -> None:
|
def _show_retry_and_sick(self, message: str) -> None:
|
||||||
"""Show retry, I'm sick and (budget allowing) the manual log.
|
"""Show TRY AGAIN, 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.clear_container()
|
||||||
self._label(
|
self._label(
|
||||||
f"{g.LIFT} {g.FAIL}",
|
"No Workout Found",
|
||||||
role="display",
|
role="display",
|
||||||
color=self._colors.palette.danger,
|
color=self._colors.palette.danger,
|
||||||
pad="md",
|
pad="md",
|
||||||
)
|
)
|
||||||
if status:
|
self._text(message, color=self._colors.palette.warning)
|
||||||
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
|
# 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
|
# not see. On 2026-08-24 this screen said "No Workout Found" after a
|
||||||
# 1h57m session, because Firebase was unreadable and the GitHub mirror
|
# 1h57m session, because Firebase was unreadable and the GitHub mirror
|
||||||
# had been stale for nine days -- neither of which was shown here.
|
# had been stale for nine days -- neither of which was shown here.
|
||||||
# Now a sync-fault glyph, one per finding; the prose is logged.
|
diagnosis = explain_findings(collect_source_findings())
|
||||||
findings = collect_source_findings()
|
if diagnosis:
|
||||||
if findings:
|
self._text(diagnosis, color=self._colors.palette.muted)
|
||||||
_logger.warning("%s", explain_findings(findings))
|
|
||||||
self._text(
|
|
||||||
f"{g.SYNC}{g.FAIL} " * len(findings),
|
|
||||||
role="title",
|
|
||||||
color=self._colors.palette.warning,
|
|
||||||
)
|
|
||||||
self._text(
|
self._text(
|
||||||
_manual_workout.budget_summary(self.log_file),
|
_manual_workout.budget_summary(self.log_file),
|
||||||
color=self._colors.palette.muted,
|
color=self._colors.palette.muted,
|
||||||
@ -105,47 +78,44 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
|
|||||||
frame = self._button_row()
|
frame = self._button_row()
|
||||||
self._button(
|
self._button(
|
||||||
frame,
|
frame,
|
||||||
g.RETRY,
|
"TRY AGAIN",
|
||||||
bg=self._colors.palette.accent,
|
bg=self._colors.palette.accent,
|
||||||
command=self._start_phone_check,
|
command=self._start_phone_check,
|
||||||
width=4,
|
width=12,
|
||||||
).pack(side="left", padx=self._colors.space("sm"))
|
).pack(side="left", padx=self._colors.space("sm"))
|
||||||
self._sick_button(frame)
|
self._sick_button(frame)
|
||||||
if self._mw_budget_closed():
|
if self._mw_budget_closed():
|
||||||
# Was "Manual-workout budget exhausted. No manual-log option".
|
self._text(
|
||||||
self._text(f"{g.FORM} {g.CLOSE}", color=self._colors.palette.danger)
|
"Manual-workout budget exhausted. No manual-log option available.",
|
||||||
|
color=self._colors.palette.danger,
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
self._button(
|
self._button(
|
||||||
frame,
|
frame,
|
||||||
g.FORM,
|
"Log Manual Workout",
|
||||||
bg=self._colors.palette.accent,
|
bg=self._colors.palette.accent,
|
||||||
command=self._show_manual_workout_form,
|
command=self._show_manual_workout_form,
|
||||||
width=4,
|
width=16,
|
||||||
).pack(side="left", padx=self._colors.space("sm"))
|
).pack(side="left", padx=self._colors.space("sm"))
|
||||||
|
|
||||||
def _paint_accepted(self, glyph: str) -> None:
|
def _on_manual_workout_saved(self, entry: dict) -> None:
|
||||||
"""Paint "accepted, unlocking" and schedule the unlock.
|
"""Show confirmation and unlock after a manual-workout entry is built."""
|
||||||
|
self.workout_data = entry
|
||||||
Was "✓ Workout Verified!" / "✓ Run Verified!" / "✓ Manual Workout
|
|
||||||
Logged!" over the source line and "Unlocking...".
|
|
||||||
"""
|
|
||||||
self.clear_container()
|
self.clear_container()
|
||||||
self._label(
|
self._label(
|
||||||
f"{glyph} {g.OK}",
|
"✓ Manual Workout Logged!",
|
||||||
role="display",
|
role="display",
|
||||||
scale=1.3,
|
scale=1.3,
|
||||||
color=self._colors.palette.success,
|
color=self._colors.palette.success,
|
||||||
pad="lg",
|
pad="lg",
|
||||||
)
|
)
|
||||||
self._text(g.WAIT, role="display", color=self._colors.palette.muted)
|
self._text(
|
||||||
|
entry.get("source", ""), 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
|
unlock_delay = 1500 if self.demo_mode else 2000
|
||||||
self.root.after(unlock_delay, self.unlock_screen)
|
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:
|
def _on_manual_workout_cancelled(self) -> None:
|
||||||
"""Return to the retry screen when the manual-workout form is cancelled."""
|
"""Return to the retry screen when the manual-workout form is cancelled."""
|
||||||
self._start_phone_check()
|
self._start_phone_check()
|
||||||
@ -155,13 +125,39 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
|
|||||||
if status == "verified":
|
if status == "verified":
|
||||||
self.workout_data["type"] = "phone_verified"
|
self.workout_data["type"] = "phone_verified"
|
||||||
self.workout_data["source"] = message
|
self.workout_data["source"] = message
|
||||||
self._paint_accepted(g.LIFT)
|
self.clear_container()
|
||||||
elif status in ("too_short", "clock_tampered"):
|
self._label(
|
||||||
self._show_retry_and_sick(message, status=status)
|
"✓ 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.",
|
||||||
|
)
|
||||||
elif status in ("stale", "no_exercises", "not_verified"):
|
elif status in ("stale", "no_exercises", "not_verified"):
|
||||||
# Try RunnerUp before showing failure — user may have run instead of lifted.
|
# Try RunnerUp before showing failure — user may have run instead of lifted.
|
||||||
self._start_runnerup_fallback(
|
self._start_runnerup_fallback(
|
||||||
lambda: self._show_retry_and_sick(message, status=status)
|
lambda: self._show_retry_and_sick(
|
||||||
|
f"❌ {message}\n\n"
|
||||||
|
"Neither StrongLifts nor RunnerUp found a workout today.\n"
|
||||||
|
"Go do your workout first!",
|
||||||
|
)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# no_phone or error — try RunnerUp first, then penalty timer.
|
# no_phone or error — try RunnerUp first, then penalty timer.
|
||||||
@ -172,16 +168,15 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
|
|||||||
|
|
||||||
Shows a waiting screen, runs the check in a background thread, then
|
Shows a waiting screen, runs the check in a background thread, then
|
||||||
either unlocks (run verified) or calls ``on_failure``.
|
either unlocks (run verified) or calls ``on_failure``.
|
||||||
Was "Checking RunnerUp..." / "Looking for today's run in RunnerUp".
|
|
||||||
"""
|
"""
|
||||||
self.clear_container()
|
self.clear_container()
|
||||||
self._label(
|
self._label(
|
||||||
f"{g.PHONE} {g.RUN}",
|
"Checking RunnerUp...",
|
||||||
role="display",
|
role="display",
|
||||||
color=self._colors.palette.warning,
|
color=self._colors.palette.warning,
|
||||||
pad="lg",
|
pad="lg",
|
||||||
)
|
)
|
||||||
self._text(g.WAIT, role="display", color=self._colors.palette.muted)
|
self._text("Looking for today's run in RunnerUp...", role="body")
|
||||||
executor = ThreadPoolExecutor(max_workers=1)
|
executor = ThreadPoolExecutor(max_workers=1)
|
||||||
self._runnerup_future = executor.submit(self._verify_runnerup_workout)
|
self._runnerup_future = executor.submit(self._verify_runnerup_workout)
|
||||||
executor.shutdown(wait=False)
|
executor.shutdown(wait=False)
|
||||||
@ -195,7 +190,20 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
|
|||||||
if status == "verified":
|
if status == "verified":
|
||||||
self.workout_data["type"] = "runnerup_verified"
|
self.workout_data["type"] = "runnerup_verified"
|
||||||
self.workout_data["source"] = message
|
self.workout_data["source"] = message
|
||||||
self._paint_accepted(g.RUN)
|
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)
|
||||||
else:
|
else:
|
||||||
self._runnerup_on_failure()
|
self._runnerup_on_failure()
|
||||||
else:
|
else:
|
||||||
|
|||||||
@ -7,10 +7,8 @@ Split out of :mod:`screen_locker._ui_flows` to keep every file under the
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._constants import (
|
from screen_locker._constants import (
|
||||||
NO_PHONE_EXTRA_LOCKOUT_SECONDS,
|
NO_PHONE_EXTRA_LOCKOUT_SECONDS,
|
||||||
PHONE_PENALTY_DELAY_DEMO,
|
PHONE_PENALTY_DELAY_DEMO,
|
||||||
@ -20,8 +18,6 @@ from screen_locker._constants import (
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class LockoutFlowMixin:
|
class LockoutFlowMixin:
|
||||||
"""Lockout countdown and the no-phone penalty timer."""
|
"""Lockout countdown and the no-phone penalty timer."""
|
||||||
@ -31,14 +27,10 @@ class LockoutFlowMixin:
|
|||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
def lockout(self) -> None:
|
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.clear_container()
|
||||||
self.lockout_label = self._label(
|
self.lockout_label = self._label(
|
||||||
g.LIFT,
|
f"Go work out!\nLocked for {self.lockout_time} seconds",
|
||||||
role="display",
|
role="display",
|
||||||
scale=1.5,
|
scale=1.5,
|
||||||
color=self._colors.palette.danger,
|
color=self._colors.palette.danger,
|
||||||
@ -69,13 +61,7 @@ class LockoutFlowMixin:
|
|||||||
def _show_phone_penalty(
|
def _show_phone_penalty(
|
||||||
self, message: str, *, on_done: Callable[[], None] | None = None
|
self, message: str, *, on_done: Callable[[], None] | 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.clear_container()
|
||||||
self._phone_penalty_done_fn: Callable[[], None] = (
|
self._phone_penalty_done_fn: Callable[[], None] = (
|
||||||
on_done
|
on_done
|
||||||
@ -94,11 +80,18 @@ class LockoutFlowMixin:
|
|||||||
else base_delay + NO_PHONE_EXTRA_LOCKOUT_SECONDS
|
else base_delay + NO_PHONE_EXTRA_LOCKOUT_SECONDS
|
||||||
)
|
)
|
||||||
self._label(
|
self._label(
|
||||||
f"{g.PHONE}{g.FAIL}",
|
"Cannot Verify Workout",
|
||||||
role="display",
|
role="display",
|
||||||
color=self._colors.palette.warning,
|
color=self._colors.palette.warning,
|
||||||
pad="md",
|
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_remaining = delay
|
||||||
self.phone_penalty_label = self._label(
|
self.phone_penalty_label = self._label(
|
||||||
str(delay),
|
str(delay),
|
||||||
|
|||||||
@ -1,23 +1,15 @@
|
|||||||
"""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 __future__ import annotations
|
||||||
|
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
import logging
|
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._weekly_check import (
|
from screen_locker._weekly_check import (
|
||||||
RELAXED_DAY_SKIP_TYPE,
|
RELAXED_DAY_SKIP_TYPE,
|
||||||
WEEKLY_WORKOUT_MINIMUM,
|
WEEKLY_WORKOUT_MINIMUM,
|
||||||
count_weekly_workouts,
|
count_weekly_workouts,
|
||||||
)
|
)
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class UIFlowsRelaxedMixin:
|
class UIFlowsRelaxedMixin:
|
||||||
"""Mixin providing the relaxed-day UI flow logic."""
|
"""Mixin providing the relaxed-day UI flow logic."""
|
||||||
@ -31,39 +23,36 @@ class UIFlowsRelaxedMixin:
|
|||||||
|
|
||||||
The screen is not locked — the user can skip freely or voluntarily
|
The screen is not locked — the user can skip freely or voluntarily
|
||||||
import a Stronglift workout that counts toward the weekly minimum.
|
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)
|
count = count_weekly_workouts(self.log_file)
|
||||||
self.clear_container()
|
self.clear_container()
|
||||||
self._label(
|
self._label(
|
||||||
g.OPTIONAL,
|
"Optional Day (Tue / Wed / Thu)",
|
||||||
role="display",
|
role="title",
|
||||||
color=self._colors.palette.warning,
|
color=self._colors.palette.warning,
|
||||||
pad="md",
|
pad="md",
|
||||||
)
|
)
|
||||||
self._text(
|
self._text(
|
||||||
g.dots(count, WEEKLY_WORKOUT_MINIMUM),
|
f"Weekly workouts: {count} / {WEEKLY_WORKOUT_MINIMUM}\n"
|
||||||
role="title",
|
"No penalty for skipping today.",
|
||||||
|
role="subtitle",
|
||||||
color=self._colors.palette.muted,
|
color=self._colors.palette.muted,
|
||||||
pad="sm",
|
pad="sm",
|
||||||
)
|
)
|
||||||
frame = self._button_row()
|
frame = self._button_row()
|
||||||
self._button(
|
self._button(
|
||||||
frame,
|
frame,
|
||||||
g.SKIP,
|
"Skip — No Penalty",
|
||||||
bg=self._colors.palette.success,
|
bg=self._colors.palette.success,
|
||||||
command=self._skip_relaxed_day,
|
command=self._skip_relaxed_day,
|
||||||
width=4,
|
width=18,
|
||||||
).pack(side="left", padx=self._colors.space("sm"))
|
).pack(side="left", padx=self._colors.space("sm"))
|
||||||
self._button(
|
self._button(
|
||||||
frame,
|
frame,
|
||||||
f"{g.GO} {g.LIFT}",
|
"Log Stronglift Workout",
|
||||||
bg=self._colors.palette.accent,
|
bg=self._colors.palette.accent,
|
||||||
command=self._start_relaxed_phone_check,
|
command=self._start_relaxed_phone_check,
|
||||||
width=8,
|
width=20,
|
||||||
).pack(side="left", padx=self._colors.space("sm"))
|
).pack(side="left", padx=self._colors.space("sm"))
|
||||||
# Skipping is free here, but a sick day is more than a skip: it
|
# 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.
|
# stands every gate down and lifts tonight's shutdown to 20:00.
|
||||||
@ -85,12 +74,12 @@ class UIFlowsRelaxedMixin:
|
|||||||
"""Run Stronglift check in relaxed mode (no screen grab)."""
|
"""Run Stronglift check in relaxed mode (no screen grab)."""
|
||||||
self.clear_container()
|
self.clear_container()
|
||||||
self._label(
|
self._label(
|
||||||
f"{g.PHONE} {g.LIFT}",
|
"Checking phone...",
|
||||||
role="display",
|
role="display",
|
||||||
color=self._colors.palette.warning,
|
color=self._colors.palette.warning,
|
||||||
pad="lg",
|
pad="lg",
|
||||||
)
|
)
|
||||||
self._text(g.WAIT, role="display", color=self._colors.palette.muted)
|
self._text("Looking for today's workout in StrongLifts...", role="body")
|
||||||
executor = ThreadPoolExecutor(max_workers=1)
|
executor = ThreadPoolExecutor(max_workers=1)
|
||||||
self._phone_future = executor.submit(self._verify_phone_workout)
|
self._phone_future = executor.submit(self._verify_phone_workout)
|
||||||
executor.shutdown(wait=False)
|
executor.shutdown(wait=False)
|
||||||
@ -119,34 +108,30 @@ class UIFlowsRelaxedMixin:
|
|||||||
self._show_relaxed_retry(message, status)
|
self._show_relaxed_retry(message, status)
|
||||||
|
|
||||||
def _show_relaxed_retry(self, message: str, status: str) -> None:
|
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.clear_container()
|
||||||
self._label(
|
self._label(
|
||||||
f"{g.LIFT} {g.FAIL}",
|
"No Workout Found",
|
||||||
role="display",
|
role="display",
|
||||||
color=self._colors.palette.danger,
|
color=self._colors.palette.danger,
|
||||||
pad="md",
|
pad="md",
|
||||||
)
|
)
|
||||||
self._text(
|
self._text(
|
||||||
g.status_glyph(status), role="display", color=self._colors.palette.warning
|
f"❌ {message}\n\nReason: {status}", color=self._colors.palette.warning
|
||||||
)
|
)
|
||||||
frame = self._button_row()
|
frame = self._button_row()
|
||||||
self._button(
|
self._button(
|
||||||
frame,
|
frame,
|
||||||
g.RETRY,
|
"TRY AGAIN",
|
||||||
bg=self._colors.palette.accent,
|
bg=self._colors.palette.accent,
|
||||||
command=self._start_relaxed_phone_check,
|
command=self._start_relaxed_phone_check,
|
||||||
width=4,
|
width=12,
|
||||||
).pack(side="left", padx=self._colors.space("sm"))
|
).pack(side="left", padx=self._colors.space("sm"))
|
||||||
self._sick_button(frame)
|
self._sick_button(frame)
|
||||||
self._button(
|
self._button(
|
||||||
frame,
|
frame,
|
||||||
g.SKIP,
|
"Close (Skip)",
|
||||||
bg=self._colors.palette.success,
|
bg=self._colors.palette.success,
|
||||||
command=self.close,
|
command=self.close,
|
||||||
width=4,
|
width=14,
|
||||||
).pack(side="left", padx=self._colors.space("sm"))
|
).pack(side="left", padx=self._colors.space("sm"))
|
||||||
|
|||||||
@ -23,10 +23,8 @@ Split out of :mod:`screen_locker._ui_flows` to keep every file under the
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._constants import SHUTDOWN_BASE_FILE
|
from screen_locker._constants import SHUTDOWN_BASE_FILE
|
||||||
from screen_locker._credit_slot import locked_shutdown_state
|
from screen_locker._credit_slot import locked_shutdown_state
|
||||||
from screen_locker._sick import mark_today_sick, push_in_background
|
from screen_locker._sick import mark_today_sick, push_in_background
|
||||||
@ -34,20 +32,18 @@ from screen_locker._sick import mark_today_sick, push_in_background
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class SickDayFlowMixin:
|
class SickDayFlowMixin:
|
||||||
"""The one-tap sick-day button and what follows it."""
|
"""The one-tap sick-day button and what follows it."""
|
||||||
|
|
||||||
def _sick_button(self, frame: tk.Widget) -> None:
|
def _sick_button(self, frame: tk.Widget) -> None:
|
||||||
"""Pack the sick-day button (was "I'm sick") into ``frame``."""
|
"""Pack the "I'm sick" button into ``frame``."""
|
||||||
self._button(
|
self._button(
|
||||||
frame,
|
frame,
|
||||||
g.SICK,
|
"I'm sick",
|
||||||
bg=self._colors.palette.warning,
|
bg=self._colors.palette.warning,
|
||||||
command=self.mark_sick_and_unlock,
|
command=self.mark_sick_and_unlock,
|
||||||
width=4,
|
width=12,
|
||||||
).pack(side="left", padx=self._colors.space("sm"))
|
).pack(side="left", padx=self._colors.space("sm"))
|
||||||
# The keep-aware alternative (``_ui_flows_sick_panel``), next to it.
|
# The keep-aware alternative (``_ui_flows_sick_panel``), next to it.
|
||||||
self._choose_lockers_link(frame)
|
self._choose_lockers_link(frame)
|
||||||
@ -82,19 +78,15 @@ class SickDayFlowMixin:
|
|||||||
self.close()
|
self.close()
|
||||||
|
|
||||||
def _show_sick_refused(self, message: str) -> None:
|
def _show_sick_refused(self, message: str) -> None:
|
||||||
"""Show that today could not be marked sick; the lock stays up.
|
"""Say why 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.clear_container()
|
||||||
self._label(
|
self._label(
|
||||||
f"{g.SICK} {g.FAIL}",
|
"Could not mark today as sick",
|
||||||
role="display",
|
role="display",
|
||||||
color=self._colors.palette.danger,
|
color=self._colors.palette.danger,
|
||||||
pad="md",
|
pad="md",
|
||||||
)
|
)
|
||||||
|
self._text(message, color=self._colors.palette.warning)
|
||||||
frame = self._button_row()
|
frame = self._button_row()
|
||||||
back = (
|
back = (
|
||||||
self._start_relaxed_day_flow
|
self._start_relaxed_day_flow
|
||||||
@ -103,8 +95,8 @@ class SickDayFlowMixin:
|
|||||||
)
|
)
|
||||||
self._button(
|
self._button(
|
||||||
frame,
|
frame,
|
||||||
g.BACK,
|
"Back",
|
||||||
bg=self._colors.palette.accent,
|
bg=self._colors.palette.accent,
|
||||||
command=back,
|
command=back,
|
||||||
width=4,
|
width=12,
|
||||||
).pack(side="left", padx=self._colors.space("sm"))
|
).pack(side="left", padx=self._colors.space("sm"))
|
||||||
|
|||||||
@ -29,7 +29,6 @@ from gatelock import bind_activate
|
|||||||
import sickdays
|
import sickdays
|
||||||
from sickdays.gui import KeepPanel
|
from sickdays.gui import KeepPanel
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._sick import stands_down_workout
|
from screen_locker._sick import stands_down_workout
|
||||||
from screen_locker._surface_group import FrameGroup
|
from screen_locker._surface_group import FrameGroup
|
||||||
|
|
||||||
@ -40,10 +39,8 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# textgate: was "choose lockers…" (sick, then pick) and "Workout lock kept —
|
LINK_TEXT = "choose lockers…"
|
||||||
# finish the workout to unlock." (sick, but the barbell lock stays).
|
KEPT_NOTE = "Workout lock kept — finish the workout to unlock."
|
||||||
LINK_TEXT = f"{g.SICK}▾"
|
|
||||||
KEPT_NOTE = f"{g.SICK} {g.LIFT} {g.LOCK}"
|
|
||||||
|
|
||||||
|
|
||||||
def build_sick_panel(
|
def build_sick_panel(
|
||||||
@ -165,10 +162,10 @@ class SickPanelFlowMixin:
|
|||||||
).pack(pady=self._colors.space("md"))
|
).pack(pady=self._colors.space("md"))
|
||||||
back = self._button(
|
back = self._button(
|
||||||
box,
|
box,
|
||||||
g.BACK,
|
"Back",
|
||||||
bg=self._colors.palette.accent,
|
bg=self._colors.palette.accent,
|
||||||
command=self._close_sick_panel,
|
command=self._close_sick_panel,
|
||||||
width=4,
|
width=12,
|
||||||
)
|
)
|
||||||
back.pack(pady=self._colors.space("sm"))
|
back.pack(pady=self._colors.space("sm"))
|
||||||
back.first.focus_set()
|
back.first.focus_set()
|
||||||
|
|||||||
@ -3,16 +3,10 @@
|
|||||||
Split out of ``screen_lock`` so that module stays inside the repo's 400-line
|
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
|
cap; this is pure view code (paint the credit, then close), which is exactly
|
||||||
the kind of thing the other ``_ui_*`` mixins already own.
|
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 __future__ import annotations
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._constants import EXTRA_BENEFITS_FILE
|
from screen_locker._constants import EXTRA_BENEFITS_FILE
|
||||||
from screen_locker._earned import span
|
from screen_locker._earned import span
|
||||||
from screen_locker._extra_benefits import current_streak
|
from screen_locker._extra_benefits import current_streak
|
||||||
@ -24,12 +18,12 @@ class UnlockViewMixin:
|
|||||||
"""Paints the unlock screen, then closes it."""
|
"""Paints the unlock screen, then closes it."""
|
||||||
|
|
||||||
def unlock_screen(self) -> None:
|
def unlock_screen(self) -> None:
|
||||||
"""Apply workout credit and display the success glyphs."""
|
"""Apply workout credit and display the success message."""
|
||||||
credit = self._apply_workout_credit()
|
credit = self._apply_workout_credit()
|
||||||
|
|
||||||
self.clear_container()
|
self.clear_container()
|
||||||
self._label(
|
self._label(
|
||||||
f"{g.UNLOCK} {g.OK}",
|
"Great job! 💪",
|
||||||
role="display",
|
role="display",
|
||||||
scale=1.5,
|
scale=1.5,
|
||||||
color=self._colors.palette.success,
|
color=self._colors.palette.success,
|
||||||
@ -37,21 +31,22 @@ class UnlockViewMixin:
|
|||||||
)
|
)
|
||||||
if credit.shutdown_adjusted:
|
if credit.shutdown_adjusted:
|
||||||
self._text(
|
self._text(
|
||||||
f"{g.SHUTDOWN} {g.GIFT}{span(120)}",
|
"Shutdown time +2h later! 🎁",
|
||||||
role="title",
|
role="title",
|
||||||
color=self._colors.palette.warning,
|
color=self._colors.palette.warning,
|
||||||
)
|
)
|
||||||
if credit.extra_bonus_delta > 0:
|
if credit.extra_bonus_delta > 0:
|
||||||
self._text(
|
self._text(
|
||||||
f"{g.LIFT} {g.GIFT}{span(credit.extra_bonus_delta)}",
|
f"Extra workout today! +{span(credit.extra_bonus_delta)} tonight",
|
||||||
role="subtitle",
|
role="subtitle",
|
||||||
color=self._colors.palette.warning,
|
color=self._colors.palette.warning,
|
||||||
)
|
)
|
||||||
streak = current_streak(EXTRA_BENEFITS_FILE)
|
streak = current_streak(EXTRA_BENEFITS_FILE)
|
||||||
if streak >= 1:
|
if streak >= 1:
|
||||||
self._text(
|
self._text(
|
||||||
f"{g.STREAK * min(streak, 10)} {streak}",
|
f"🔥 {streak}-week streak (5+ workouts each)",
|
||||||
role="label",
|
role="label",
|
||||||
color=self._colors.palette.muted,
|
color=self._colors.palette.muted,
|
||||||
)
|
)
|
||||||
|
self._text("Screen Unlocked!", role="display", pad="md")
|
||||||
self.root.after(_UNLOCK_DELAY_MS, self.close)
|
self.root.after(_UNLOCK_DELAY_MS, self.close)
|
||||||
|
|||||||
@ -201,10 +201,9 @@ class WindowSetupMixin:
|
|||||||
|
|
||||||
def _setup_demo_close_button(self) -> None:
|
def _setup_demo_close_button(self) -> None:
|
||||||
"""Add close button for demo mode."""
|
"""Add close button for demo mode."""
|
||||||
# Was "✕ Close Demo": the cross on the danger fill says it alone.
|
|
||||||
close_btn = tk.Button(
|
close_btn = tk.Button(
|
||||||
self.root,
|
self.root,
|
||||||
text="✕",
|
text="✕ Close Demo",
|
||||||
font=self._colors.font("caption"),
|
font=self._colors.font("caption"),
|
||||||
bg=self._colors.palette.danger,
|
bg=self._colors.palette.danger,
|
||||||
fg=self._colors.palette.on_fill,
|
fg=self._colors.palette.on_fill,
|
||||||
|
|||||||
@ -168,9 +168,7 @@ class ScreenLocker(
|
|||||||
self._instance_lock.release()
|
self._instance_lock.release()
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
self.root.on_callback_error = self.on_callback_error
|
self.root.on_callback_error = self.on_callback_error
|
||||||
# textgate: the window is fullscreen, so its title is never painted;
|
self.root.title("Workout Locker" + (" [DEMO MODE]" if demo_mode else ""))
|
||||||
# was "Workout Locker" (+ " [DEMO MODE]"). Nothing matches on it.
|
|
||||||
self.root.title("")
|
|
||||||
self.demo_mode = demo_mode
|
self.demo_mode = demo_mode
|
||||||
self.lockout_time = 10 if demo_mode else 1800
|
self.lockout_time = 10 if demo_mode else 1800
|
||||||
self._lock: LockWindow | None = None
|
self._lock: LockWindow | None = None
|
||||||
|
|||||||
@ -30,7 +30,6 @@ from typing import TYPE_CHECKING
|
|||||||
|
|
||||||
from gatelock import LockConfig
|
from gatelock import LockConfig
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
|
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
|
||||||
from screen_locker._status_data import (
|
from screen_locker._status_data import (
|
||||||
StatusSnapshot,
|
StatusSnapshot,
|
||||||
@ -113,7 +112,7 @@ class StatusWindow(
|
|||||||
"""Redraw the whole window from *snapshot*."""
|
"""Redraw the whole window from *snapshot*."""
|
||||||
self._last_snapshot = snapshot
|
self._last_snapshot = snapshot
|
||||||
self.clear_container()
|
self.clear_container()
|
||||||
# textgate: the "Workout Status" heading is gone; see the sections.
|
self._label("Workout Status", role="title", pad="md")
|
||||||
self._section_today(self.container, snapshot.today)
|
self._section_today(self.container, snapshot.today)
|
||||||
self._section_week(self.container, snapshot.week)
|
self._section_week(self.container, snapshot.week)
|
||||||
self._section_streak(self.container, snapshot.streak, snapshot.week_rewards)
|
self._section_streak(self.container, snapshot.streak, snapshot.week_rewards)
|
||||||
@ -131,29 +130,44 @@ class StatusWindow(
|
|||||||
if status == "verified"
|
if status == "verified"
|
||||||
else self._colors.palette.warning
|
else self._colors.palette.warning
|
||||||
)
|
)
|
||||||
self._text(message, role="title", color=color)
|
self._text(f"Phone check ({status}): {message}", role="body", color=color)
|
||||||
if self._credit_message is not None:
|
if self._credit_message is not None:
|
||||||
self._text(
|
self._text(
|
||||||
self._credit_message, role="body", color=self._colors.palette.success
|
self._credit_message, role="body", color=self._colors.palette.success
|
||||||
)
|
)
|
||||||
# Check phone / manual log are the primary write actions (accent,
|
# "Check Phone"/"Log Manual Workout" are the primary write actions
|
||||||
# high contrast per rule 3); refresh / close are secondary utility
|
# (accent, high contrast per rule 3); "Refresh"/"Close" are secondary
|
||||||
# actions (muted) -- two tiers instead of four arbitrary hues. Was
|
# utility actions (muted) -- two tiers instead of four arbitrary hues.
|
||||||
# "Check Phone" / "Log Manual Workout" / "Refresh" / "Close".
|
|
||||||
frame = self._button_row()
|
frame = self._button_row()
|
||||||
buttons = [(g.PHONE, self._colors.palette.accent, self._on_check_phone_clicked)]
|
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"))
|
||||||
if not self._mw_budget_closed():
|
if not self._mw_budget_closed():
|
||||||
buttons.append(
|
self._button(
|
||||||
(g.FORM, self._colors.palette.accent, self._show_manual_workout_form)
|
frame,
|
||||||
)
|
"Log Manual Workout",
|
||||||
buttons += [
|
bg=self._colors.palette.accent,
|
||||||
(g.RETRY, self._colors.palette.field_bg, self._on_refresh_clicked),
|
command=self._show_manual_workout_form,
|
||||||
(g.CLOSE, self._colors.palette.field_bg, self.root.destroy),
|
width=16,
|
||||||
]
|
).pack(side="left", padx=self._colors.space("sm"))
|
||||||
for glyph, bg, command in buttons:
|
self._button(
|
||||||
self._button(frame, glyph, bg=bg, command=command, width=4).pack(
|
frame,
|
||||||
side="left", padx=self._colors.space("sm")
|
"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"))
|
||||||
|
|
||||||
def _on_refresh_clicked(self) -> None:
|
def _on_refresh_clicked(self) -> None:
|
||||||
"""Clear any stale phone-check/credit/temperature results, re-check both."""
|
"""Clear any stale phone-check/credit/temperature results, re-check both."""
|
||||||
@ -178,7 +192,9 @@ class StatusWindow(
|
|||||||
verifier.workout_data = entry
|
verifier.workout_data = entry
|
||||||
credit = verifier._apply_workout_credit()
|
credit = verifier._apply_workout_credit()
|
||||||
self._credit_message = "\n".join(
|
self._credit_message = "\n".join(
|
||||||
self._credit_result_lines(f"{g.FORM} {g.OK}", credit)
|
self._credit_result_lines(
|
||||||
|
f"Manual workout logged: {entry.get('source', '')}", credit
|
||||||
|
)
|
||||||
)
|
)
|
||||||
self.render(gather_status())
|
self.render(gather_status())
|
||||||
|
|
||||||
@ -205,7 +221,7 @@ def main(argv: list[str] | None = None) -> None:
|
|||||||
return
|
return
|
||||||
|
|
||||||
root = tk.Tk()
|
root = tk.Tk()
|
||||||
root.title("")
|
root.title("Workout Status")
|
||||||
root.configure(bg=_STATUS_COLORS.palette.bg)
|
root.configure(bg=_STATUS_COLORS.palette.bg)
|
||||||
root.minsize(560, 200)
|
root.minsize(560, 200)
|
||||||
|
|
||||||
|
|||||||
@ -37,7 +37,7 @@ def setup_unlock(
|
|||||||
if seed_today_type is None:
|
if seed_today_type is None:
|
||||||
log_file.write_text("{}")
|
log_file.write_text("{}")
|
||||||
else:
|
else:
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
log_file.write_text(
|
log_file.write_text(
|
||||||
json.dumps(
|
json.dumps(
|
||||||
{
|
{
|
||||||
|
|||||||
@ -199,8 +199,7 @@ def _isolate_shutdown_base(tmp_path: Path) -> Iterator[None]:
|
|||||||
refresh sees an empty unit dir, never the real one.
|
refresh sees an empty unit dir, never the real one.
|
||||||
"""
|
"""
|
||||||
target = tmp_path / "shutdown_base.json"
|
target = tmp_path / "shutdown_base.json"
|
||||||
# Local day, as the code compares it (_day.today_str), not the UTC one.
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
|
||||||
target.write_text(json.dumps(dict.fromkeys(["last_reset_date", *_BONUS], today)))
|
target.write_text(json.dumps(dict.fromkeys(["last_reset_date", *_BONUS], today)))
|
||||||
with (
|
with (
|
||||||
patch("screen_locker._constants.SHUTDOWN_BASE_FILE", target),
|
patch("screen_locker._constants.SHUTDOWN_BASE_FILE", target),
|
||||||
|
|||||||
@ -22,7 +22,7 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
|
|
||||||
def _today() -> str:
|
def _today() -> str:
|
||||||
return datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
return datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
|
||||||
class TestIsScheduledSkipToday:
|
class TestIsScheduledSkipToday:
|
||||||
|
|||||||
@ -19,7 +19,7 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
|
|
||||||
def _today() -> str:
|
def _today() -> str:
|
||||||
return datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
return datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
|
||||||
class TestExplainLockDecision:
|
class TestExplainLockDecision:
|
||||||
|
|||||||
@ -18,10 +18,6 @@ import pytest
|
|||||||
from screen_locker import _credit_notify
|
from screen_locker import _credit_notify
|
||||||
from screen_locker.tests.conftest import create_locker
|
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:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@ -68,30 +64,28 @@ class TestCreditBody:
|
|||||||
def test_full_body(self) -> None:
|
def test_full_body(self) -> None:
|
||||||
"""Shutdown time, tonight's move and the gaming budget."""
|
"""Shutdown time, tonight's move and the gaming budget."""
|
||||||
body = _credit_notify.credit_body((0, 1200, 0), (0, 1320, 0), 420)
|
body = _credit_notify.credit_body((0, 1200, 0), (0, 1320, 0), 420)
|
||||||
assert body == f"{_SHUTDOWN} 22:00 (+2h) \N{MIDDLE DOT} {_GAMING} 7.0h"
|
assert body == "Shutdown 22:00 (+2h) \N{MIDDLE DOT} gaming 7.0h"
|
||||||
|
|
||||||
def test_a_capped_credit_shows_plus_zero(self) -> None:
|
def test_a_capped_credit_shows_plus_zero(self) -> None:
|
||||||
"""No backwards move is ever shown: the delta floors at zero."""
|
"""No backwards move is ever shown: the delta floors at zero."""
|
||||||
body = _credit_notify.credit_body((0, 1380, 0), (0, 1320, 0), None)
|
body = _credit_notify.credit_body((0, 1380, 0), (0, 1320, 0), None)
|
||||||
assert body == f"{_SHUTDOWN} 22:00 (+0h)"
|
assert body == "Shutdown 22:00 (+0h)"
|
||||||
|
|
||||||
def test_unknown_before_drops_the_delta(self) -> None:
|
def test_unknown_before_drops_the_delta(self) -> None:
|
||||||
"""Without the old config there is no move to show."""
|
"""Without the old config there is no move to show."""
|
||||||
assert (
|
assert _credit_notify.credit_body(None, (0, 1320, 0), None) == "Shutdown 22:00"
|
||||||
_credit_notify.credit_body(None, (0, 1320, 0), None) == f"{_SHUTDOWN} 22:00"
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_unreadable_after_warns_and_shows_gaming_only(
|
def test_unreadable_after_warns_and_shows_gaming_only(
|
||||||
self, caplog: pytest.LogCaptureFixture
|
self, caplog: pytest.LogCaptureFixture
|
||||||
) -> None:
|
) -> None:
|
||||||
"""An unreadable config is said out loud, not silently omitted."""
|
"""An unreadable config is said out loud, not silently omitted."""
|
||||||
assert _credit_notify.credit_body(None, None, 90) == f"{_GAMING} 1.5h"
|
assert _credit_notify.credit_body(None, None, 90) == "gaming 1.5h"
|
||||||
assert _warned(caplog, "unreadable")
|
assert _warned(caplog, "unreadable")
|
||||||
|
|
||||||
def test_nothing_known_still_says_something(self) -> None:
|
def test_nothing_known_still_says_something(self) -> None:
|
||||||
"""An empty body would read as a glitch; say the credit happened."""
|
"""An empty body would read as a glitch; say the credit happened."""
|
||||||
body = _credit_notify.credit_body(None, None, None)
|
body = _credit_notify.credit_body(None, None, None)
|
||||||
assert body == "\N{CHECK MARK}"
|
assert body == "Credit applied (details unavailable)"
|
||||||
|
|
||||||
|
|
||||||
class TestSendNotification:
|
class TestSendNotification:
|
||||||
@ -157,7 +151,7 @@ def test_notify_workout_credit_sends_the_composed_body() -> None:
|
|||||||
):
|
):
|
||||||
assert _real_notify((0, 1200, 0), (0, 1260, 0), None)
|
assert _real_notify((0, 1200, 0), (0, 1260, 0), None)
|
||||||
send.assert_called_once_with(
|
send.assert_called_once_with(
|
||||||
_credit_notify.TITLE, f"{_SHUTDOWN} 21:00 (+1h) \N{MIDDLE DOT} {_GAMING} 1.0h"
|
_credit_notify.TITLE, "Shutdown 21:00 (+1h) \N{MIDDLE DOT} gaming 1.0h"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -49,7 +49,7 @@ class TestTryAutoUpgradeEarlyBird:
|
|||||||
assert result is True
|
assert result is True
|
||||||
with log_file.open() as f:
|
with log_file.open() as f:
|
||||||
data: dict[str, Any] = json.load(f)
|
data: dict[str, Any] = json.load(f)
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
assert data[today][0]["workout_data"]["type"] == "phone_verified"
|
assert data[today][0]["workout_data"]["type"] == "phone_verified"
|
||||||
assert data[today][0]["workout_data"]["after_early_bird"] == "true"
|
assert data[today][0]["workout_data"]["after_early_bird"] == "true"
|
||||||
|
|
||||||
|
|||||||
@ -81,7 +81,7 @@ class TestIsEarlyBirdPending:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Return False when HMAC verification fails."""
|
"""Return False when HMAC verification fails."""
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
pending_file = tmp_path / "early_bird_pending.json"
|
pending_file = tmp_path / "early_bird_pending.json"
|
||||||
pending_file.write_text(json.dumps({"date": today, "hmac": "bad"}))
|
pending_file.write_text(json.dumps({"date": today, "hmac": "bad"}))
|
||||||
with (
|
with (
|
||||||
@ -105,7 +105,7 @@ class TestIsEarlyBirdPending:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Return True when today's marker is present and HMAC-valid."""
|
"""Return True when today's marker is present and HMAC-valid."""
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
pending_file = tmp_path / "early_bird_pending.json"
|
pending_file = tmp_path / "early_bird_pending.json"
|
||||||
pending_file.write_text(json.dumps({"date": today, "hmac": "sig"}))
|
pending_file.write_text(json.dumps({"date": today, "hmac": "sig"}))
|
||||||
with (
|
with (
|
||||||
@ -125,7 +125,7 @@ class TestIsEarlyBirdPending:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Unsigned marker is accepted when no HMAC key is configured."""
|
"""Unsigned marker is accepted when no HMAC key is configured."""
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
pending_file = tmp_path / "early_bird_pending.json"
|
pending_file = tmp_path / "early_bird_pending.json"
|
||||||
pending_file.write_text(json.dumps({"date": today}))
|
pending_file.write_text(json.dumps({"date": today}))
|
||||||
with (
|
with (
|
||||||
@ -163,7 +163,7 @@ class TestSaveEarlyBirdPending:
|
|||||||
assert pending_file.exists()
|
assert pending_file.exists()
|
||||||
with pending_file.open() as f:
|
with pending_file.open() as f:
|
||||||
data: dict[str, Any] = json.load(f)
|
data: dict[str, Any] = json.load(f)
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
assert data["date"] == today
|
assert data["date"] == today
|
||||||
assert not locker.log_file.exists()
|
assert not locker.log_file.exists()
|
||||||
|
|
||||||
|
|||||||
@ -2,10 +2,8 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
from screen_locker._constants import HEAT_SKIP_CITY, HEAT_SKIP_TEMP_THRESHOLD
|
|
||||||
from screen_locker._heat_skip import HeatSkipMixin
|
from screen_locker._heat_skip import HeatSkipMixin
|
||||||
|
|
||||||
|
|
||||||
@ -17,15 +15,11 @@ class _HeatSkipHost(HeatSkipMixin):
|
|||||||
self.save_workout_log = MagicMock()
|
self.save_workout_log = MagicMock()
|
||||||
|
|
||||||
|
|
||||||
def _button_command(mock_tk: MagicMock, name: str):
|
def _button_command(mock_tk: MagicMock, text: 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:
|
for call in mock_tk.Button.call_args_list:
|
||||||
if call.kwargs.get("name") == name:
|
if call.kwargs.get("text") == text:
|
||||||
return call.kwargs["command"]
|
return call.kwargs["command"]
|
||||||
msg = f"No button named {name!r} was created"
|
msg = f"No button with text {text!r} was created"
|
||||||
raise AssertionError(msg)
|
raise AssertionError(msg)
|
||||||
|
|
||||||
|
|
||||||
@ -37,7 +31,7 @@ class TestShowHeatSkipDialog:
|
|||||||
host = _HeatSkipHost()
|
host = _HeatSkipHost()
|
||||||
|
|
||||||
def _simulate_click() -> None:
|
def _simulate_click() -> None:
|
||||||
_button_command(mock_tk, "skip")()
|
_button_command(mock_tk, "Skip workout")()
|
||||||
|
|
||||||
mock_tk.Tk.return_value.mainloop.side_effect = _simulate_click
|
mock_tk.Tk.return_value.mainloop.side_effect = _simulate_click
|
||||||
assert host._show_heat_skip_dialog(35.0) is True
|
assert host._show_heat_skip_dialog(35.0) is True
|
||||||
@ -48,21 +42,19 @@ class TestShowHeatSkipDialog:
|
|||||||
host = _HeatSkipHost()
|
host = _HeatSkipHost()
|
||||||
|
|
||||||
def _simulate_click() -> None:
|
def _simulate_click() -> None:
|
||||||
_button_command(mock_tk, "decline")()
|
_button_command(mock_tk, "No, I'll workout")()
|
||||||
|
|
||||||
mock_tk.Tk.return_value.mainloop.side_effect = _simulate_click
|
mock_tk.Tk.return_value.mainloop.side_effect = _simulate_click
|
||||||
assert host._show_heat_skip_dialog(35.0) is False
|
assert host._show_heat_skip_dialog(35.0) is False
|
||||||
|
|
||||||
def test_dialog_shows_temperature_and_threshold(self, mock_tk: MagicMock) -> None:
|
def test_dialog_shows_temperature_and_threshold(self, mock_tk: MagicMock) -> None:
|
||||||
"""The dialog shows the rounded temperature against the threshold, no words."""
|
"""The dialog text shows the rounded temperature and mentions the threshold."""
|
||||||
host = _HeatSkipHost()
|
host = _HeatSkipHost()
|
||||||
mock_tk.Tk.return_value.mainloop.side_effect = None
|
mock_tk.Tk.return_value.mainloop.side_effect = None
|
||||||
host._show_heat_skip_dialog(36.4)
|
host._show_heat_skip_dialog(36.4)
|
||||||
texts = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
|
texts = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
|
||||||
assert any(f"36°C ≥ {HEAT_SKIP_TEMP_THRESHOLD}°C" in t for t in texts)
|
assert any("36°C" in t for t in texts)
|
||||||
# Only the city (config data) may carry letters: no chrome sentence.
|
assert any("threshold" in t for t in texts)
|
||||||
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:
|
class TestSaveHeatSkipLog:
|
||||||
|
|||||||
@ -140,7 +140,7 @@ class TestHasLoggedToday:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Test when today's workout is logged with valid HMAC."""
|
"""Test when today's workout is logged with valid HMAC."""
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
log_file.write_text(
|
log_file.write_text(
|
||||||
json.dumps({today: {"workout": "data", "hmac": "valid"}}),
|
json.dumps({today: {"workout": "data", "hmac": "valid"}}),
|
||||||
)
|
)
|
||||||
@ -161,7 +161,7 @@ class TestHasLoggedToday:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Test rejects entry when HMAC verification fails."""
|
"""Test rejects entry when HMAC verification fails."""
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
log_file.write_text(
|
log_file.write_text(
|
||||||
json.dumps({today: {"workout": "data", "hmac": "tampered"}}),
|
json.dumps({today: {"workout": "data", "hmac": "tampered"}}),
|
||||||
)
|
)
|
||||||
@ -182,7 +182,7 @@ class TestHasLoggedToday:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Accept unsigned entry when HMAC key is unavailable."""
|
"""Accept unsigned entry when HMAC key is unavailable."""
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
log_file.write_text(
|
log_file.write_text(
|
||||||
json.dumps({today: {"workout": "data"}}),
|
json.dumps({today: {"workout": "data"}}),
|
||||||
)
|
)
|
||||||
@ -209,7 +209,7 @@ class TestHasLoggedToday:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Reject unsigned entry when HMAC key IS available."""
|
"""Reject unsigned entry when HMAC key IS available."""
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
log_file.write_text(
|
log_file.write_text(
|
||||||
json.dumps({today: {"workout": "data"}}),
|
json.dumps({today: {"workout": "data"}}),
|
||||||
)
|
)
|
||||||
|
|||||||
@ -36,7 +36,7 @@ class TestSaveWorkoutLog:
|
|||||||
assert log_file.exists()
|
assert log_file.exists()
|
||||||
with log_file.open() as f:
|
with log_file.open() as f:
|
||||||
data: dict[str, Any] = json.load(f)
|
data: dict[str, Any] = json.load(f)
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
assert today in data
|
assert today in data
|
||||||
# The log now holds a list of entries per day (multiple workouts/day).
|
# The log now holds a list of entries per day (multiple workouts/day).
|
||||||
assert data[today][0]["workout_data"]["type"] == "running"
|
assert data[today][0]["workout_data"]["type"] == "running"
|
||||||
@ -61,7 +61,7 @@ class TestSaveWorkoutLog:
|
|||||||
|
|
||||||
with log_file.open() as f:
|
with log_file.open() as f:
|
||||||
data: dict[str, Any] = json.load(f)
|
data: dict[str, Any] = json.load(f)
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
assert "hmac" not in data[today][0]
|
assert "hmac" not in data[today][0]
|
||||||
|
|
||||||
def test_save_to_existing_file(
|
def test_save_to_existing_file(
|
||||||
@ -86,7 +86,7 @@ class TestSaveWorkoutLog:
|
|||||||
with log_file.open() as f:
|
with log_file.open() as f:
|
||||||
data: dict[str, Any] = json.load(f)
|
data: dict[str, Any] = json.load(f)
|
||||||
assert "2020-01-01" in data
|
assert "2020-01-01" in data
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
assert today in data
|
assert today in data
|
||||||
|
|
||||||
def test_save_with_corrupted_existing_file(
|
def test_save_with_corrupted_existing_file(
|
||||||
@ -110,7 +110,7 @@ class TestSaveWorkoutLog:
|
|||||||
|
|
||||||
with log_file.open() as f:
|
with log_file.open() as f:
|
||||||
data: dict[str, Any] = json.load(f)
|
data: dict[str, Any] = json.load(f)
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
assert today in data
|
assert today in data
|
||||||
|
|
||||||
def test_save_with_write_error(
|
def test_save_with_write_error(
|
||||||
|
|||||||
@ -163,11 +163,8 @@ class TestBudgetSummary:
|
|||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
_write_logs(log_file, {"2026-07-04": "manual_workout"})
|
_write_logs(log_file, {"2026-07-04": "manual_workout"})
|
||||||
summary = budget_summary(log_file, today=_TODAY)
|
summary = budget_summary(log_file, today=_TODAY)
|
||||||
# Glyph + used/7-day budget · used/30-day budget, no words.
|
assert "Manual:" in summary
|
||||||
assert summary == (
|
assert "1/" in summary
|
||||||
f"≡ 1/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS} · "
|
|
||||||
f"1/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
_TT_DEFAULT = ManualWorkoutDraft(
|
_TT_DEFAULT = ManualWorkoutDraft(
|
||||||
|
|||||||
@ -8,19 +8,12 @@ from unittest.mock import MagicMock, patch
|
|||||||
|
|
||||||
from screen_locker._day import today_str
|
from screen_locker._day import today_str
|
||||||
from screen_locker._manual_schedule import ScheduleResult
|
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 import test_manual_workout_dialog_part2 as dialog_tests
|
||||||
from screen_locker.tests.conftest import create_locker
|
from screen_locker.tests.conftest import create_locker
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
_MOD = "screen_locker._manual_workout_date"
|
_MOD = "screen_locker._manual_workout_date"
|
||||||
|
|
||||||
|
|
||||||
@ -39,11 +32,6 @@ def _locker(mock_tk: MagicMock, tmp_path: Path, day: str) -> MagicMock:
|
|||||||
return locker
|
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:
|
class TestBudgetClosed:
|
||||||
"""The button gate reads the local ledger only (no network)."""
|
"""The button gate reads the local ledger only (no network)."""
|
||||||
|
|
||||||
@ -78,35 +66,25 @@ class TestHandledByDate:
|
|||||||
"""An unparsable date shows an error and schedules nothing."""
|
"""An unparsable date shows an error and schedules nothing."""
|
||||||
locker = _locker(mock_tk, tmp_path, "soon")
|
locker = _locker(mock_tk, tmp_path, "soon")
|
||||||
assert locker._mw_handled_by_date(MagicMock()) is True
|
assert locker._mw_handled_by_date(MagicMock()) is True
|
||||||
locker._mw_error_label.config.assert_called_once_with(text=REJECTED_GLYPH)
|
locker._mw_error_label.config.assert_called_once()
|
||||||
locker._show_manual_workout_scheduled.assert_not_called()
|
locker._show_manual_workout_scheduled.assert_not_called()
|
||||||
|
|
||||||
def test_a_past_date_shows_the_error(
|
def test_a_past_date_shows_the_error(
|
||||||
self,
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
caplog: pytest.LogCaptureFixture,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
"""A past date shows the fail mark; the reason (the past) is logged."""
|
"""A date before today is rejected with a message mentioning the past."""
|
||||||
locker = _locker(mock_tk, tmp_path, _plus(-1))
|
locker = _locker(mock_tk, tmp_path, _plus(-1))
|
||||||
assert locker._mw_handled_by_date(MagicMock()) is True
|
assert locker._mw_handled_by_date(MagicMock()) is True
|
||||||
locker._mw_error_label.config.assert_called_once_with(text=REJECTED_GLYPH)
|
assert "past" in locker._mw_error_label.config.call_args.kwargs["text"]
|
||||||
assert any("past" in m for m in _warned(caplog))
|
|
||||||
|
|
||||||
def test_today_over_budget_shows_the_error(
|
def test_today_over_budget_shows_the_error(
|
||||||
self,
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
caplog: pytest.LogCaptureFixture,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Today's date with no budget left shows the budget error and is handled."""
|
"""Today's date with no budget left shows the budget error and is handled."""
|
||||||
locker = _locker(mock_tk, tmp_path, today_str())
|
locker = _locker(mock_tk, tmp_path, today_str())
|
||||||
with patch(f"{_MOD}.budget_error", return_value="budget full"):
|
with patch(f"{_MOD}.budget_error", return_value="budget full"):
|
||||||
assert locker._mw_handled_by_date(MagicMock()) is True
|
assert locker._mw_handled_by_date(MagicMock()) is True
|
||||||
locker._mw_error_label.config.assert_called_once_with(text=REJECTED_GLYPH)
|
locker._mw_error_label.config.assert_called_once_with(text="budget full")
|
||||||
assert any("budget full" in m for m in _warned(caplog))
|
|
||||||
|
|
||||||
def test_today_within_budget_is_left_to_the_host(
|
def test_today_within_budget_is_left_to_the_host(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
@ -118,19 +96,14 @@ class TestHandledByDate:
|
|||||||
locker._mw_error_label.config.assert_not_called()
|
locker._mw_error_label.config.assert_not_called()
|
||||||
|
|
||||||
def test_a_refused_future_entry_shows_why(
|
def test_a_refused_future_entry_shows_why(
|
||||||
self,
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
caplog: pytest.LogCaptureFixture,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
"""A refused future entry shows the fail mark, logs why, confirms nothing."""
|
"""A future entry the scheduler refuses shows its reason and no confirmation."""
|
||||||
locker = _locker(mock_tk, tmp_path, _plus(2))
|
locker = _locker(mock_tk, tmp_path, _plus(2))
|
||||||
refused = ScheduleResult(scheduled=False, record_id="r", reason="no room")
|
refused = ScheduleResult(scheduled=False, record_id="r", reason="no room")
|
||||||
with patch(f"{_MOD}.schedule_future_workout", return_value=refused):
|
with patch(f"{_MOD}.schedule_future_workout", return_value=refused):
|
||||||
assert locker._mw_handled_by_date(MagicMock()) is True
|
assert locker._mw_handled_by_date(MagicMock()) is True
|
||||||
locker._mw_error_label.config.assert_called_once_with(text=REJECTED_GLYPH)
|
locker._mw_error_label.config.assert_called_once_with(text="no room")
|
||||||
assert any("no room" in m for m in _warned(caplog))
|
|
||||||
locker._show_manual_workout_scheduled.assert_not_called()
|
locker._show_manual_workout_scheduled.assert_not_called()
|
||||||
|
|
||||||
def test_a_scheduled_future_entry_shows_the_confirmation(
|
def test_a_scheduled_future_entry_shows_the_confirmation(
|
||||||
@ -143,7 +116,7 @@ class TestHandledByDate:
|
|||||||
with patch(f"{_MOD}.schedule_future_workout", return_value=done) as schedule:
|
with patch(f"{_MOD}.schedule_future_workout", return_value=done) as schedule:
|
||||||
assert locker._mw_handled_by_date(draft) is True
|
assert locker._mw_handled_by_date(draft) is True
|
||||||
schedule.assert_called_once_with(locker.log_file, draft, _plus(2))
|
schedule.assert_called_once_with(locker.log_file, draft, _plus(2))
|
||||||
locker._show_manual_workout_scheduled.assert_called_once_with(_plus(2))
|
locker._show_manual_workout_scheduled.assert_called_once_with("scheduled")
|
||||||
locker._mw_error_label.config.assert_not_called()
|
locker._mw_error_label.config.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
@ -161,18 +134,18 @@ class TestScheduledConfirmation:
|
|||||||
object.__setattr__(locker, "_on_manual_workout_cancelled", cancelled)
|
object.__setattr__(locker, "_on_manual_workout_cancelled", cancelled)
|
||||||
mock_tk.Button.reset_mock()
|
mock_tk.Button.reset_mock()
|
||||||
|
|
||||||
locker._show_manual_workout_scheduled("2026-11-13")
|
locker._show_manual_workout_scheduled("scheduled for tomorrow")
|
||||||
|
|
||||||
buttons = {
|
buttons = {
|
||||||
c.kwargs.get("text"): c.kwargs for c in mock_tk.Button.call_args_list
|
c.kwargs.get("text"): c.kwargs for c in mock_tk.Button.call_args_list
|
||||||
}
|
}
|
||||||
assert set(buttons) == {BACK_GLYPH}
|
assert set(buttons) == {"OK"}
|
||||||
buttons[BACK_GLYPH]["command"]()
|
buttons["OK"]["command"]()
|
||||||
cancelled.assert_called_once_with()
|
cancelled.assert_called_once_with()
|
||||||
saved.assert_not_called()
|
saved.assert_not_called()
|
||||||
texts = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
|
texts = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
|
||||||
assert SCHEDULED_GLYPH in texts
|
assert any("Workout Scheduled" in t for t in texts)
|
||||||
assert "2026-11-13" in texts
|
assert any("scheduled for tomorrow" in t for t in texts)
|
||||||
|
|
||||||
|
|
||||||
class TestSubmitRoutesThroughTheDateRules:
|
class TestSubmitRoutesThroughTheDateRules:
|
||||||
|
|||||||
@ -6,8 +6,6 @@ from typing import TYPE_CHECKING
|
|||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from screen_locker import _manual_workout
|
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
|
from screen_locker.tests.conftest import create_locker
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -27,8 +25,8 @@ class TestShowManualWorkoutForm:
|
|||||||
with patch(_CLOSED, return_value=False):
|
with patch(_CLOSED, return_value=False):
|
||||||
locker._show_manual_workout_form()
|
locker._show_manual_workout_form()
|
||||||
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
|
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
|
||||||
assert SUBMIT_GLYPH in button_texts
|
assert "SUBMIT" in button_texts
|
||||||
assert BACK_GLYPH in button_texts
|
assert "BACK" in button_texts
|
||||||
|
|
||||||
def test_shows_exhausted_message_and_hides_submit(
|
def test_shows_exhausted_message_and_hides_submit(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
@ -38,10 +36,10 @@ class TestShowManualWorkoutForm:
|
|||||||
with patch(_CLOSED, return_value=True):
|
with patch(_CLOSED, return_value=True):
|
||||||
locker._show_manual_workout_form()
|
locker._show_manual_workout_form()
|
||||||
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
|
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
|
||||||
assert BACK_GLYPH in button_texts
|
assert "BACK" in button_texts
|
||||||
assert SUBMIT_GLYPH not in button_texts
|
assert "SUBMIT" not in button_texts
|
||||||
text_calls = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
|
text_calls = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
|
||||||
assert EXHAUSTED_GLYPH in text_calls
|
assert any("exhausted" in t for t in text_calls)
|
||||||
|
|
||||||
|
|
||||||
class TestSportToggle:
|
class TestSportToggle:
|
||||||
|
|||||||
@ -6,7 +6,6 @@ import pathlib
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker.tests.conftest import create_locker
|
from screen_locker.tests.conftest import create_locker
|
||||||
|
|
||||||
# The Dart mirror of the budget caps; read at test time so drift on
|
# The Dart mirror of the budget caps; read at test time so drift on
|
||||||
@ -39,7 +38,7 @@ class TestShowRetryAndManualWorkoutBudget:
|
|||||||
):
|
):
|
||||||
locker._show_retry_and_sick("nope")
|
locker._show_retry_and_sick("nope")
|
||||||
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
|
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
|
||||||
assert g.FORM in button_texts
|
assert "Log Manual Workout" in button_texts
|
||||||
|
|
||||||
def test_hides_button_when_budget_exhausted(
|
def test_hides_button_when_budget_exhausted(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
@ -53,9 +52,9 @@ class TestShowRetryAndManualWorkoutBudget:
|
|||||||
button_texts: set[str] = set()
|
button_texts: set[str] = set()
|
||||||
for call in mock_tk.Button.call_args_list:
|
for call in mock_tk.Button.call_args_list:
|
||||||
button_texts.add(call.kwargs.get("text", ""))
|
button_texts.add(call.kwargs.get("text", ""))
|
||||||
assert g.FORM not in button_texts
|
assert "Log Manual Workout" not in button_texts
|
||||||
text_calls = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
|
text_calls = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
|
||||||
assert f"{g.FORM} {g.CLOSE}" in text_calls
|
assert any("Manual-workout budget exhausted" in t for t in text_calls)
|
||||||
|
|
||||||
|
|
||||||
class TestOnManualWorkoutSaved:
|
class TestOnManualWorkoutSaved:
|
||||||
|
|||||||
@ -5,7 +5,6 @@ from __future__ import annotations
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._workout_credit import WorkoutCreditResult
|
from screen_locker._workout_credit import WorkoutCreditResult
|
||||||
from screen_locker.tests._status_view_helpers import (
|
from screen_locker.tests._status_view_helpers import (
|
||||||
_button_texts,
|
_button_texts,
|
||||||
@ -32,7 +31,7 @@ class TestSectionManualWorkoutBudget:
|
|||||||
calls = [
|
calls = [
|
||||||
c
|
c
|
||||||
for c in mock_tk.Label.call_args_list
|
for c in mock_tk.Label.call_args_list
|
||||||
if c.kwargs.get("text", "") == f"{g.FORM} 2/2 · 0/5"
|
if "week" in c.kwargs.get("text", "")
|
||||||
]
|
]
|
||||||
assert any(c.kwargs.get("fg") == window._colors.palette.danger for c in calls)
|
assert any(c.kwargs.get("fg") == window._colors.palette.danger for c in calls)
|
||||||
|
|
||||||
@ -45,7 +44,7 @@ class TestSectionManualWorkoutBudget:
|
|||||||
calls = [
|
calls = [
|
||||||
c
|
c
|
||||||
for c in mock_tk.Label.call_args_list
|
for c in mock_tk.Label.call_args_list
|
||||||
if c.kwargs.get("text", "") == f"{g.FORM} 0/2 · 0/5"
|
if "week" in c.kwargs.get("text", "")
|
||||||
]
|
]
|
||||||
assert any(c.kwargs.get("fg") == window._colors.palette.muted for c in calls)
|
assert any(c.kwargs.get("fg") == window._colors.palette.muted for c in calls)
|
||||||
|
|
||||||
@ -58,7 +57,7 @@ class TestManualWorkoutButtonVisibility:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""The Log Manual Workout button appears while budget remains."""
|
"""The Log Manual Workout button appears while budget remains."""
|
||||||
_make_window(mock_tk, _snapshot(), log_file=temp_log_file)
|
_make_window(mock_tk, _snapshot(), log_file=temp_log_file)
|
||||||
assert g.FORM in _button_texts(mock_tk)
|
assert "Log Manual Workout" in _button_texts(mock_tk)
|
||||||
|
|
||||||
def test_hidden_when_budget_exhausted(
|
def test_hidden_when_budget_exhausted(
|
||||||
self, mock_tk: MagicMock, temp_log_file: Path
|
self, mock_tk: MagicMock, temp_log_file: Path
|
||||||
@ -66,7 +65,7 @@ class TestManualWorkoutButtonVisibility:
|
|||||||
"""The Log Manual Workout button is hidden once the budget is closed."""
|
"""The Log Manual Workout button is hidden once the budget is closed."""
|
||||||
with patch(_CLOSED, return_value=True):
|
with patch(_CLOSED, return_value=True):
|
||||||
_make_window(mock_tk, _snapshot(), log_file=temp_log_file)
|
_make_window(mock_tk, _snapshot(), log_file=temp_log_file)
|
||||||
assert g.FORM not in _button_texts(mock_tk)
|
assert "Log Manual Workout" not in _button_texts(mock_tk)
|
||||||
|
|
||||||
|
|
||||||
class TestOnManualWorkoutSaved:
|
class TestOnManualWorkoutSaved:
|
||||||
@ -103,7 +102,8 @@ class TestOnManualWorkoutSaved:
|
|||||||
fake_verifier._apply_workout_credit.assert_called_once()
|
fake_verifier._apply_workout_credit.assert_called_once()
|
||||||
message = window._credit_message
|
message = window._credit_message
|
||||||
assert message is not None
|
assert message is not None
|
||||||
assert message.splitlines() == [f"{g.FORM} {g.OK}", f"{g.SHUTDOWN} +2h"]
|
assert "table tennis at Solec" in message
|
||||||
|
assert "Shutdown time +2h later!" in message
|
||||||
|
|
||||||
def test_shows_extra_bonus_line_and_no_debt(
|
def test_shows_extra_bonus_line_and_no_debt(
|
||||||
self, mock_tk: MagicMock, temp_log_file: Path
|
self, mock_tk: MagicMock, temp_log_file: Path
|
||||||
@ -127,12 +127,13 @@ class TestOnManualWorkoutSaved:
|
|||||||
|
|
||||||
message = window._credit_message
|
message = window._credit_message
|
||||||
assert message is not None
|
assert message is not None
|
||||||
assert message.splitlines() == [f"{g.FORM} {g.OK}", f"{g.LIFT} +1h"]
|
assert "Extra workout today! +1h tonight" in message
|
||||||
|
assert "debt" not in message.lower()
|
||||||
|
|
||||||
def test_already_counted_today_shows_no_extra_credit_note(
|
def test_already_counted_today_shows_no_extra_credit_note(
|
||||||
self, mock_tk: MagicMock, temp_log_file: Path
|
self, mock_tk: MagicMock, temp_log_file: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""A second workout the same day shows a zero gift and no reward line."""
|
"""A second workout the same day says no additional credit was given."""
|
||||||
credit = WorkoutCreditResult(
|
credit = WorkoutCreditResult(
|
||||||
shutdown_adjusted=False,
|
shutdown_adjusted=False,
|
||||||
extra_bonus_delta=0,
|
extra_bonus_delta=0,
|
||||||
@ -151,7 +152,8 @@ class TestOnManualWorkoutSaved:
|
|||||||
|
|
||||||
message = window._credit_message
|
message = window._credit_message
|
||||||
assert message is not None
|
assert message is not None
|
||||||
assert message.splitlines() == [f"{g.FORM} {g.OK}", f"{g.OK}{g.OK} +0"]
|
assert "no additional credit" in message
|
||||||
|
assert "Shutdown time" not in message
|
||||||
|
|
||||||
|
|
||||||
class TestOnManualWorkoutCancelled:
|
class TestOnManualWorkoutCancelled:
|
||||||
|
|||||||
@ -7,7 +7,6 @@ from unittest.mock import MagicMock, patch
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker.tests._unlock_helpers import setup_unlock
|
from screen_locker.tests._unlock_helpers import setup_unlock
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -50,7 +49,7 @@ class TestUnlockScreenExtras:
|
|||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""extra_bonus_delta > 0 → _text shows the barbell and the +1h gift."""
|
"""extra_bonus_delta > 0 → _text called with 'Extra workout'."""
|
||||||
locker = setup_unlock(mock_tk, tmp_path, seed_today_type="manual_workout")
|
locker = setup_unlock(mock_tk, tmp_path, seed_today_type="manual_workout")
|
||||||
|
|
||||||
# Simulate before=22:00, after=23:00 → delta=60
|
# Simulate before=22:00, after=23:00 → delta=60
|
||||||
@ -78,7 +77,7 @@ class TestUnlockScreenExtras:
|
|||||||
):
|
):
|
||||||
locker.unlock_screen()
|
locker.unlock_screen()
|
||||||
|
|
||||||
assert f"{g.LIFT} {g.GIFT}1h" in text_calls
|
assert any("Extra workout" in c for c in text_calls)
|
||||||
|
|
||||||
def test_no_extra_bonus_when_adjust_fails(
|
def test_no_extra_bonus_when_adjust_fails(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@ -64,7 +64,7 @@ class TestTryAutoUpgradeEarlyBirdRunnerUp:
|
|||||||
result = locker._try_auto_upgrade_early_bird()
|
result = locker._try_auto_upgrade_early_bird()
|
||||||
|
|
||||||
assert result is True
|
assert result is True
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
data = json.loads(log_file.read_text())
|
data = json.loads(log_file.read_text())
|
||||||
assert data[today][0]["workout_data"]["type"] == "runnerup_verified"
|
assert data[today][0]["workout_data"]["type"] == "runnerup_verified"
|
||||||
assert data[today][0]["workout_data"]["after_early_bird"] == "true"
|
assert data[today][0]["workout_data"]["after_early_bird"] == "true"
|
||||||
|
|||||||
@ -12,7 +12,6 @@ from unittest.mock import MagicMock, patch
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker.tests._locker_factories import create_locker
|
from screen_locker.tests._locker_factories import create_locker
|
||||||
from screen_locker.tests._unlock_helpers import setup_unlock
|
from screen_locker.tests._unlock_helpers import setup_unlock
|
||||||
|
|
||||||
@ -52,7 +51,7 @@ class TestUnlockScreenRewards:
|
|||||||
):
|
):
|
||||||
locker.unlock_screen()
|
locker.unlock_screen()
|
||||||
|
|
||||||
assert f"{g.STREAK * 3} 3" in text_calls
|
assert any("streak" in c.lower() for c in text_calls)
|
||||||
|
|
||||||
def test_extra_bonus_skipped_when_old_cfg_none(
|
def test_extra_bonus_skipped_when_old_cfg_none(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@ -78,7 +78,7 @@ class TestResetToBaseIfNewDay:
|
|||||||
|
|
||||||
def test_returns_false_when_already_reset_today(self, tmp_path: Path) -> None:
|
def test_returns_false_when_already_reset_today(self, tmp_path: Path) -> None:
|
||||||
"""Same-day last_reset_date → early False return (line 63)."""
|
"""Same-day last_reset_date → early False return (line 63)."""
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
f = tmp_path / "state.json"
|
f = tmp_path / "state.json"
|
||||||
f.write_text(json.dumps({"last_reset_date": today}))
|
f.write_text(json.dumps({"last_reset_date": today}))
|
||||||
assert reset_to_base_if_new_day(f, self._make_mixin()) is False
|
assert reset_to_base_if_new_day(f, self._make_mixin()) is False
|
||||||
|
|||||||
@ -10,7 +10,6 @@ from unittest.mock import MagicMock, patch
|
|||||||
import freedays
|
import freedays
|
||||||
import sickdays
|
import sickdays
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker import _sick, _ui_flows_sick
|
from screen_locker import _sick, _ui_flows_sick
|
||||||
from screen_locker._auto_upgrade import AutoUpgradeMixin
|
from screen_locker._auto_upgrade import AutoUpgradeMixin
|
||||||
from screen_locker._compliance_predicates import is_sick_day_today
|
from screen_locker._compliance_predicates import is_sick_day_today
|
||||||
@ -21,8 +20,6 @@ from screen_locker.tests.conftest import create_locker
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
def _button_texts(mock_tk: MagicMock) -> list[str]:
|
def _button_texts(mock_tk: MagicMock) -> list[str]:
|
||||||
"""Return the text of every Button created on the mocked tk module."""
|
"""Return the text of every Button created on the mocked tk module."""
|
||||||
@ -158,7 +155,7 @@ class TestButtonEverywhere:
|
|||||||
"""The retry screen shows the I'm sick button."""
|
"""The retry screen shows the I'm sick button."""
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker._show_retry_and_sick("nope")
|
locker._show_retry_and_sick("nope")
|
||||||
assert g.SICK in _button_texts(mock_tk)
|
assert "I'm sick" in _button_texts(mock_tk)
|
||||||
|
|
||||||
def test_phone_penalty_screen_offers_it_without_waiting(
|
def test_phone_penalty_screen_offers_it_without_waiting(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
@ -166,7 +163,7 @@ class TestButtonEverywhere:
|
|||||||
"""The phone penalty screen shows I'm sick immediately."""
|
"""The phone penalty screen shows I'm sick immediately."""
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker._show_phone_penalty("no phone")
|
locker._show_phone_penalty("no phone")
|
||||||
assert g.SICK in _button_texts(mock_tk)
|
assert "I'm sick" in _button_texts(mock_tk)
|
||||||
|
|
||||||
def test_relaxed_prompt_and_retry_offer_it(
|
def test_relaxed_prompt_and_retry_offer_it(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
@ -174,10 +171,10 @@ class TestButtonEverywhere:
|
|||||||
"""Both the relaxed-day prompt and its retry screen show I'm sick."""
|
"""Both the relaxed-day prompt and its retry screen show I'm sick."""
|
||||||
locker = create_locker_relaxed_day(mock_tk, tmp_path)
|
locker = create_locker_relaxed_day(mock_tk, tmp_path)
|
||||||
locker._start_relaxed_day_flow()
|
locker._start_relaxed_day_flow()
|
||||||
assert g.SICK in _button_texts(mock_tk)
|
assert "I'm sick" in _button_texts(mock_tk)
|
||||||
mock_tk.Button.reset_mock()
|
mock_tk.Button.reset_mock()
|
||||||
locker._show_relaxed_retry("nothing", "no_workout")
|
locker._show_relaxed_retry("nothing", "no_workout")
|
||||||
assert g.SICK in _button_texts(mock_tk)
|
assert "I'm sick" in _button_texts(mock_tk)
|
||||||
|
|
||||||
|
|
||||||
class TestTap:
|
class TestTap:
|
||||||
@ -203,13 +200,9 @@ class TestTap:
|
|||||||
close.assert_called_once_with()
|
close.assert_called_once_with()
|
||||||
|
|
||||||
def test_refusal_stays_locked_and_says_why(
|
def test_refusal_stays_locked_and_says_why(
|
||||||
self,
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
caplog: pytest.LogCaptureFixture,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
"""A refused tap keeps the lock, shows sick-fail, logs why, offers back."""
|
"""A refused tap keeps the lock, shows the reason and offers a Back button."""
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
close = MagicMock()
|
close = MagicMock()
|
||||||
object.__setattr__(locker, "close", close)
|
object.__setattr__(locker, "close", close)
|
||||||
@ -221,15 +214,9 @@ class TestTap:
|
|||||||
locker.mark_sick_and_unlock()
|
locker.mark_sick_and_unlock()
|
||||||
close.assert_not_called()
|
close.assert_not_called()
|
||||||
push.assert_not_called()
|
push.assert_not_called()
|
||||||
assert f"{g.SICK} {g.FAIL}" in _label_texts(mock_tk)
|
assert "today is a free day" 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(
|
back = next(
|
||||||
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == g.BACK
|
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == "Back"
|
||||||
)
|
)
|
||||||
assert [back.kwargs["command"]] == [locker._start_phone_check]
|
assert [back.kwargs["command"]] == [locker._start_phone_check]
|
||||||
|
|
||||||
@ -240,6 +227,6 @@ class TestTap:
|
|||||||
locker = create_locker_relaxed_day(mock_tk, tmp_path)
|
locker = create_locker_relaxed_day(mock_tk, tmp_path)
|
||||||
locker._show_sick_refused("nope")
|
locker._show_sick_refused("nope")
|
||||||
back = next(
|
back = next(
|
||||||
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == g.BACK
|
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == "Back"
|
||||||
)
|
)
|
||||||
assert [back.kwargs["command"]] == [locker._start_relaxed_day_flow]
|
assert [back.kwargs["command"]] == [locker._start_relaxed_day_flow]
|
||||||
|
|||||||
@ -13,7 +13,6 @@ import pytest
|
|||||||
import sickdays
|
import sickdays
|
||||||
import sickdays.gui._panel
|
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 import _ui_flows_sick, _ui_flows_sick_panel
|
||||||
from screen_locker._ui_flows_sick_panel import LINK_TEXT, build_sick_panel
|
from screen_locker._ui_flows_sick_panel import LINK_TEXT, build_sick_panel
|
||||||
from screen_locker.tests.conftest import create_locker
|
from screen_locker.tests.conftest import create_locker
|
||||||
@ -98,15 +97,15 @@ class TestLink:
|
|||||||
def test_the_link_sits_next_to_the_one_tap_button(
|
def test_the_link_sits_next_to_the_one_tap_button(
|
||||||
self, mock_tk: MagicMock, locker: ScreenLocker
|
self, mock_tk: MagicMock, locker: ScreenLocker
|
||||||
) -> None:
|
) -> None:
|
||||||
"""The link is wired to open_sick_panel and sits right after the sick button."""
|
"""The link is wired to open_sick_panel and appears right after the "I'm sick" button."""
|
||||||
locker._show_retry_and_sick("nope")
|
locker._show_retry_and_sick("nope")
|
||||||
buttons = mock_tk.Button.call_args_list
|
buttons = mock_tk.Button.call_args_list
|
||||||
texts = _texts(mock_tk.Button)
|
texts = _texts(mock_tk.Button)
|
||||||
sick = next(c for c in buttons if c.kwargs.get("text") == g.SICK)
|
sick = next(c for c in buttons if c.kwargs.get("text") == "I'm sick")
|
||||||
link = next(c for c in buttons if c.kwargs.get("text") == LINK_TEXT)
|
link = next(c for c in buttons if c.kwargs.get("text") == LINK_TEXT)
|
||||||
assert sick.kwargs["command"] == locker.mark_sick_and_unlock
|
assert sick.kwargs["command"] == locker.mark_sick_and_unlock
|
||||||
assert link.kwargs["command"] == locker.open_sick_panel
|
assert link.kwargs["command"] == locker.open_sick_panel
|
||||||
assert texts.index(LINK_TEXT) == texts.index(g.SICK) + 1
|
assert texts.index(LINK_TEXT) == texts.index("I'm sick") + 1
|
||||||
|
|
||||||
def test_opening_builds_todays_panel_on_a_backdrop(
|
def test_opening_builds_todays_panel_on_a_backdrop(
|
||||||
self, locker: ScreenLocker, panels: list[FakePanel]
|
self, locker: ScreenLocker, panels: list[FakePanel]
|
||||||
|
|||||||
@ -8,7 +8,6 @@ from unittest.mock import MagicMock, patch
|
|||||||
import pytest
|
import pytest
|
||||||
import sickdays
|
import sickdays
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker import _ui_flows_sick
|
from screen_locker import _ui_flows_sick
|
||||||
from screen_locker._ui_flows_sick_panel import KEPT_NOTE
|
from screen_locker._ui_flows_sick_panel import KEPT_NOTE
|
||||||
from screen_locker.tests._sick_helpers import mark_sick
|
from screen_locker.tests._sick_helpers import mark_sick
|
||||||
@ -76,7 +75,7 @@ class TestSaved:
|
|||||||
assert KEPT_NOTE in _texts(mock_tk.Label)
|
assert KEPT_NOTE in _texts(mock_tk.Label)
|
||||||
mock_tk.Button.return_value.focus_set.assert_called_once_with()
|
mock_tk.Button.return_value.focus_set.assert_called_once_with()
|
||||||
back = next(
|
back = next(
|
||||||
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == g.BACK
|
c for c in mock_tk.Button.call_args_list if c.kwargs.get("text") == "Back"
|
||||||
)
|
)
|
||||||
back.kwargs["command"]()
|
back.kwargs["command"]()
|
||||||
assert locker._sick_overlay is None
|
assert locker._sick_overlay is None
|
||||||
|
|||||||
@ -4,7 +4,6 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker.tests._status_view_helpers import (
|
from screen_locker.tests._status_view_helpers import (
|
||||||
_make_window,
|
_make_window,
|
||||||
_snapshot,
|
_snapshot,
|
||||||
@ -15,38 +14,32 @@ if TYPE_CHECKING:
|
|||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
|
||||||
def _fg_of(mock_tk: MagicMock, text: str) -> list[object]:
|
def _fg_of(mock_tk: MagicMock, needle: str) -> list[object]:
|
||||||
"""fg of every Label whose text is exactly *text*."""
|
|
||||||
return [
|
return [
|
||||||
c.kwargs.get("fg")
|
c.kwargs.get("fg")
|
||||||
for c in mock_tk.Label.call_args_list
|
for c in mock_tk.Label.call_args_list
|
||||||
if c.kwargs.get("text", "") == text
|
if needle in c.kwargs.get("text", "")
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class TestSectionStreak:
|
class TestSectionStreak:
|
||||||
"""Tests for StatusWindow._section_streak (display only, glyphs + numbers)."""
|
"""Tests for StatusWindow._section_streak (display only)."""
|
||||||
|
|
||||||
def test_shows_the_real_week_count_in_success_color(
|
def test_shows_the_real_week_count_in_success_color(
|
||||||
self, mock_tk: MagicMock
|
self, mock_tk: MagicMock
|
||||||
) -> None:
|
) -> None:
|
||||||
"""One bar per streak week plus the real count, in the success colour."""
|
"""The streak line shows the real week count in the success colour."""
|
||||||
window = _make_window(mock_tk, _snapshot(streak=3))
|
window = _make_window(mock_tk, _snapshot(streak=3))
|
||||||
line = f"{g.STREAK * 3} 3"
|
assert any("3-week streak" in t for t in _texts(mock_tk))
|
||||||
assert line in _texts(mock_tk)
|
assert window._colors.palette.success in _fg_of(mock_tk, "3-week streak")
|
||||||
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:
|
def test_zero_streak_is_stated_plainly_not_padded(self, mock_tk: MagicMock) -> None:
|
||||||
"""A zero streak is one bar and 0, muted, never padded."""
|
"""A zero streak reads No streak in the muted colour, with no week count."""
|
||||||
window = _make_window(mock_tk, _snapshot(streak=0))
|
window = _make_window(mock_tk, _snapshot(streak=0))
|
||||||
line = f"{g.STREAK} 0"
|
texts = _texts(mock_tk)
|
||||||
assert line in _texts(mock_tk)
|
assert any("No streak" in t for t in texts)
|
||||||
assert window._colors.palette.muted in _fg_of(mock_tk, line)
|
assert not any("-week streak" in t for t in texts)
|
||||||
|
assert window._colors.palette.muted in _fg_of(mock_tk, "No streak")
|
||||||
|
|
||||||
def test_early_bird_is_never_rendered(self, mock_tk: MagicMock) -> None:
|
def test_early_bird_is_never_rendered(self, mock_tk: MagicMock) -> None:
|
||||||
"""The 09:00 early-bird extension is gone (wake-alarm owns it)."""
|
"""The 09:00 early-bird extension is gone (wake-alarm owns it)."""
|
||||||
@ -56,24 +49,19 @@ class TestSectionStreak:
|
|||||||
def test_week_reward_reaches_the_window_in_success_color(
|
def test_week_reward_reaches_the_window_in_success_color(
|
||||||
self, mock_tk: MagicMock
|
self, mock_tk: MagicMock
|
||||||
) -> None:
|
) -> None:
|
||||||
"""A week reward shows as bar + gift, success colour; never its words."""
|
"""A week reward message is shown in the success colour."""
|
||||||
msg = "5 workouts in 2026-W41! 4-week streak"
|
msg = "5 workouts in 2026-W41! 4-week streak"
|
||||||
window = _make_window(mock_tk, _snapshot(streak=4, week_rewards=(msg,)))
|
window = _make_window(mock_tk, _snapshot(streak=4, week_rewards=(msg,)))
|
||||||
assert msg not in _texts(mock_tk)
|
assert msg in _texts(mock_tk)
|
||||||
line = f"{g.STREAK}{g.GIFT}"
|
assert window._colors.palette.success in _fg_of(mock_tk, msg)
|
||||||
assert window._colors.palette.success in _fg_of(mock_tk, line)
|
|
||||||
|
|
||||||
def test_no_reward_line_when_the_week_has_none(self, mock_tk: MagicMock) -> None:
|
def test_no_reward_text_when_the_week_has_none(self, mock_tk: MagicMock) -> None:
|
||||||
"""No reward or reset line appears when the week has no reward."""
|
"""No reward line appears when the week has no reward."""
|
||||||
_make_window(mock_tk, _snapshot(streak=4))
|
_make_window(mock_tk, _snapshot(streak=4))
|
||||||
texts = _texts(mock_tk)
|
assert not any("workouts in 20" in t for t in _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:
|
def test_a_streak_reset_is_not_painted_as_a_win(self, mock_tk: MagicMock) -> None:
|
||||||
"""A streak reset shows as bar + fail in the warning colour, not as a win."""
|
"""A streak-reset message is shown in the warning colour, not as a win."""
|
||||||
msg = "Streak reset (was 3 weeks of 5+ workouts)"
|
msg = "Streak reset (was 3 weeks of 5+ workouts)"
|
||||||
window = _make_window(mock_tk, _snapshot(streak=0, week_rewards=(msg,)))
|
window = _make_window(mock_tk, _snapshot(streak=0, week_rewards=(msg,)))
|
||||||
assert _fg_of(mock_tk, f"{g.STREAK}{g.FAIL}") == [
|
assert window._colors.palette.warning in _fg_of(mock_tk, msg)
|
||||||
window._colors.palette.warning
|
|
||||||
]
|
|
||||||
|
|||||||
@ -1,16 +1,9 @@
|
|||||||
"""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 __future__ import annotations
|
||||||
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from gatelock import LockConfig
|
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._compliance_state import AutoUpgradeOpportunity
|
from screen_locker._compliance_state import AutoUpgradeOpportunity
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -25,22 +18,12 @@ from screen_locker.tests._status_view_helpers import (
|
|||||||
_week,
|
_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:
|
class TestSectionToday:
|
||||||
"""SectionToday."""
|
"""SectionToday."""
|
||||||
|
|
||||||
def test_counted_shows_checkmark_and_entry(self, mock_tk: MagicMock) -> None:
|
def test_counted_shows_checkmark_and_entry(self, mock_tk: MagicMock) -> None:
|
||||||
"""A counted day shows the tick and its entry's glyph, not the source."""
|
"""Counted shows checkmark and entry."""
|
||||||
snap = _snapshot(
|
snap = _snapshot(
|
||||||
today=_day(
|
today=_day(
|
||||||
entry_types=("phone_verified",),
|
entry_types=("phone_verified",),
|
||||||
@ -51,53 +34,64 @@ class TestSectionToday:
|
|||||||
)
|
)
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
texts = _texts(mock_tk)
|
texts = _texts(mock_tk)
|
||||||
assert f"{g.OK} {g.LIFT}" in texts
|
assert any("✓" in t and "phone_verified" in t for t in texts)
|
||||||
assert "gym" not in texts
|
assert any(t == "gym" for t in texts)
|
||||||
|
|
||||||
def test_sick_day_shows_sick_mark(self, mock_tk: MagicMock) -> None:
|
def test_sick_day_shows_sick_mark(self, mock_tk: MagicMock) -> None:
|
||||||
"""Sick day shows the sick cross twice: mark and cell."""
|
"""Sick day shows sick mark."""
|
||||||
snap = _snapshot(today=_day(entry_types=(), is_sick_day=True))
|
snap = _snapshot(today=_day(entry_types=(), is_sick_day=True))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert f"{g.SICK} {g.WEEK_SICK}" in _texts(mock_tk)
|
assert any("😷" in t and "sick day" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_no_entry_shows_fail_and_empty_circle(self, mock_tk: MagicMock) -> None:
|
def test_no_entry_shows_dash(self, mock_tk: MagicMock) -> None:
|
||||||
"""No entry: the fail mark over an empty circle, in warning colour."""
|
"""No entry shows dash."""
|
||||||
snap = _snapshot(today=_day(entry_types=(), is_sick_day=False))
|
snap = _snapshot(today=_day(entry_types=(), is_sick_day=False))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert (f"{g.FAIL} {g.WEEK_EMPTY}", _PALETTE.warning) in _colored(mock_tk)
|
assert any("no entry yet" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_unknown_entry_type_falls_back_to_tick(self, mock_tk: MagicMock) -> None:
|
def test_empty_source_adds_no_extra_line(self, mock_tk: MagicMock) -> None:
|
||||||
"""An entry type with no glyph shows as a tick, never as its name."""
|
"""Empty source adds no extra line."""
|
||||||
snap = _snapshot(today=_day(entry_types=("mystery",), counted=True))
|
snap = _snapshot(
|
||||||
|
today=_day(
|
||||||
|
entry_types=("phone_verified",),
|
||||||
|
counted=True,
|
||||||
|
day_count=1,
|
||||||
|
source="",
|
||||||
|
)
|
||||||
|
)
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
texts = _texts(mock_tk)
|
# Only the main "Today (...)" line, no second call for an empty source.
|
||||||
assert f"{g.OK} {g.OK}" in texts
|
today_related = [t for t in _texts(mock_tk) if "Today" in t]
|
||||||
assert not any("mystery" in t for t in texts)
|
assert len(today_related) == 1
|
||||||
|
|
||||||
|
|
||||||
class TestSectionWeek:
|
class TestSectionWeek:
|
||||||
"""SectionWeek."""
|
"""SectionWeek."""
|
||||||
|
|
||||||
def test_under_minimum_is_warning_dots(self, mock_tk: MagicMock) -> None:
|
def test_shows_remaining_message_when_under_minimum(
|
||||||
"""Under the minimum: filled/empty dots and the count, warning colour."""
|
self, mock_tk: MagicMock
|
||||||
|
) -> None:
|
||||||
|
"""Shows remaining message when under minimum."""
|
||||||
snap = _snapshot(week=_week(counted_count=2, remaining=2, extra=0))
|
snap = _snapshot(week=_week(counted_count=2, remaining=2, extra=0))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert (g.dots(2, 4), _PALETTE.warning) in _colored(mock_tk)
|
assert any("Need 2 more this week." in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_over_minimum_is_success_dots(self, mock_tk: MagicMock) -> None:
|
def test_shows_extra_message_when_over_minimum(self, mock_tk: MagicMock) -> None:
|
||||||
"""Over the minimum: the count above the total, success colour."""
|
"""Shows extra message when over minimum."""
|
||||||
snap = _snapshot(week=_week(counted_count=5, remaining=0, extra=1))
|
snap = _snapshot(week=_week(counted_count=5, remaining=0, extra=1))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert ("●●●● 5/4", _PALETTE.success) in _colored(mock_tk)
|
assert any("above the weekly minimum" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_exact_minimum_is_success(self, mock_tk: MagicMock) -> None:
|
def test_shows_neither_message_at_exact_minimum(self, mock_tk: MagicMock) -> None:
|
||||||
"""At exactly the minimum the week is met: success colour."""
|
"""Shows neither message at exact minimum."""
|
||||||
snap = _snapshot(week=_week(counted_count=4, remaining=0, extra=0))
|
snap = _snapshot(week=_week(counted_count=4, remaining=0, extra=0))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert (g.dots(4, 4), _PALETTE.success) in _colored(mock_tk)
|
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)
|
||||||
|
|
||||||
def test_renders_one_cell_per_day(self, mock_tk: MagicMock) -> None:
|
def test_renders_a_line_per_day(self, mock_tk: MagicMock) -> None:
|
||||||
"""One row, one cell per day in order, no weekday names."""
|
"""Renders a line per day."""
|
||||||
days = (
|
days = (
|
||||||
_day(
|
_day(
|
||||||
date="2024-01-01",
|
date="2024-01-01",
|
||||||
@ -112,8 +106,9 @@ class TestSectionWeek:
|
|||||||
snap = _snapshot(week=_week(days=days))
|
snap = _snapshot(week=_week(days=days))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
texts = _texts(mock_tk)
|
texts = _texts(mock_tk)
|
||||||
assert f"{g.LIFT} {g.WEEK_SICK} {g.WEEK_EMPTY}" in texts
|
assert any("Mon Jan 01" in t and "✓" in t for t in texts)
|
||||||
assert not any("Mon" 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)
|
||||||
|
|
||||||
|
|
||||||
class TestSectionLockExplanation:
|
class TestSectionLockExplanation:
|
||||||
@ -122,11 +117,10 @@ class TestSectionLockExplanation:
|
|||||||
def test_fired_with_auto_upgrade_and_heat_skip_pending(
|
def test_fired_with_auto_upgrade_and_heat_skip_pending(
|
||||||
self, mock_tk: MagicMock
|
self, mock_tk: MagicMock
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Fired: the lock square + stage glyph in danger, and a retry mark."""
|
"""Fired with auto upgrade and heat skip pending."""
|
||||||
snap = _snapshot(
|
snap = _snapshot(
|
||||||
lock_explanation=_lock_explanation(
|
lock_explanation=_lock_explanation(
|
||||||
fired=True,
|
fired=True,
|
||||||
stage="would_lock",
|
|
||||||
reason="Full lock.",
|
reason="Full lock.",
|
||||||
auto_upgrade=AutoUpgradeOpportunity(
|
auto_upgrade=AutoUpgradeOpportunity(
|
||||||
would_attempt=True, via="sick_day", reason="will try phone"
|
would_attempt=True, via="sick_day", reason="will try phone"
|
||||||
@ -135,26 +129,19 @@ class TestSectionLockExplanation:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
colored = _colored(mock_tk)
|
texts = _texts(mock_tk)
|
||||||
assert (f"{g.LOCK} {g.LIFT}", _PALETTE.danger) in colored
|
assert any(t == "Full lock." for t in texts)
|
||||||
assert (g.RETRY, _PALETTE.warning) in colored
|
assert any("Pending auto-upgrade: will try phone" in t for t in texts)
|
||||||
assert "Full lock." not in _texts(mock_tk)
|
|
||||||
|
|
||||||
def test_not_fired_no_auto_upgrade(self, mock_tk: MagicMock) -> None:
|
def test_not_fired_no_auto_upgrade(self, mock_tk: MagicMock) -> None:
|
||||||
"""Not fired: the open square + stage glyph in success, no retry mark."""
|
"""Not fired no auto upgrade."""
|
||||||
snap = _snapshot(
|
snap = _snapshot(
|
||||||
lock_explanation=_lock_explanation(fired=False, reason="Skipped.")
|
lock_explanation=_lock_explanation(fired=False, reason="Skipped.")
|
||||||
)
|
)
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
colored = _colored(mock_tk)
|
texts = _texts(mock_tk)
|
||||||
assert (f"{g.UNLOCK} {g.OK}", _PALETTE.success) in colored
|
assert any(t == "Skipped." for t in texts)
|
||||||
assert (g.RETRY, _PALETTE.warning) not in colored
|
assert not any("Pending auto-upgrade" in t for t in texts)
|
||||||
|
|
||||||
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(
|
def test_temperature_section_renders_regardless_of_heat_skip_evaluated(
|
||||||
self, mock_tk: MagicMock
|
self, mock_tk: MagicMock
|
||||||
@ -165,28 +152,28 @@ class TestSectionLockExplanation:
|
|||||||
lock_explanation=_lock_explanation(fired=True, heat_skip_evaluated=True)
|
lock_explanation=_lock_explanation(fired=True, heat_skip_evaluated=True)
|
||||||
)
|
)
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert any(t.startswith(g.HEAT) for t in _texts(mock_tk))
|
assert any("Warsaw Temperature" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
|
|
||||||
class TestSectionShutdown:
|
class TestSectionShutdown:
|
||||||
"""SectionShutdown."""
|
"""SectionShutdown."""
|
||||||
|
|
||||||
def test_tonight_present_shows_live_config(self, mock_tk: MagicMock) -> None:
|
def test_tonight_present_shows_live_config(self, mock_tk: MagicMock) -> None:
|
||||||
"""Tonight present shows both live times after the shutdown glyph."""
|
"""Tonight present shows live config."""
|
||||||
snap = _snapshot(shutdown=_shutdown(tonight=(1320, 1380, 300)))
|
snap = _snapshot(shutdown=_shutdown(tonight=(1320, 1380, 300)))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert f"{g.SHUTDOWN} 22:00 · 23:00" in _texts(mock_tk)
|
assert any("22:00" in t and "23:00" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_tonight_absent_shows_fail_glyph(self, mock_tk: MagicMock) -> None:
|
def test_tonight_absent_shows_unavailable_message(self, mock_tk: MagicMock) -> None:
|
||||||
"""Tonight absent shows the shutdown glyph crossed out, warning colour."""
|
"""Tonight absent shows unavailable message."""
|
||||||
snap = _snapshot(shutdown=_shutdown(tonight=None))
|
snap = _snapshot(shutdown=_shutdown(tonight=None))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert (f"{g.SHUTDOWN} {g.FAIL}", _PALETTE.warning) in _colored(mock_tk)
|
assert any("Live shutdown config unavailable." in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_shows_rest_of_week_and_next_week_preview(self, mock_tk: MagicMock) -> None:
|
def test_shows_rest_of_week_and_next_week_preview(self, mock_tk: MagicMock) -> None:
|
||||||
"""Rest of week and next week are rows of times, muted, no labels."""
|
"""Shows rest of week and next week preview."""
|
||||||
snap = _snapshot()
|
snap = _snapshot()
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
row = " ".join(["21:00"] * 7)
|
texts = _texts(mock_tk)
|
||||||
assert _colored(mock_tk).count((row, _PALETTE.muted)) == 2
|
assert any("Rest of week:" in t for t in texts)
|
||||||
assert not any("two separate systems" in t for t in _texts(mock_tk))
|
assert any("Next week (speculative):" in t for t in texts)
|
||||||
|
|||||||
@ -5,7 +5,6 @@ from __future__ import annotations
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._status_view_verify import PhoneCheckOutcome
|
from screen_locker._status_view_verify import PhoneCheckOutcome
|
||||||
from screen_locker._workout_credit import WorkoutCreditResult
|
from screen_locker._workout_credit import WorkoutCreditResult
|
||||||
from screen_locker.status_view import (
|
from screen_locker.status_view import (
|
||||||
@ -21,8 +20,6 @@ from screen_locker.tests._status_view_helpers import (
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
class TestPhoneCheckResultRendering:
|
class TestPhoneCheckResultRendering:
|
||||||
"""PhoneCheckResultRendering."""
|
"""PhoneCheckResultRendering."""
|
||||||
@ -31,17 +28,17 @@ class TestPhoneCheckResultRendering:
|
|||||||
"""No result shows nothing."""
|
"""No result shows nothing."""
|
||||||
snap = _snapshot()
|
snap = _snapshot()
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert not any(f"{g.RUN}{g.FAIL}" in t for t in _texts(mock_tk))
|
assert not any("Phone check" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_verified_result_shown_in_green(self, mock_tk: MagicMock) -> None:
|
def test_verified_result_shown_in_green(self, mock_tk: MagicMock) -> None:
|
||||||
"""Verified result shown in green."""
|
"""Verified result shown in green."""
|
||||||
window = _make_window(mock_tk, _snapshot())
|
window = _make_window(mock_tk, _snapshot())
|
||||||
window._phone_check_result = ("verified", "verified glyphs")
|
window._phone_check_result = ("verified", "Workout verified!")
|
||||||
window.render(_snapshot())
|
window.render(_snapshot())
|
||||||
calls = [
|
calls = [
|
||||||
c
|
c
|
||||||
for c in mock_tk.Label.call_args_list
|
for c in mock_tk.Label.call_args_list
|
||||||
if c.kwargs.get("text") == "verified glyphs"
|
if "Phone check" in c.kwargs.get("text", "")
|
||||||
]
|
]
|
||||||
assert calls
|
assert calls
|
||||||
assert calls[-1].kwargs.get("fg") == window._colors.palette.success
|
assert calls[-1].kwargs.get("fg") == window._colors.palette.success
|
||||||
@ -49,11 +46,12 @@ class TestPhoneCheckResultRendering:
|
|||||||
def test_non_verified_result_shown_in_orange(self, mock_tk: MagicMock) -> None:
|
def test_non_verified_result_shown_in_orange(self, mock_tk: MagicMock) -> None:
|
||||||
"""Non verified result shown in orange."""
|
"""Non verified result shown in orange."""
|
||||||
window = _make_window(mock_tk, _snapshot())
|
window = _make_window(mock_tk, _snapshot())
|
||||||
failed = f"{g.LIFT}{g.FAIL} {g.RUN}{g.FAIL}"
|
window._phone_check_result = ("no_phone", "Phone not connected")
|
||||||
window._phone_check_result = ("no_phone", failed)
|
|
||||||
window.render(_snapshot())
|
window.render(_snapshot())
|
||||||
calls = [
|
calls = [
|
||||||
c for c in mock_tk.Label.call_args_list if c.kwargs.get("text") == failed
|
c
|
||||||
|
for c in mock_tk.Label.call_args_list
|
||||||
|
if "Phone check" in c.kwargs.get("text", "")
|
||||||
]
|
]
|
||||||
assert calls
|
assert calls
|
||||||
assert calls[-1].kwargs.get("fg") == window._colors.palette.warning
|
assert calls[-1].kwargs.get("fg") == window._colors.palette.warning
|
||||||
@ -67,7 +65,12 @@ class TestButtons:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Renders check phone refresh close."""
|
"""Renders check phone refresh close."""
|
||||||
_make_window(mock_tk, _snapshot(), log_file=temp_log_file)
|
_make_window(mock_tk, _snapshot(), log_file=temp_log_file)
|
||||||
assert _button_texts(mock_tk) == {g.PHONE, g.FORM, g.RETRY, g.CLOSE}
|
assert _button_texts(mock_tk) == {
|
||||||
|
"Check Phone",
|
||||||
|
"Log Manual Workout",
|
||||||
|
"Refresh",
|
||||||
|
"Close",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class TestRefreshAndCheckPhoneFlow:
|
class TestRefreshAndCheckPhoneFlow:
|
||||||
@ -121,9 +124,9 @@ class TestRefreshAndCheckPhoneFlow:
|
|||||||
mock_handle.assert_not_called()
|
mock_handle.assert_not_called()
|
||||||
|
|
||||||
def test_failed_check_shows_combined_message_and_rerenders(
|
def test_failed_check_shows_combined_message_and_rerenders(
|
||||||
self, mock_tk: MagicMock, caplog: pytest.LogCaptureFixture
|
self, mock_tk: MagicMock
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Neither source verified → both fail glyphs, both reasons logged."""
|
"""Neither source verified → show both messages, apply no credit."""
|
||||||
window = _make_window(mock_tk, _snapshot())
|
window = _make_window(mock_tk, _snapshot())
|
||||||
with patch(
|
with patch(
|
||||||
"screen_locker._status_view_verify.gather_status", return_value=_snapshot()
|
"screen_locker._status_view_verify.gather_status", return_value=_snapshot()
|
||||||
@ -133,10 +136,8 @@ class TestRefreshAndCheckPhoneFlow:
|
|||||||
)
|
)
|
||||||
assert window._phone_check_result == (
|
assert window._phone_check_result == (
|
||||||
"no_phone",
|
"no_phone",
|
||||||
f"{g.LIFT}{g.FAIL} {g.RUN}{g.FAIL}",
|
"StrongLifts: no lifts · RunnerUp: no run",
|
||||||
)
|
)
|
||||||
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
|
assert window._credit_message is None
|
||||||
mock_gather.assert_called_once()
|
mock_gather.assert_called_once()
|
||||||
|
|
||||||
@ -173,7 +174,8 @@ class TestRefreshAndCheckPhoneFlow:
|
|||||||
assert window._phone_check_result is None
|
assert window._phone_check_result is None
|
||||||
message = window._credit_message
|
message = window._credit_message
|
||||||
assert message is not None
|
assert message is not None
|
||||||
assert message.splitlines() == [f"{g.LIFT} {g.OK}", f"{g.SHUTDOWN} +2h"]
|
assert "StrongLifts verified: StrongLifts ok" in message
|
||||||
|
assert "Shutdown time +2h later!" in message
|
||||||
|
|
||||||
def test_runnerup_verified_credits_using_runnerup_message(
|
def test_runnerup_verified_credits_using_runnerup_message(
|
||||||
self, mock_tk: MagicMock, temp_log_file: Path
|
self, mock_tk: MagicMock, temp_log_file: Path
|
||||||
@ -208,7 +210,7 @@ class TestRefreshAndCheckPhoneFlow:
|
|||||||
}
|
}
|
||||||
message = window._credit_message
|
message = window._credit_message
|
||||||
assert message is not None
|
assert message is not None
|
||||||
assert message == f"{g.RUN} {g.OK}"
|
assert "RunnerUp verified: RunnerUp 5.0 km" in message
|
||||||
|
|
||||||
|
|
||||||
class TestMakeBareVerifier:
|
class TestMakeBareVerifier:
|
||||||
|
|||||||
@ -6,7 +6,6 @@ from unittest.mock import MagicMock, patch
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._status_view_verify import (
|
from screen_locker._status_view_verify import (
|
||||||
_backfill_week_and_apply_bonus,
|
_backfill_week_and_apply_bonus,
|
||||||
)
|
)
|
||||||
@ -47,7 +46,7 @@ class TestBackfillWeekAndApplyBonus:
|
|||||||
):
|
):
|
||||||
message = _backfill_week_and_apply_bonus(verifier)
|
message = _backfill_week_and_apply_bonus(verifier)
|
||||||
|
|
||||||
assert message == f"{g.RETRY}{g.LIFT} +1"
|
assert message == "Auto-filled 1 workout from earlier this week."
|
||||||
verifier._scan_and_fill_week_runnerup.assert_called_once_with(
|
verifier._scan_and_fill_week_runnerup.assert_called_once_with(
|
||||||
verifier.log_file, on_ingested=verifier._credit_ingested_workout
|
verifier.log_file, on_ingested=verifier._credit_ingested_workout
|
||||||
)
|
)
|
||||||
@ -66,7 +65,9 @@ class TestBackfillWeekAndApplyBonus:
|
|||||||
message = _backfill_week_and_apply_bonus(verifier)
|
message = _backfill_week_and_apply_bonus(verifier)
|
||||||
|
|
||||||
# prev 4 + 1 RunnerUp fill already credited = 5; 7 - 5 = 2 surplus.
|
# prev 4 + 1 RunnerUp fill already credited = 5; 7 - 5 = 2 surplus.
|
||||||
assert message == f"{g.RETRY}{g.LIFT} +2 {g.SHUTDOWN} +2h"
|
assert message == (
|
||||||
|
"Auto-filled 2 workouts from earlier this week. +2h shutdown time."
|
||||||
|
)
|
||||||
verifier._adjust_shutdown_time_by.assert_called_once_with(120)
|
verifier._adjust_shutdown_time_by.assert_called_once_with(120)
|
||||||
|
|
||||||
def test_stronglifts_fill_below_minimum_earns_no_surplus(self) -> None:
|
def test_stronglifts_fill_below_minimum_earns_no_surplus(self) -> None:
|
||||||
@ -81,5 +82,5 @@ class TestBackfillWeekAndApplyBonus:
|
|||||||
):
|
):
|
||||||
message = _backfill_week_and_apply_bonus(verifier)
|
message = _backfill_week_and_apply_bonus(verifier)
|
||||||
|
|
||||||
assert message == f"{g.RETRY}{g.LIFT} +1"
|
assert message == "Auto-filled 1 workout from earlier this week."
|
||||||
verifier._adjust_shutdown_time_by.assert_not_called()
|
verifier._adjust_shutdown_time_by.assert_not_called()
|
||||||
|
|||||||
@ -4,7 +4,6 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker._status_view_verify import (
|
from screen_locker._status_view_verify import (
|
||||||
PhoneCheckOutcome,
|
PhoneCheckOutcome,
|
||||||
_verify_phone_then_runnerup,
|
_verify_phone_then_runnerup,
|
||||||
@ -69,6 +68,8 @@ class TestVerifyPhoneThenRunnerup:
|
|||||||
result = _verify_phone_then_runnerup(verifier)
|
result = _verify_phone_then_runnerup(verifier)
|
||||||
|
|
||||||
assert result.credited_type is None
|
assert result.credited_type is None
|
||||||
assert result.week_fill_message == f"{g.RETRY}{g.LIFT} +1"
|
assert (
|
||||||
|
result.week_fill_message == "Auto-filled 1 workout from earlier this week."
|
||||||
|
)
|
||||||
# The RunnerUp fill is credited by the shared callback, not here.
|
# The RunnerUp fill is credited by the shared callback, not here.
|
||||||
verifier._adjust_shutdown_time_by.assert_not_called()
|
verifier._adjust_shutdown_time_by.assert_not_called()
|
||||||
|
|||||||
@ -5,7 +5,6 @@ from __future__ import annotations
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from screen_locker import _glyphs as g
|
|
||||||
from screen_locker.status_view import (
|
from screen_locker.status_view import (
|
||||||
StatusWindow,
|
StatusWindow,
|
||||||
main,
|
main,
|
||||||
@ -94,21 +93,21 @@ class TestTemperatureSectionRendering:
|
|||||||
window = _make_window(mock_tk, _snapshot())
|
window = _make_window(mock_tk, _snapshot())
|
||||||
window._temp_result = None
|
window._temp_result = None
|
||||||
window.render(_snapshot())
|
window.render(_snapshot())
|
||||||
assert f"{g.HEAT} {g.WAIT}" in _texts(mock_tk)
|
assert any("Checking Warsaw temperature" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_shows_resolved_temperature(self, mock_tk: MagicMock) -> None:
|
def test_shows_resolved_temperature(self, mock_tk: MagicMock) -> None:
|
||||||
"""Shows resolved temperature."""
|
"""Shows resolved temperature."""
|
||||||
window = _make_window(mock_tk, _snapshot())
|
window = _make_window(mock_tk, _snapshot())
|
||||||
window._temp_result = _temp_check(temp_celsius=22.0)
|
window._temp_result = _temp_check(temp_celsius=22.0)
|
||||||
window.render(_snapshot())
|
window.render(_snapshot())
|
||||||
assert f"{g.HEAT} 22°C < 33°C" in _texts(mock_tk)
|
assert any("Warsaw: 22" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_flags_would_trigger_heat_skip_when_hot(self, mock_tk: MagicMock) -> None:
|
def test_flags_would_trigger_heat_skip_when_hot(self, mock_tk: MagicMock) -> None:
|
||||||
"""Flags would trigger heat skip when hot."""
|
"""Flags would trigger heat skip when hot."""
|
||||||
window = _make_window(mock_tk, _snapshot())
|
window = _make_window(mock_tk, _snapshot())
|
||||||
window._temp_result = _temp_check(temp_celsius=35.0)
|
window._temp_result = _temp_check(temp_celsius=35.0)
|
||||||
window.render(_snapshot())
|
window.render(_snapshot())
|
||||||
assert f"{g.HEAT} 35°C ≥ 33°C {g.SKIP}" in _texts(mock_tk)
|
assert any("Would trigger heat-skip today." in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_does_not_flag_heat_skip_when_below_threshold(
|
def test_does_not_flag_heat_skip_when_below_threshold(
|
||||||
self, mock_tk: MagicMock
|
self, mock_tk: MagicMock
|
||||||
@ -117,28 +116,21 @@ class TestTemperatureSectionRendering:
|
|||||||
window = _make_window(mock_tk, _snapshot())
|
window = _make_window(mock_tk, _snapshot())
|
||||||
window._temp_result = _temp_check(temp_celsius=22.0)
|
window._temp_result = _temp_check(temp_celsius=22.0)
|
||||||
window.render(_snapshot())
|
window.render(_snapshot())
|
||||||
assert not any(g.SKIP in t for t in _texts(mock_tk) if t.startswith(g.HEAT))
|
assert not any("Would trigger heat-skip today." in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_shows_timeout_message(
|
def test_shows_timeout_message(self, mock_tk: MagicMock) -> None:
|
||||||
self, mock_tk: MagicMock, caplog: pytest.LogCaptureFixture
|
"""Shows timeout message."""
|
||||||
) -> None:
|
|
||||||
"""A timeout shows the clock-fail glyph and logs the timeout."""
|
|
||||||
window = _make_window(mock_tk, _snapshot())
|
window = _make_window(mock_tk, _snapshot())
|
||||||
window._temp_result = _temp_check(temp_celsius=None, timed_out=True)
|
window._temp_result = _temp_check(temp_celsius=None, timed_out=True)
|
||||||
window.render(_snapshot())
|
window.render(_snapshot())
|
||||||
assert f"{g.HEAT} {g.CLOCK}{g.FAIL}" in _texts(mock_tk)
|
assert any("timed out" in t for t 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:
|
def test_shows_failure_message_when_not_timed_out(self, mock_tk: MagicMock) -> None:
|
||||||
"""Shows failure message when not timed out."""
|
"""Shows failure message when not timed out."""
|
||||||
window = _make_window(mock_tk, _snapshot())
|
window = _make_window(mock_tk, _snapshot())
|
||||||
window._temp_result = _temp_check(temp_celsius=None, timed_out=False)
|
window._temp_result = _temp_check(temp_celsius=None, timed_out=False)
|
||||||
window.render(_snapshot())
|
window.render(_snapshot())
|
||||||
assert f"{g.HEAT} {g.FAIL}" in _texts(mock_tk)
|
assert any("failed (network/API error)" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
|
|
||||||
class TestTemperatureCheckFlow:
|
class TestTemperatureCheckFlow:
|
||||||
|
|||||||
@ -1,146 +0,0 @@
|
|||||||
"""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(())
|
|
||||||
@ -5,7 +5,6 @@ from __future__ import annotations
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
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._compliance_predicates import is_relaxed_day_skipped_today
|
||||||
from screen_locker.tests.conftest import (
|
from screen_locker.tests.conftest import (
|
||||||
create_locker,
|
create_locker,
|
||||||
@ -70,7 +69,9 @@ class TestStartRelaxedDayFlow:
|
|||||||
locker._start_relaxed_day_flow()
|
locker._start_relaxed_day_flow()
|
||||||
|
|
||||||
skip_cmds = [
|
skip_cmds = [
|
||||||
c.kwargs["command"] for c in mock_button.call_args_list if g.SKIP in c.args
|
c.kwargs["command"]
|
||||||
|
for c in mock_button.call_args_list
|
||||||
|
if "Skip" in str(c.args)
|
||||||
]
|
]
|
||||||
assert locker._skip_relaxed_day in skip_cmds
|
assert locker._skip_relaxed_day in skip_cmds
|
||||||
|
|
||||||
@ -119,7 +120,7 @@ class TestStartRelaxedDayFlow:
|
|||||||
log_cmds = [
|
log_cmds = [
|
||||||
c.kwargs["command"]
|
c.kwargs["command"]
|
||||||
for c in mock_button.call_args_list
|
for c in mock_button.call_args_list
|
||||||
if f"{g.GO} {g.LIFT}" in c.args
|
if "Log" in str(c.args)
|
||||||
]
|
]
|
||||||
assert locker._start_relaxed_phone_check in log_cmds
|
assert locker._start_relaxed_phone_check in log_cmds
|
||||||
|
|
||||||
@ -232,5 +233,5 @@ class TestHandleRelaxedPhoneResult:
|
|||||||
button_texts = {
|
button_texts = {
|
||||||
call.kwargs.get("text") for call in mock_tk.Button.call_args_list
|
call.kwargs.get("text") for call in mock_tk.Button.call_args_list
|
||||||
}
|
}
|
||||||
assert g.RETRY in button_texts
|
assert "TRY AGAIN" in button_texts
|
||||||
assert g.SKIP in button_texts
|
assert "Close (Skip)" in button_texts
|
||||||
|
|||||||
@ -34,7 +34,7 @@ class TestRelaxedDayAlreadySkippedBranch:
|
|||||||
# script_dir.parent/"log.json" resolves to tmp_path/"log.json" -- NOT
|
# script_dir.parent/"log.json" resolves to tmp_path/"log.json" -- NOT
|
||||||
# tmp_path/"screen_locker"/"log.json".
|
# tmp_path/"screen_locker"/"log.json".
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
|
today = datetime.now(tz=UTC).strftime("%Y-%m-%d")
|
||||||
write_signed_entry(log_file, today, {"type": "relaxed_day_skip"})
|
write_signed_entry(log_file, today, {"type": "relaxed_day_skip"})
|
||||||
|
|
||||||
with (
|
with (
|
||||||
|
|||||||
@ -1,20 +0,0 @@
|
|||||||
"""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))
|
|
||||||
@ -1,85 +0,0 @@
|
|||||||
"""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),
|
|
||||||
]
|
|
||||||
@ -56,21 +56,19 @@ class _DemoHooks:
|
|||||||
|
|
||||||
def build_surface(self, parent: tk.Misc, _surface: object) -> None:
|
def build_surface(self, parent: tk.Misc, _surface: object) -> None:
|
||||||
"""Draw the status line and the release/reacquire buttons."""
|
"""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(
|
tk.Label(
|
||||||
parent,
|
parent,
|
||||||
text="▣",
|
text="DEMO LOCK — local grab, VT switching still enabled",
|
||||||
font=("TkDefaultFont", 18, "bold"),
|
font=("TkDefaultFont", 18, "bold"),
|
||||||
bg="#1B1D21",
|
bg="#1B1D21",
|
||||||
fg="#E6E6E6",
|
fg="#E6E6E6",
|
||||||
).pack(pady=(120, 8))
|
).pack(pady=(120, 8))
|
||||||
self.status = tk.Label(
|
self.status = tk.Label(
|
||||||
parent,
|
parent,
|
||||||
text="Ctrl+Shift+Q",
|
text=(
|
||||||
|
"Press “Start workout”. While the app holds the screen, "
|
||||||
|
"press Ctrl+Shift+Q to escape."
|
||||||
|
),
|
||||||
font=("TkDefaultFont", 12),
|
font=("TkDefaultFont", 12),
|
||||||
bg="#1B1D21",
|
bg="#1B1D21",
|
||||||
fg="#9AA0A6",
|
fg="#9AA0A6",
|
||||||
@ -78,7 +76,7 @@ class _DemoHooks:
|
|||||||
self.status.pack(pady=8)
|
self.status.pack(pady=8)
|
||||||
tk.Button(
|
tk.Button(
|
||||||
parent,
|
parent,
|
||||||
text="▶",
|
text="Start workout",
|
||||||
font=("TkDefaultFont", 14, "bold"),
|
font=("TkDefaultFont", 14, "bold"),
|
||||||
bg="#3B82F6",
|
bg="#3B82F6",
|
||||||
fg="#FFFFFF",
|
fg="#FFFFFF",
|
||||||
@ -88,7 +86,7 @@ class _DemoHooks:
|
|||||||
).pack(pady=16)
|
).pack(pady=16)
|
||||||
tk.Button(
|
tk.Button(
|
||||||
parent,
|
parent,
|
||||||
text="✕",
|
text="✕ Close demo (or press Escape)",
|
||||||
bg="#EF4444",
|
bg="#EF4444",
|
||||||
fg="#FFFFFF",
|
fg="#FFFFFF",
|
||||||
command=self._close,
|
command=self._close,
|
||||||
@ -130,7 +128,7 @@ def main() -> int:
|
|||||||
if workout_app_binary() is None:
|
if workout_app_binary() is None:
|
||||||
return 1
|
return 1
|
||||||
root = tk.Tk()
|
root = tk.Tk()
|
||||||
root.title("")
|
root.title("Workout handoff demo")
|
||||||
# Local grab + VT switching enabled: every escape hatch stays open.
|
# Local grab + VT switching enabled: every escape hatch stays open.
|
||||||
config = LockConfig(mode="hard", grab=GrabPolicy(kind="local", disable_vt=False))
|
config = LockConfig(mode="hard", grab=GrabPolicy(kind="local", disable_vt=False))
|
||||||
hooks = _DemoHooks()
|
hooks = _DemoHooks()
|
||||||
|
|||||||
@ -31,7 +31,7 @@ from typing import TYPE_CHECKING
|
|||||||
|
|
||||||
from gatelock import LockConfig, measure_fit, report_fit
|
from gatelock import LockConfig, measure_fit, report_fit
|
||||||
|
|
||||||
from screen_locker._manual_workout_date import REJECTED_GLYPH
|
from screen_locker._constants import MANUAL_WORKOUT_REFLECTION_MIN_CHARS
|
||||||
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
|
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
|
||||||
from screen_locker._surface_group import FrameGroup
|
from screen_locker._surface_group import FrameGroup
|
||||||
from screen_locker._ui_flows import UIFlowsMixin
|
from screen_locker._ui_flows import UIFlowsMixin
|
||||||
@ -147,7 +147,12 @@ class ScreenHost(
|
|||||||
not fitting.
|
not fitting.
|
||||||
"""
|
"""
|
||||||
self._show_manual_workout_form()
|
self._show_manual_workout_form()
|
||||||
self._mw_error_label.config(text=REJECTED_GLYPH)
|
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."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
def paint_sick_refused(self) -> None:
|
def paint_sick_refused(self) -> None:
|
||||||
"""Paint the screen shown when today cannot be marked sick."""
|
"""Paint the screen shown when today cannot be marked sick."""
|
||||||
|
|||||||
@ -1,140 +0,0 @@
|
|||||||
#!/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())
|
|
||||||
@ -192,8 +192,7 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return MaterialApp(
|
return MaterialApp(
|
||||||
// textgate: no title. Was 'Workout Tracker'; the recents card shows
|
title: 'Workout Tracker',
|
||||||
// the launcher icon and the manifest label (android:label) already.
|
|
||||||
debugShowCheckedModeBanner: false,
|
debugShowCheckedModeBanner: false,
|
||||||
theme: buildAppTheme(),
|
theme: buildAppTheme(),
|
||||||
home: const HomeScreen(),
|
home: const HomeScreen(),
|
||||||
@ -201,8 +200,7 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
|
|||||||
// ribbon on every screen, in the error colour, on the sandbox only.
|
// ribbon on every screen, in the error colour, on the sandbox only.
|
||||||
builder: (context, child) => Sandbox.enabled
|
builder: (context, child) => Sandbox.enabled
|
||||||
? Banner(
|
? Banner(
|
||||||
// Was 'SANDBOX': the red corner ribbon alone marks it.
|
message: 'SANDBOX',
|
||||||
message: '',
|
|
||||||
location: BannerLocation.topEnd,
|
location: BannerLocation.topEnd,
|
||||||
color: Theme.of(context).colorScheme.error,
|
color: Theme.of(context).colorScheme.error,
|
||||||
child: child,
|
child: child,
|
||||||
|
|||||||
@ -200,10 +200,23 @@ DateTime? parsePauseDate(Object? raw) {
|
|||||||
return parsed;
|
return parsed;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `11.10`: how a pause's end date is shown (textgate: numerals, no month
|
const _months = [
|
||||||
/// word; was `11 Oct`).
|
'Jan',
|
||||||
String formatShortDate(DateTime d) =>
|
'Feb',
|
||||||
'${d.day}.${d.month.toString().padLeft(2, '0')}';
|
'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]}';
|
||||||
|
|
||||||
/// `3:00`: how a rest length is shown.
|
/// `3:00`: how a rest length is shown.
|
||||||
String formatRest(int secs) =>
|
String formatRest(int secs) =>
|
||||||
|
|||||||
@ -125,19 +125,15 @@ ProgressionTarget targetAfterFailure(ProgressionInputs s) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What [describeTargetChange] returns when the rule has nowhere to go.
|
/// Short label for moving from [from] to [to]: `25 kg`, `13 reps`,
|
||||||
const kNoTargetChange = '=';
|
/// `25 kg × 6`, or `same` when the rule has nowhere left to go.
|
||||||
|
|
||||||
/// 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) {
|
String describeTargetChange(ProgressionInputs from, ProgressionTarget to) {
|
||||||
final weightChanged = to.weight != from.weight;
|
final weightChanged = to.weight != from.weight;
|
||||||
final repsChanged = to.reps != from.reps;
|
final repsChanged = to.reps != from.reps;
|
||||||
if (weightChanged && repsChanged) return '${_kg(to.weight)} kg × ${to.reps}';
|
if (weightChanged && repsChanged) return '${_kg(to.weight)} kg × ${to.reps}';
|
||||||
if (weightChanged) return '${_kg(to.weight)} kg';
|
if (weightChanged) return '${_kg(to.weight)} kg';
|
||||||
if (repsChanged) return '×${to.reps}';
|
if (repsChanged) return '${to.reps} reps';
|
||||||
return kNoTargetChange;
|
return 'same';
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `25` for 25.0, `27.5` for 27.5 — no trailing `.0` noise in tight rows.
|
/// `25` for 25.0, `27.5` for 27.5 — no trailing `.0` noise in tight rows.
|
||||||
|
|||||||
@ -198,11 +198,9 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
|||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||||
// textgate: was "Advanced sync (GitHub)".
|
title: Text(
|
||||||
title: Icon(
|
'Advanced sync (GitHub)',
|
||||||
Icons.code,
|
style: TextStyle(color: colorScheme.onSurface),
|
||||||
color: colorScheme.onSurface,
|
|
||||||
semanticLabel: 'Advanced sync (GitHub)',
|
|
||||||
),
|
),
|
||||||
iconTheme: IconThemeData(color: colorScheme.onSurface),
|
iconTheme: IconThemeData(color: colorScheme.onSurface),
|
||||||
),
|
),
|
||||||
@ -211,20 +209,25 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
|||||||
: ListView(
|
: ListView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: [
|
children: [
|
||||||
// textgate: the explanation sentence above is gone.
|
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),
|
||||||
if (_syncStatus != null) ...[
|
if (_syncStatus != null) ...[
|
||||||
_SyncStatusBadge(text: _syncStatus!, kind: _syncStatusKind),
|
_SyncStatusBadge(text: _syncStatus!, kind: _syncStatusKind),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
],
|
],
|
||||||
Align(
|
Align(
|
||||||
alignment: Alignment.centerLeft,
|
alignment: Alignment.centerLeft,
|
||||||
child: ElevatedButton(
|
child: ElevatedButton.icon(
|
||||||
onPressed: _connectGitHub,
|
onPressed: _connectGitHub,
|
||||||
child: const Icon(
|
icon: const Icon(Icons.login),
|
||||||
Icons.login,
|
label: const Text('Connect GitHub'),
|
||||||
size: 20,
|
|
||||||
semanticLabel: 'Connect GitHub',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
|
|||||||
@ -19,12 +19,6 @@ class _SyncStatusBadge extends StatelessWidget {
|
|||||||
_SyncStatusKind.error => colorScheme.error,
|
_SyncStatusKind.error => colorScheme.error,
|
||||||
_SyncStatusKind.pending => colorScheme.onSurfaceVariant,
|
_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(
|
return Container(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
@ -48,6 +42,17 @@ class _SyncStatusBadge extends StatelessWidget {
|
|||||||
color: color,
|
color: color,
|
||||||
size: 16,
|
size: 16,
|
||||||
),
|
),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
text,
|
||||||
|
style: TextStyle(
|
||||||
|
color: color,
|
||||||
|
fontSize: AppTextSize.label,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@ -75,23 +80,17 @@ class _SyncTokenField extends StatelessWidget {
|
|||||||
// inputDecorationTheme (theme.dart) — only the field-specific
|
// inputDecorationTheme (theme.dart) — only the field-specific
|
||||||
// hint/padding need setting here.
|
// hint/padding need setting here.
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
|
hintText: 'GitHub PAT',
|
||||||
hintStyle: TextStyle(color: colorScheme.onSurfaceVariant),
|
hintStyle: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
contentPadding: const EdgeInsets.symmetric(
|
contentPadding: const EdgeInsets.symmetric(
|
||||||
horizontal: 12,
|
horizontal: 12,
|
||||||
vertical: 10,
|
vertical: 10,
|
||||||
),
|
),
|
||||||
prefixIcon: const Icon(
|
|
||||||
Icons.vpn_key,
|
|
||||||
semanticLabel: 'GitHub PAT',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
ElevatedButton(
|
ElevatedButton(onPressed: onSave, child: const Text('Save')),
|
||||||
onPressed: onSave,
|
|
||||||
child: const Icon(Icons.save, semanticLabel: 'Save'),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -141,17 +140,19 @@ class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
|
|||||||
final colorScheme = Theme.of(context).colorScheme;
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
return AlertDialog(
|
return AlertDialog(
|
||||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||||
// Was "Authorize on GitHub" / "Enter this code on GitHub:" /
|
title: Text(
|
||||||
// "Waiting for authorization…": key glyph, the code, a spinner.
|
'Authorize on GitHub',
|
||||||
title: Icon(
|
style: TextStyle(color: colorScheme.onSurface),
|
||||||
Icons.vpn_key,
|
|
||||||
color: colorScheme.onSurface,
|
|
||||||
semanticLabel: 'Authorize on GitHub',
|
|
||||||
),
|
),
|
||||||
content: Column(
|
content: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
|
Text(
|
||||||
|
'Enter this code on GitHub:',
|
||||||
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
SelectableText(
|
SelectableText(
|
||||||
widget.device.userCode,
|
widget.device.userCode,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
@ -162,39 +163,38 @@ class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
if (_error == null)
|
if (_error == null)
|
||||||
const SizedBox(
|
Row(
|
||||||
width: 16,
|
children: [
|
||||||
height: 16,
|
const SizedBox(
|
||||||
child: CircularProgressIndicator(
|
width: 16,
|
||||||
strokeWidth: 2,
|
height: 16,
|
||||||
semanticsLabel: 'Waiting for authorization…',
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
),
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
'Waiting for authorization…',
|
||||||
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
// textgate: the failure is spoken only.
|
Text(_error!, style: TextStyle(color: colorScheme.error)),
|
||||||
Icon(
|
|
||||||
Icons.error_outline,
|
|
||||||
color: colorScheme.error,
|
|
||||||
semanticLabel: _error,
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
child: Icon(
|
child: Text(
|
||||||
Icons.close,
|
'Cancel',
|
||||||
color: colorScheme.onSurfaceVariant,
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
semanticLabel: 'Cancel',
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
// Was "Open GitHub & copy code".
|
FilledButton.icon(
|
||||||
FilledButton(
|
|
||||||
onPressed: _openPage,
|
onPressed: _openPage,
|
||||||
child: const Icon(
|
icon: const Icon(Icons.open_in_new),
|
||||||
Icons.open_in_new,
|
label: const Text('Open GitHub & copy code'),
|
||||||
semanticLabel: 'Open GitHub & copy code',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -6,7 +6,6 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:developer' as developer;
|
|
||||||
import 'dart:math';
|
import 'dart:math';
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
@ -162,7 +161,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||||
title: const Icon(Icons.timeline, size: 20, semanticLabel: 'Progress'),
|
title: Text('Progress', style: TextStyle(color: colorScheme.onSurface)),
|
||||||
iconTheme: IconThemeData(color: colorScheme.onSurface),
|
iconTheme: IconThemeData(color: colorScheme.onSurface),
|
||||||
),
|
),
|
||||||
body: _loading
|
body: _loading
|
||||||
@ -173,7 +172,12 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
_syncedRows.isEmpty &&
|
_syncedRows.isEmpty &&
|
||||||
_plannedRows.isEmpty &&
|
_plannedRows.isEmpty &&
|
||||||
_runs.isEmpty
|
_runs.isEmpty
|
||||||
? const _EmptyHistory()
|
? Center(
|
||||||
|
child: Text(
|
||||||
|
'No workouts yet.',
|
||||||
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
|
),
|
||||||
|
)
|
||||||
: ListView(
|
: ListView(
|
||||||
padding: const EdgeInsets.all(12),
|
padding: const EdgeInsets.all(12),
|
||||||
children: [
|
children: [
|
||||||
@ -205,21 +209,18 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
_RunsStrip(runs: _runs, onOpen: _openRun),
|
_RunsStrip(runs: _runs, onOpen: _openRun),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
],
|
],
|
||||||
const _SectionLabel(
|
const _SectionLabel('TOTAL VOLUME (2-session rolling avg, kg)'),
|
||||||
Icons.stacked_line_chart,
|
|
||||||
'TOTAL VOLUME (2-session rolling avg, kg)',
|
|
||||||
),
|
|
||||||
const SizedBox(height: 6),
|
const SizedBox(height: 6),
|
||||||
_WeightChart(points: _rollingAvg2(_totalVolumePoints(_rows))),
|
_WeightChart(points: _rollingAvg2(_totalVolumePoints(_rows))),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
_calendar(_allWorkoutDates(_rows, _syncedRows, _runs)),
|
_calendar(_allWorkoutDates(_rows, _syncedRows, _runs)),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
const _SectionLabel(Icons.list, 'ALL SESSIONS'),
|
const _SectionLabel('ALL SESSIONS'),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
..._rows.map((row) => _AllSessionTile(row: row)),
|
..._rows.map((row) => _AllSessionTile(row: row)),
|
||||||
if (_syncedRows.isNotEmpty) ...[
|
if (_syncedRows.isNotEmpty) ...[
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
const _SectionLabel(Icons.computer, 'SYNCED FROM PC'),
|
const _SectionLabel('SYNCED FROM PC'),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
..._syncedRows.map((row) => _SyncedWorkoutTile(payload: row)),
|
..._syncedRows.map((row) => _SyncedWorkoutTile(payload: row)),
|
||||||
],
|
],
|
||||||
@ -230,14 +231,13 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
_ProgressStatsCard(state: _selectedState!),
|
_ProgressStatsCard(state: _selectedState!),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
],
|
],
|
||||||
const _SectionLabel(Icons.show_chart, 'WEIGHT OVER TIME'),
|
const _SectionLabel('WEIGHT OVER TIME'),
|
||||||
const SizedBox(height: 6),
|
const SizedBox(height: 6),
|
||||||
_WeightChart(points: _exerciseWeightPoints(_rows, name)),
|
_WeightChart(points: _exerciseWeightPoints(_rows, name)),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
_calendar(_exerciseDates(_rows, name)),
|
_calendar(_exerciseDates(_rows, name)),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
// The picker above already names the exercise: a list glyph here.
|
_SectionLabel(name.toUpperCase()),
|
||||||
_SectionLabel(Icons.list, name),
|
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
..._sessionsForExercise(
|
..._sessionsForExercise(
|
||||||
_rows,
|
_rows,
|
||||||
|
|||||||
@ -7,44 +7,24 @@ part of 'history_screen.dart';
|
|||||||
|
|
||||||
// ── Shared sub-widgets ──────────────────────────────────────────────────────
|
// ── 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 {
|
class _SectionLabel extends StatelessWidget {
|
||||||
const _SectionLabel(this.icon, this.spoken);
|
const _SectionLabel(this.text);
|
||||||
|
|
||||||
final IconData icon;
|
final String text;
|
||||||
final String spoken;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Align(
|
return Text(
|
||||||
alignment: Alignment.centerLeft,
|
text,
|
||||||
child: Icon(
|
style: TextStyle(
|
||||||
icon,
|
|
||||||
size: 18,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
semanticLabel: spoken,
|
fontSize: AppTextSize.caption,
|
||||||
|
letterSpacing: 1.3,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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 {
|
class _ExercisePicker extends StatelessWidget {
|
||||||
const _ExercisePicker({
|
const _ExercisePicker({
|
||||||
required this.names,
|
required this.names,
|
||||||
@ -69,18 +49,15 @@ class _ExercisePicker extends StatelessWidget {
|
|||||||
.map(
|
.map(
|
||||||
(n) => DropdownMenuItem(
|
(n) => DropdownMenuItem(
|
||||||
value: n,
|
value: n,
|
||||||
// textgate: the all-workouts entry is a sum glyph (was
|
child: Text(
|
||||||
// "Total (all workouts)"); exercise names are content.
|
n,
|
||||||
child: n == _kTotal
|
style: TextStyle(
|
||||||
? Align(
|
color: n == _kTotal
|
||||||
alignment: Alignment.centerLeft,
|
? colorScheme.onSurfaceVariant
|
||||||
child: Icon(
|
: colorScheme.onSurface,
|
||||||
Icons.functions,
|
fontStyle: n == _kTotal ? FontStyle.italic : FontStyle.normal,
|
||||||
color: colorScheme.onSurfaceVariant,
|
),
|
||||||
semanticLabel: _kTotal,
|
),
|
||||||
),
|
|
||||||
)
|
|
||||||
: Text(n, style: TextStyle(color: colorScheme.onSurface)),
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.toList(),
|
.toList(),
|
||||||
@ -185,8 +162,7 @@ class _StreakRow extends StatelessWidget {
|
|||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Text(
|
||||||
// textgate: was "2 more to ↑ 25 kg".
|
'${threshold - shown} more to $direction $actionLabel',
|
||||||
'${threshold - shown} $direction $actionLabel',
|
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: colorScheme.onSurfaceVariant,
|
color: colorScheme.onSurfaceVariant,
|
||||||
fontSize: AppTextSize.caption,
|
fontSize: AppTextSize.caption,
|
||||||
@ -211,11 +187,9 @@ class _WeightChart extends StatelessWidget {
|
|||||||
return Container(
|
return Container(
|
||||||
height: 80,
|
height: 80,
|
||||||
alignment: Alignment.center,
|
alignment: Alignment.center,
|
||||||
// textgate: was "Not enough data for chart".
|
child: Text(
|
||||||
child: Icon(
|
'Not enough data for chart',
|
||||||
Icons.show_chart,
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
color: colorScheme.outlineVariant,
|
|
||||||
semanticLabel: 'Not enough data for chart',
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,6 +5,7 @@
|
|||||||
// these are `part` files.
|
// these are `part` files.
|
||||||
part of 'history_screen.dart';
|
part of 'history_screen.dart';
|
||||||
|
|
||||||
|
|
||||||
class _ChartPainter extends CustomPainter {
|
class _ChartPainter extends CustomPainter {
|
||||||
_ChartPainter(
|
_ChartPainter(
|
||||||
this.points, {
|
this.points, {
|
||||||
@ -24,8 +25,22 @@ class _ChartPainter extends CustomPainter {
|
|||||||
static const _bottomPad = 22.0; // room for X-axis dates
|
static const _bottomPad = 22.0; // room for X-axis dates
|
||||||
static const _hPad = 8.0;
|
static const _hPad = 8.0;
|
||||||
|
|
||||||
// textgate: numeric day.month on the axis (was "Aug 15").
|
static const _months = [
|
||||||
static String _shortDate(DateTime d) => formatShortDate(d);
|
'Jan',
|
||||||
|
'Feb',
|
||||||
|
'Mar',
|
||||||
|
'Apr',
|
||||||
|
'May',
|
||||||
|
'Jun',
|
||||||
|
'Jul',
|
||||||
|
'Aug',
|
||||||
|
'Sep',
|
||||||
|
'Oct',
|
||||||
|
'Nov',
|
||||||
|
'Dec',
|
||||||
|
];
|
||||||
|
|
||||||
|
static String _shortDate(DateTime d) => '${_months[d.month - 1]} ${d.day}';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void paint(Canvas canvas, Size size) {
|
void paint(Canvas canvas, Size size) {
|
||||||
|
|||||||
@ -17,7 +17,7 @@ extension _HistoryPlanned on _HistoryScreenState {
|
|||||||
/// when there are none.
|
/// when there are none.
|
||||||
List<Widget> _plannedSection() => [
|
List<Widget> _plannedSection() => [
|
||||||
if (_plannedRows.isNotEmpty) ...[
|
if (_plannedRows.isNotEmpty) ...[
|
||||||
const _SectionLabel(Icons.event, 'PLANNED (not done yet)'),
|
const _SectionLabel('PLANNED (not done yet)'),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
..._plannedRows.map(
|
..._plannedRows.map(
|
||||||
(row) => _PlannedWorkoutTile(
|
(row) => _PlannedWorkoutTile(
|
||||||
@ -40,33 +40,19 @@ extension _HistoryPlanned on _HistoryScreenState {
|
|||||||
final confirmed = await showDialog<bool>(
|
final confirmed = await showDialog<bool>(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (context) => AlertDialog(
|
builder: (context) => AlertDialog(
|
||||||
// Was "Delete planned workout?" / "<source> on <date> at <time>.
|
title: const Text('Delete planned workout?'),
|
||||||
// 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(
|
content: Text(
|
||||||
[
|
'${payload['source'] ?? 'Manual workout'} on $date at '
|
||||||
'${payload['source'] ?? ''}',
|
'${payload['start_time']}. It will not be credited.',
|
||||||
date,
|
|
||||||
'${payload['start_time']}',
|
|
||||||
].where((part) => part.isNotEmpty).join(' · '),
|
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.of(context).pop(false),
|
onPressed: () => Navigator.of(context).pop(false),
|
||||||
child: const Icon(Icons.close, semanticLabel: 'KEEP'),
|
child: const Text('KEEP'),
|
||||||
),
|
),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.of(context).pop(true),
|
onPressed: () => Navigator.of(context).pop(true),
|
||||||
child: Icon(
|
child: const Text('DELETE'),
|
||||||
Icons.delete_outline,
|
|
||||||
color: Theme.of(context).colorScheme.error,
|
|
||||||
semanticLabel: 'DELETE',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@ -76,16 +62,11 @@ extension _HistoryPlanned on _HistoryScreenState {
|
|||||||
// loaded, and a delete confirmed after midnight would cancel a workout
|
// loaded, and a delete confirmed after midnight would cancel a workout
|
||||||
// that is now today's -- one the PC may already have credited.
|
// that is now today's -- one the PC may already have credited.
|
||||||
if (!_isPlanned(payload, dayKey((widget.clock ?? DateTime.now)()))) {
|
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(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(
|
SnackBar(
|
||||||
content: Row(
|
content: Text(
|
||||||
children: [
|
'Not deleted — $date has started, so it is no longer '
|
||||||
const Icon(Icons.block, semanticLabel: 'Not deleted'),
|
'a planned workout.',
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(date),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@ -100,20 +81,9 @@ extension _HistoryPlanned on _HistoryScreenState {
|
|||||||
});
|
});
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
if (!result.pushed) {
|
if (!result.pushed) {
|
||||||
// Was "Not deleted — <reason>"; the reason goes to the log instead.
|
ScaffoldMessenger.of(
|
||||||
developer.log(
|
context,
|
||||||
'History: planned $id not deleted: ${result.reason}',
|
).showSnackBar(SnackBar(content: Text('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;
|
return;
|
||||||
}
|
}
|
||||||
await _load();
|
await _load();
|
||||||
@ -153,9 +123,7 @@ class _PlannedWorkoutTile extends StatelessWidget {
|
|||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Text(
|
Text(
|
||||||
// textgate: was "<date> <time> · Planned"; the event
|
'${payload['date']} $time · Planned',
|
||||||
// glyph and the section glyph already say planned.
|
|
||||||
'${payload['date']} $time',
|
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: colorScheme.onSurface,
|
color: colorScheme.onSurface,
|
||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.bold,
|
||||||
@ -173,11 +141,8 @@ class _PlannedWorkoutTile extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: Icon(
|
tooltip: 'Delete planned workout',
|
||||||
Icons.delete_outline,
|
icon: Icon(Icons.delete_outline, color: colorScheme.error),
|
||||||
color: colorScheme.error,
|
|
||||||
semanticLabel: 'Delete planned workout',
|
|
||||||
),
|
|
||||||
onPressed: onDelete,
|
onPressed: onDelete,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@ -13,12 +13,10 @@ class _SyncedWorkoutTile extends StatelessWidget {
|
|||||||
final colorScheme = Theme.of(context).colorScheme;
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
final kind = '${payload['kind']}';
|
final kind = '${payload['kind']}';
|
||||||
final isRun = kind == 'runnerup_verified';
|
final isRun = kind == 'runnerup_verified';
|
||||||
final semanticLabel = isRun ? 'Run' : 'Manual';
|
final label = isRun ? 'Run' : 'Manual';
|
||||||
final detail = '${payload['source'] ?? ''}';
|
final detail = '${payload['source'] ?? ''}';
|
||||||
|
|
||||||
return Container(
|
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),
|
margin: const EdgeInsets.only(bottom: 8),
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
@ -34,16 +32,14 @@ class _SyncedWorkoutTile extends StatelessWidget {
|
|||||||
isRun ? Icons.directions_run : Icons.edit_note,
|
isRun ? Icons.directions_run : Icons.edit_note,
|
||||||
color: colorScheme.onSurfaceVariant,
|
color: colorScheme.onSurfaceVariant,
|
||||||
size: 20,
|
size: 20,
|
||||||
semanticLabel: semanticLabel,
|
|
||||||
),
|
),
|
||||||
const SizedBox(width: 10),
|
const SizedBox(width: 10),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
// textgate: was "<date> · Run|Manual"; the glyph says which.
|
|
||||||
Text(
|
Text(
|
||||||
'${payload['date']}',
|
'${payload['date']} · $label',
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: colorScheme.onSurface,
|
color: colorScheme.onSurface,
|
||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.bold,
|
||||||
@ -108,9 +104,8 @@ class _AllSessionTile extends StatelessWidget {
|
|||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
// textgate: was "Workout A · <date>".
|
|
||||||
Text(
|
Text(
|
||||||
'$type · $date',
|
'Workout $type · $date',
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: colorScheme.onSurface,
|
color: colorScheme.onSurface,
|
||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.bold,
|
||||||
@ -196,29 +191,17 @@ class _ExerciseSessionTile extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 2),
|
const SizedBox(height: 2),
|
||||||
// textgate: was "20kg · 3/3 sets · ⬤ warmup" / "reps: 5, 5"
|
Text(
|
||||||
// / "workout: 30m 00s". Now numbers behind glyphs; the warmup
|
'${weight ?? '?'}kg · $doneSets/$targetSets sets'
|
||||||
// is a filled or hollow sun.
|
' · ${warmupDone ? '⬤ warmup' : '○ no warmup'}',
|
||||||
Row(
|
style: mutedStyle,
|
||||||
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) ...[
|
if (repsSummary.isNotEmpty) ...[
|
||||||
const SizedBox(height: 2),
|
const SizedBox(height: 2),
|
||||||
_GlyphLine(Icons.repeat, repsSummary, mutedStyle),
|
Text('reps: $repsSummary', style: mutedStyle),
|
||||||
],
|
],
|
||||||
const SizedBox(height: 2),
|
const SizedBox(height: 2),
|
||||||
_GlyphLine(Icons.timer, dur, mutedStyle),
|
Text('workout: $dur', style: mutedStyle),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@ -227,22 +210,3 @@ 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),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@ -149,7 +149,10 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||||
// textgate: no title (was "Workout Tracker"); the app is the app.
|
title: Text(
|
||||||
|
'Workout Tracker',
|
||||||
|
style: TextStyle(color: colorScheme.onSurface),
|
||||||
|
),
|
||||||
actions: [
|
actions: [
|
||||||
IconButton(
|
IconButton(
|
||||||
key: const Key('home_run'),
|
key: const Key('home_run'),
|
||||||
@ -161,11 +164,8 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
onPressed: _openRun,
|
onPressed: _openRun,
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: Icon(
|
icon: Icon(Icons.edit_note, color: colorScheme.onSurface),
|
||||||
Icons.edit_note,
|
tooltip: 'Log manual workout',
|
||||||
color: colorScheme.onSurface,
|
|
||||||
semanticLabel: 'Log manual workout',
|
|
||||||
),
|
|
||||||
onPressed: () => Navigator.of(context).push(
|
onPressed: () => Navigator.of(context).push(
|
||||||
MaterialPageRoute<void>(
|
MaterialPageRoute<void>(
|
||||||
builder: (_) => const ManualWorkoutScreen(),
|
builder: (_) => const ManualWorkoutScreen(),
|
||||||
@ -173,21 +173,15 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: Icon(
|
tooltip: 'History',
|
||||||
Icons.history,
|
icon: Icon(Icons.history, color: colorScheme.onSurface),
|
||||||
color: colorScheme.onSurface,
|
|
||||||
semanticLabel: 'History',
|
|
||||||
),
|
|
||||||
onPressed: () => Navigator.of(context).push(
|
onPressed: () => Navigator.of(context).push(
|
||||||
MaterialPageRoute<void>(builder: (_) => const HistoryScreen()),
|
MaterialPageRoute<void>(builder: (_) => const HistoryScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: Icon(
|
tooltip: 'Settings',
|
||||||
Icons.settings,
|
icon: Icon(Icons.settings, color: colorScheme.onSurface),
|
||||||
color: colorScheme.onSurface,
|
|
||||||
semanticLabel: 'Settings',
|
|
||||||
),
|
|
||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
await Navigator.of(context).push(
|
await Navigator.of(context).push(
|
||||||
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()),
|
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()),
|
||||||
|
|||||||
@ -35,45 +35,44 @@ class _WorkoutCard extends StatelessWidget {
|
|||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
// textgate: was "Done for today!" / "Next: Workout A" /
|
if (doneToday && !hasActiveSession) ...[
|
||||||
// "Workout A in progress". Now the plan letter plus a state
|
Row(
|
||||||
// glyph; colour is the second channel (success / warning).
|
children: [
|
||||||
Row(
|
Icon(Icons.check_circle, color: status.success, size: 18),
|
||||||
children: [
|
const SizedBox(width: 8),
|
||||||
if (doneToday && !hasActiveSession)
|
Text(
|
||||||
Icon(
|
'Done for today!',
|
||||||
Icons.check_circle,
|
style: TextStyle(
|
||||||
key: const Key('home_done_today'),
|
color: status.success,
|
||||||
color: status.success,
|
fontWeight: FontWeight.bold,
|
||||||
semanticLabel: 'Done for today',
|
fontSize: AppTextSize.body,
|
||||||
)
|
),
|
||||||
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),
|
const SizedBox(height: 10),
|
||||||
...exercises.map(
|
...exercises.map(
|
||||||
(e) => Text(
|
(e) => Text(
|
||||||
@ -94,10 +93,13 @@ class _WorkoutCard extends StatelessWidget {
|
|||||||
padding: buttonPadding,
|
padding: buttonPadding,
|
||||||
),
|
),
|
||||||
onPressed: onResume,
|
onPressed: onResume,
|
||||||
child: Icon(
|
child: Text(
|
||||||
Icons.play_arrow,
|
'Resume Workout',
|
||||||
color: colorScheme.onPrimary,
|
style: TextStyle(
|
||||||
semanticLabel: 'Resume Workout',
|
color: colorScheme.onPrimary,
|
||||||
|
fontSize: AppTextSize.body,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@ -112,10 +114,13 @@ class _WorkoutCard extends StatelessWidget {
|
|||||||
padding: buttonPadding,
|
padding: buttonPadding,
|
||||||
),
|
),
|
||||||
onPressed: onStart,
|
onPressed: onStart,
|
||||||
child: Icon(
|
child: Text(
|
||||||
Icons.play_arrow,
|
'Start Workout $type',
|
||||||
color: colorScheme.onPrimary,
|
style: TextStyle(
|
||||||
semanticLabel: 'Start Workout $type',
|
color: colorScheme.onPrimary,
|
||||||
|
fontSize: AppTextSize.body,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -10,37 +10,26 @@ part of 'manual_workout_screen.dart';
|
|||||||
extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
|
extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
|
||||||
/// The budget as seen from the selected date: the fullest 7- and 30-day
|
/// The budget as seen from the selected date: the fullest 7- and 30-day
|
||||||
/// windows around it, planned entries included.
|
/// windows around it, planned entries included.
|
||||||
///
|
Widget _budgetBanner(ManualBudget budget) => Text(
|
||||||
/// textgate: was "Manual around DATE: 0/2 per 7 days · 0/10 per 30
|
'Manual around ${dayKey(_date)}: '
|
||||||
/// days"; now the counts with their window length in days.
|
'${budget.week}/$kManualWorkoutBudgetPer7Days per 7 days · '
|
||||||
Widget _budgetBanner(ManualBudget budget) => Row(
|
'${budget.month}/$kManualWorkoutBudgetPer30Days per 30 days',
|
||||||
key: const Key('mw_budget'),
|
style: TextStyle(
|
||||||
children: [
|
color: Theme.of(context).colorScheme.primary,
|
||||||
Icon(
|
fontSize: AppTextSize.body,
|
||||||
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,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
/// `+0` for today, `+1` for tomorrow, `+N` (textgate: was "today" /
|
/// "today", "tomorrow" or "in N days" for the selected date.
|
||||||
/// "tomorrow" / "in N days").
|
|
||||||
String _relativeDay() {
|
String _relativeDay() {
|
||||||
// Rounded, not truncated: across a DST change two local midnights are
|
// Rounded, not truncated: across a DST change two local midnights are
|
||||||
// 23 or 25 hours apart.
|
// 23 or 25 hours apart.
|
||||||
final days = (_date.difference(_today()).inHours / 24).round();
|
final days = (_date.difference(_today()).inHours / 24).round();
|
||||||
return '+$days';
|
return switch (days) {
|
||||||
|
0 => 'today',
|
||||||
|
1 => 'tomorrow',
|
||||||
|
_ => 'in $days days',
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The workout date and the button that changes it.
|
/// The workout date and the button that changes it.
|
||||||
@ -50,8 +39,7 @@ extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
|
|||||||
children: [
|
children: [
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Text(
|
||||||
// textgate: was "Workout date: DATE (today)".
|
'Workout date: ${dayKey(_date)} (${_relativeDay()})',
|
||||||
'${dayKey(_date)} ${_relativeDay()}',
|
|
||||||
key: const Key('mw_date'),
|
key: const Key('mw_date'),
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: Theme.of(context).colorScheme.onSurface,
|
color: Theme.of(context).colorScheme.onSurface,
|
||||||
@ -62,32 +50,25 @@ extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
|
|||||||
TextButton(
|
TextButton(
|
||||||
key: const Key('mw_pick_date'),
|
key: const Key('mw_pick_date'),
|
||||||
onPressed: _submitting ? null : _pickDate,
|
onPressed: _submitting ? null : _pickDate,
|
||||||
child: const Icon(
|
child: const Text('CHANGE DATE'),
|
||||||
Icons.calendar_today,
|
|
||||||
size: 20,
|
|
||||||
semanticLabel: 'CHANGE DATE',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
/// A divider between field groups (textgate: was a word heading such as
|
Widget _section(String title) => Padding(
|
||||||
/// "Basics" or "Reflection").
|
padding: const EdgeInsets.only(top: 16, bottom: 4),
|
||||||
Widget _section() => Padding(
|
child: Text(
|
||||||
padding: const EdgeInsets.only(top: 12, bottom: 4),
|
title,
|
||||||
child: Divider(color: Theme.of(context).colorScheme.primary),
|
style: TextStyle(
|
||||||
|
color: Theme.of(context).colorScheme.primary,
|
||||||
|
fontSize: AppTextSize.subtitle,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
/// A field marked by [icon]; [semanticsLabel] (the old floating label) is
|
Widget _text(String key, String label, {int lines = 1}) => Padding(
|
||||||
/// 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),
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||||
child: TextField(
|
child: TextField(
|
||||||
key: Key('mw_$key'),
|
key: Key('mw_$key'),
|
||||||
@ -97,68 +78,14 @@ extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
|
|||||||
// filled/fillColor/border inherit from the shared inputDecorationTheme
|
// filled/fillColor/border inherit from the shared inputDecorationTheme
|
||||||
// (theme.dart) — only the field-specific label needs setting here.
|
// (theme.dart) — only the field-specific label needs setting here.
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
hintText: hint,
|
labelText: label,
|
||||||
prefixIcon: Icon(
|
labelStyle: TextStyle(
|
||||||
icon,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
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.
|
/// Reads [key]'s field as an int, treating blank or unparsable as 0.
|
||||||
int _int(String key) => int.tryParse(_fields[key]!.text.trim()) ?? 0;
|
int _int(String key) => int.tryParse(_fields[key]!.text.trim()) ?? 0;
|
||||||
|
|
||||||
|
|||||||
@ -124,11 +124,9 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
|
|||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||||
// textgate: was "Log Manual Workout".
|
title: Text(
|
||||||
title: Icon(
|
'Log Manual Workout',
|
||||||
Icons.edit_note,
|
style: TextStyle(color: colorScheme.onSurface),
|
||||||
color: colorScheme.onSurface,
|
|
||||||
semanticLabel: 'Log Manual Workout',
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
body: !_budgetLoaded
|
body: !_budgetLoaded
|
||||||
@ -141,49 +139,47 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
|
|||||||
_dateRow(),
|
_dateRow(),
|
||||||
_budgetBanner(budget),
|
_budgetBanner(budget),
|
||||||
if (exhausted)
|
if (exhausted)
|
||||||
// textgate: was "Manual-workout budget exhausted for a
|
|
||||||
// window containing <date> — pick another date."
|
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.only(top: 8),
|
padding: const EdgeInsets.only(top: 8),
|
||||||
child: Icon(
|
child: Text(
|
||||||
Icons.block,
|
'Manual-workout budget exhausted for a window '
|
||||||
key: const Key('mw_exhausted'),
|
'containing ${dayKey(_date)} — pick another date.',
|
||||||
size: 40,
|
style: TextStyle(color: colorScheme.error),
|
||||||
color: colorScheme.error,
|
|
||||||
semanticLabel:
|
|
||||||
'Manual-workout budget exhausted — '
|
|
||||||
'pick another date.',
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
else ...[
|
else ...[
|
||||||
_section(),
|
_section('Basics'),
|
||||||
_sportDropdown(),
|
_sportDropdown(),
|
||||||
..._basicFields(),
|
_text('start_time', 'Start time (HH:MM)'),
|
||||||
_section(),
|
_text('end_time', 'End time (HH:MM)'),
|
||||||
..._logisticsFields(),
|
_section('Location & logistics'),
|
||||||
_section(),
|
_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'),
|
||||||
..._sportFields(),
|
..._sportFields(),
|
||||||
_rpeSlider(),
|
_rpeSlider(),
|
||||||
..._detailFields(),
|
_text('techniques_practiced', 'Techniques (optional)'),
|
||||||
_section(),
|
_text('warm_up_minutes', 'Warm-up (optional)'),
|
||||||
..._reflectionFields(),
|
_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),
|
||||||
if (_error != null)
|
if (_error != null)
|
||||||
// textgate: the refusal reason is spoken only; painted
|
|
||||||
// as an error glyph.
|
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||||
child: Icon(
|
child: Text(
|
||||||
Icons.error_outline,
|
_error!,
|
||||||
key: const Key('mw_error'),
|
style: TextStyle(color: colorScheme.error),
|
||||||
color: colorScheme.error,
|
|
||||||
semanticLabel: _error,
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||||
child: ElevatedButton(
|
child: ElevatedButton(
|
||||||
onPressed: _submitting ? null : _submit,
|
onPressed: _submitting ? null : _submit,
|
||||||
child: const Icon(Icons.save, semanticLabel: 'SUBMIT'),
|
child: const Text('SUBMIT'),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@ -192,6 +188,24 @@ 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(
|
Widget _sportDropdown() => Padding(
|
||||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||||
child: DropdownButton<String>(
|
child: DropdownButton<String>(
|
||||||
@ -200,17 +214,8 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
|
|||||||
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
|
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
|
||||||
isExpanded: true,
|
isExpanded: true,
|
||||||
items: [
|
items: [
|
||||||
// textgate: sport glyphs; the names are spoken only.
|
|
||||||
for (final entry in kSportLabels.entries)
|
for (final entry in kSportLabels.entries)
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(value: entry.key, child: Text(entry.value)),
|
||||||
value: entry.key,
|
|
||||||
child: Icon(
|
|
||||||
entry.key == kSportTableTennis
|
|
||||||
? Icons.sports_tennis
|
|
||||||
: Icons.sports,
|
|
||||||
semanticLabel: entry.value,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
onChanged: (value) {
|
onChanged: (value) {
|
||||||
if (value != null) setState(() => _sport = value);
|
if (value != null) setState(() => _sport = value);
|
||||||
@ -222,16 +227,8 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
|
|||||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
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(
|
Text(
|
||||||
'${_rpe.round()}',
|
'RPE ${_rpe.round()}',
|
||||||
key: const Key('mw_rpe'),
|
|
||||||
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
|
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
|
||||||
),
|
),
|
||||||
Expanded(
|
Expanded(
|
||||||
|
|||||||
@ -7,7 +7,6 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:developer';
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
@ -54,8 +53,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
bool _soundEnabled = true;
|
bool _soundEnabled = true;
|
||||||
|
|
||||||
// Set after a Sync settings visit restores progression; the banner stays.
|
// Set after a Sync settings visit restores progression; the banner stays.
|
||||||
/// Exercises the last sync-settings visit restored; null until one did.
|
String? _progressionStatus;
|
||||||
int? _restoredCount;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@ -127,7 +125,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
ProgressionSyncService().pullProgression)();
|
ProgressionSyncService().pullProgression)();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
if (restored.changed) {
|
if (restored.changed) {
|
||||||
setState(() => _restoredCount = restored.count);
|
setState(
|
||||||
|
() => _progressionStatus =
|
||||||
|
'Restored ${restored.count} exercise(s) from Firebase.',
|
||||||
|
);
|
||||||
await _load();
|
await _load();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -177,7 +178,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
await (widget.progressionPusher ??
|
await (widget.progressionPusher ??
|
||||||
ProgressionSyncService().pushProgression)();
|
ProgressionSyncService().pushProgression)();
|
||||||
if (!mounted || pushed.changed) return;
|
if (!mounted || pushed.changed) return;
|
||||||
_flagUnsynced(pushed.reason);
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Saved on this phone, not synced: ${pushed.reason}'),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shows a deloaded target everywhere this screen holds a copy of it.
|
/// Shows a deloaded target everywhere this screen holds a copy of it.
|
||||||
@ -223,7 +228,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
_SoundSection(enabled: _soundEnabled, onChanged: _setSound),
|
_SoundSection(enabled: _soundEnabled, onChanged: _setSound),
|
||||||
const SizedBox(height: 20),
|
const SizedBox(height: 20),
|
||||||
_SyncSection(
|
_SyncSection(
|
||||||
restoredCount: _restoredCount,
|
progressionStatus: _progressionStatus,
|
||||||
onOpenSyncSettings: () => unawaited(_openSyncSettings()),
|
onOpenSyncSettings: () => unawaited(_openSyncSettings()),
|
||||||
onOpenGitHubMirror: () => unawaited(_openGitHubMirror()),
|
onOpenGitHubMirror: () => unawaited(_openGitHubMirror()),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -23,29 +23,26 @@ extension _SettingsScreenActions on _SettingsScreenState {
|
|||||||
context: context,
|
context: context,
|
||||||
builder: (_) => AlertDialog(
|
builder: (_) => AlertDialog(
|
||||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||||
// Was "Reset to defaults?" / "All weights and thresholds will be
|
title: Text(
|
||||||
// reset. Streak counters will be cleared.".
|
'Reset to defaults?',
|
||||||
title: Icon(
|
style: TextStyle(color: colorScheme.onSurface),
|
||||||
Icons.restart_alt,
|
),
|
||||||
color: colorScheme.error,
|
content: Text(
|
||||||
semanticLabel: 'Reset to defaults?',
|
'All weights and thresholds will be reset. '
|
||||||
|
'Streak counters will be cleared.',
|
||||||
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.pop(context, false),
|
onPressed: () => Navigator.pop(context, false),
|
||||||
child: Icon(
|
child: Text(
|
||||||
Icons.close,
|
'Cancel',
|
||||||
color: colorScheme.onSurfaceVariant,
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
semanticLabel: 'Cancel',
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.pop(context, true),
|
onPressed: () => Navigator.pop(context, true),
|
||||||
child: Icon(
|
child: Text('Reset', style: TextStyle(color: colorScheme.error)),
|
||||||
Icons.restart_alt,
|
|
||||||
color: colorScheme.error,
|
|
||||||
semanticLabel: 'Reset',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@ -86,20 +83,4 @@ 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',
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -21,17 +21,9 @@ extension _SettingsScreenDeload on _SettingsScreenState {
|
|||||||
if (!mounted) return null;
|
if (!mounted) return null;
|
||||||
final next = result.state;
|
final next = result.state;
|
||||||
if (next == null) {
|
if (next == null) {
|
||||||
// Was the refusal reason as a sentence; it goes to the log instead.
|
ScaffoldMessenger.of(
|
||||||
log('Settings: deload of $name refused: ${result.reason}', level: 900);
|
context,
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
).showSnackBar(SnackBar(content: Text(result.reason)));
|
||||||
SnackBar(
|
|
||||||
content: Icon(
|
|
||||||
Icons.block,
|
|
||||||
color: Theme.of(context).colorScheme.error,
|
|
||||||
semanticLabel: 'Deload failed',
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
SandboxLog.event('manual deload', {
|
SandboxLog.event('manual deload', {
|
||||||
|
|||||||
@ -25,11 +25,20 @@ class _ExercisesSection extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
// textgate: the helper sentence under the heading is gone.
|
const _SectionHeader('PER EXERCISE'),
|
||||||
const _SectionHeader(Icons.tune, '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,
|
||||||
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
...orderedNames.map((name) {
|
...orderedNames.map((name) {
|
||||||
final s = states[name];
|
final s = states[name];
|
||||||
@ -48,50 +57,29 @@ class _ExerciseSettingsRow extends StatelessWidget {
|
|||||||
final ExerciseState state;
|
final ExerciseState state;
|
||||||
final VoidCallback onTap;
|
final VoidCallback onTap;
|
||||||
|
|
||||||
// textgate: was "kg · ↑3 ↓2 · rest 3:00 / 5:00 · warmup 1:00" (or
|
String get _summary {
|
||||||
// "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 s = state;
|
||||||
final style = TextStyle(color: color, fontSize: AppTextSize.caption);
|
final mode = switch (s.mode) {
|
||||||
final modeIcon = switch (s.mode) {
|
ProgressionMode.weight => 'kg',
|
||||||
ProgressionMode.weight => Icons.fitness_center,
|
ProgressionMode.reps => 'reps',
|
||||||
ProgressionMode.reps => Icons.repeat,
|
ProgressionMode.doubleProgression => '${s.repsLow}→${s.repsHigh} reps',
|
||||||
ProgressionMode.doubleProgression => null,
|
|
||||||
};
|
};
|
||||||
return Row(
|
final warmup = s.hasWarmup
|
||||||
key: const Key('exercise_settings_summary'),
|
? 'warmup ${formatRest(s.restWarmupSecs)}'
|
||||||
children: [
|
: 'no warmup';
|
||||||
if (modeIcon == null)
|
return '$mode · ↑${s.successThreshold} ↓${s.failThreshold} · '
|
||||||
Text('${s.repsLow}→${s.repsHigh}', style: style)
|
'rest ${formatRest(s.restSuccessSecs)} / '
|
||||||
else
|
'${formatRest(s.restFailSecs)} · $warmup';
|
||||||
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
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final colorScheme = Theme.of(context).colorScheme;
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
final until = state.isPausedAt(DateTime.now()) ? state.pausedUntil : null;
|
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(
|
return Semantics(
|
||||||
container: true,
|
container: true,
|
||||||
button: true,
|
button: true,
|
||||||
label: semanticsLabel,
|
label: '${state.name} exercise settings',
|
||||||
excludeSemantics: true,
|
excludeSemantics: true,
|
||||||
child: InkWell(
|
child: InkWell(
|
||||||
onTap: onTap,
|
onTap: onTap,
|
||||||
@ -118,26 +106,21 @@ class _ExerciseSettingsRow extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
_summary(colorScheme.onSurfaceVariant),
|
Text(
|
||||||
|
_summary,
|
||||||
|
style: TextStyle(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
fontSize: AppTextSize.caption,
|
||||||
|
),
|
||||||
|
),
|
||||||
if (until != null) ...[
|
if (until != null) ...[
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
// textgate: was "Paused — back on 11 Oct".
|
Text(
|
||||||
Row(
|
'Paused — back on ${formatShortDate(until)}',
|
||||||
children: [
|
style: TextStyle(
|
||||||
Icon(
|
color: colorScheme.error,
|
||||||
Icons.pause_circle_outline,
|
fontSize: AppTextSize.caption,
|
||||||
size: 14,
|
),
|
||||||
color: colorScheme.error,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 4),
|
|
||||||
Text(
|
|
||||||
formatShortDate(until),
|
|
||||||
style: TextStyle(
|
|
||||||
color: colorScheme.error,
|
|
||||||
fontSize: AppTextSize.caption,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
|||||||
@ -26,11 +26,20 @@ class _WeightsSection extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
// textgate: the helper sentence under the heading is gone.
|
const _SectionHeader('WEIGHTS'),
|
||||||
const _SectionHeader(Icons.fitness_center, '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,
|
||||||
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
...orderedNames.map((name) {
|
...orderedNames.map((name) {
|
||||||
final w = weights[name];
|
final w = weights[name];
|
||||||
@ -65,11 +74,21 @@ class _RepsSection extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
// textgate: the helper sentence under the heading is gone.
|
const _SectionHeader('TARGET REPS'),
|
||||||
const _SectionHeader(Icons.repeat, '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,
|
||||||
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
...orderedNames.map((name) {
|
...orderedNames.map((name) {
|
||||||
final r = reps[name];
|
final r = reps[name];
|
||||||
|
|||||||
@ -20,7 +20,7 @@ class _PcLinkSection extends StatefulWidget {
|
|||||||
class _PcLinkSectionState extends State<_PcLinkSection> {
|
class _PcLinkSectionState extends State<_PcLinkSection> {
|
||||||
final TextEditingController _host = TextEditingController();
|
final TextEditingController _host = TextEditingController();
|
||||||
bool? _paired;
|
bool? _paired;
|
||||||
({bool ok, String spoken})? _status;
|
String? _status;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@ -44,39 +44,32 @@ class _PcLinkSectionState extends State<_PcLinkSection> {
|
|||||||
Future<void> _save() async {
|
Future<void> _save() async {
|
||||||
final host = _host.text.trim();
|
final host = _host.text.trim();
|
||||||
if (!isValidPcHost(host)) {
|
if (!isValidPcHost(host)) {
|
||||||
setState(
|
setState(() => _status = 'Not an IPv4 address or hostname: "$host".');
|
||||||
() => _status = (
|
|
||||||
ok: false,
|
|
||||||
spoken: 'Not an IPv4 address or hostname: "$host".',
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await PcPairing.saveHost(host);
|
await PcPairing.saveHost(host);
|
||||||
SandboxLog.event('pc host saved', {'host': host});
|
SandboxLog.event('pc host saved', {'host': host});
|
||||||
setState(
|
setState(() => _status = 'Workouts are now sent to $host:$kPcPokePort.');
|
||||||
() => _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
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||||
final paired = _paired;
|
final paired = _paired;
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
// textgate: the explanation sentence under the heading is gone.
|
const _SectionHeader('PC LINK'),
|
||||||
const _SectionHeader(Icons.computer, '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,
|
||||||
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: AppSpacing.sm),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
@ -85,10 +78,9 @@ class _PcLinkSectionState extends State<_PcLinkSection> {
|
|||||||
key: const Key('pc-host'),
|
key: const Key('pc-host'),
|
||||||
controller: _host,
|
controller: _host,
|
||||||
keyboardType: TextInputType.url,
|
keyboardType: TextInputType.url,
|
||||||
// Was labelText 'PC address'.
|
|
||||||
decoration: const InputDecoration(
|
decoration: const InputDecoration(
|
||||||
isDense: true,
|
isDense: true,
|
||||||
prefixIcon: Icon(Icons.computer, semanticLabel: 'PC address'),
|
labelText: 'PC address',
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@ -98,32 +90,32 @@ class _PcLinkSectionState extends State<_PcLinkSection> {
|
|||||||
onPressed: () => unawaited(_save()),
|
onPressed: () => unawaited(_save()),
|
||||||
// Distinct label: the sandbox section has its own "Save", and
|
// Distinct label: the sandbox section has its own "Save", and
|
||||||
// two identical labels cannot be driven by element.
|
// two identical labels cannot be driven by element.
|
||||||
child: const Icon(Icons.save, semanticLabel: 'Save PC address'),
|
child: const Text('Save', semanticsLabel: 'Save PC address'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: AppSpacing.sm),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
// textgate: was "PC paired: checking…" / "PC paired ✓" / "PC
|
Text(
|
||||||
// paired ✗ — run scripts/pair_phone.sh on the PC". Now a link glyph
|
switch (paired) {
|
||||||
// (hourglass while checking, broken link when unpaired) in the
|
null => 'PC paired: checking…',
|
||||||
// success / warning colour.
|
true => 'PC paired ✓',
|
||||||
Align(
|
false => 'PC paired ✗ — run scripts/pair_phone.sh on the PC',
|
||||||
alignment: Alignment.centerLeft,
|
},
|
||||||
child: Icon(
|
key: const Key('pc-paired'),
|
||||||
switch (paired) {
|
style: TextStyle(
|
||||||
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,
|
color: paired ?? false ? status.success : status.warning,
|
||||||
semanticLabel: _pairedSemanticsLabel(paired),
|
fontSize: AppTextSize.caption,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (_status case final s?) ...[
|
if (_status != null) ...[
|
||||||
const SizedBox(height: AppSpacing.xs),
|
const SizedBox(height: AppSpacing.xs),
|
||||||
_StatusGlyph(ok: s.ok, spoken: s.spoken),
|
Text(
|
||||||
|
_status!,
|
||||||
|
style: TextStyle(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
fontSize: AppTextSize.caption,
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -4,23 +4,19 @@
|
|||||||
// See history_screen_charts.dart for the full reasoning.
|
// See history_screen_charts.dart for the full reasoning.
|
||||||
part of 'settings_screen.dart';
|
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 {
|
class _SectionHeader extends StatelessWidget {
|
||||||
const _SectionHeader(this.icon, this.spoken);
|
const _SectionHeader(this.text);
|
||||||
|
|
||||||
final IconData icon;
|
final String text;
|
||||||
final String spoken;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Align(
|
return Text(
|
||||||
alignment: Alignment.centerLeft,
|
text,
|
||||||
child: Icon(
|
style: TextStyle(
|
||||||
icon,
|
|
||||||
size: 20,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
semanticLabel: spoken,
|
fontSize: AppTextSize.caption,
|
||||||
|
letterSpacing: 1.4,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -60,8 +56,7 @@ class _RepsRow extends StatelessWidget {
|
|||||||
SizedBox(
|
SizedBox(
|
||||||
width: 72,
|
width: 72,
|
||||||
child: Text(
|
child: Text(
|
||||||
// textgate: was "12 reps"; the section's repeat glyph says it.
|
'$reps reps',
|
||||||
'×$reps',
|
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: colorScheme.onSurface,
|
color: colorScheme.onSurface,
|
||||||
@ -109,8 +104,9 @@ class _WeightRow extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
_StepperButton(
|
_StepperButton(
|
||||||
icon: Icons.remove,
|
icon: Icons.remove,
|
||||||
onTap: () =>
|
onTap: () => onChanged(
|
||||||
onChanged((weight - kWeightIncrement).clamp(0.0, 999.0)),
|
(weight - kWeightIncrement).clamp(0.0, 999.0),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
// Fixed-width container supports up to "999.9kg" (7 chars).
|
// Fixed-width container supports up to "999.9kg" (7 chars).
|
||||||
SizedBox(
|
SizedBox(
|
||||||
@ -159,27 +155,3 @@ 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,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@ -18,7 +18,7 @@ class _SandboxSectionState extends State<_SandboxSection> {
|
|||||||
late final TextEditingController _rest = TextEditingController(
|
late final TextEditingController _rest = TextEditingController(
|
||||||
text: '${Sandbox.restSecs}',
|
text: '${Sandbox.restSecs}',
|
||||||
);
|
);
|
||||||
({bool ok, String spoken})? _status;
|
String? _status;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
@ -26,9 +26,9 @@ class _SandboxSectionState extends State<_SandboxSection> {
|
|||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _report(String status, {bool ok = true}) {
|
void _report(String status) {
|
||||||
SandboxLog.event('sandbox settings', {'status': status});
|
SandboxLog.event('sandbox settings', {'status': status});
|
||||||
setState(() => _status = (ok: ok, spoken: status));
|
setState(() => _status = status);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _wipe() async {
|
Future<void> _wipe() async {
|
||||||
@ -53,10 +53,7 @@ class _SandboxSectionState extends State<_SandboxSection> {
|
|||||||
Future<void> _saveRest() async {
|
Future<void> _saveRest() async {
|
||||||
final secs = int.tryParse(_rest.text.trim());
|
final secs = int.tryParse(_rest.text.trim());
|
||||||
if (secs == null || secs < 1) {
|
if (secs == null || secs < 1) {
|
||||||
_report(
|
_report('Rest length must be a whole number of seconds, 1 or more.');
|
||||||
'Rest length must be a whole number of seconds, 1 or more.',
|
|
||||||
ok: false,
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await StorageService.instance.setSandboxRestSecs(secs);
|
await StorageService.instance.setSandboxRestSecs(secs);
|
||||||
@ -76,36 +73,38 @@ class _SandboxSectionState extends State<_SandboxSection> {
|
|||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
// textgate: the explanation paragraph under the heading is gone.
|
const _SectionHeader('SANDBOX'),
|
||||||
const _SectionHeader(Icons.science, '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,
|
||||||
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
Wrap(
|
Wrap(
|
||||||
spacing: 8,
|
spacing: 8,
|
||||||
runSpacing: 8,
|
runSpacing: 8,
|
||||||
children: [
|
children: [
|
||||||
ElevatedButton(
|
ElevatedButton.icon(
|
||||||
onPressed: () => unawaited(_wipe()),
|
onPressed: () => unawaited(_wipe()),
|
||||||
child: Icon(
|
icon: const Icon(Icons.delete_sweep),
|
||||||
Icons.delete_sweep,
|
label: const Text('Wipe sandbox data'),
|
||||||
color: colorScheme.error,
|
|
||||||
semanticLabel: 'Wipe sandbox data',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
ElevatedButton(
|
ElevatedButton.icon(
|
||||||
onPressed: () => unawaited(_markTodayNotDone()),
|
onPressed: () => unawaited(_markTodayNotDone()),
|
||||||
child: const Icon(
|
icon: const Icon(Icons.undo),
|
||||||
Icons.undo,
|
label: const Text('Mark today not done'),
|
||||||
semanticLabel: 'Mark today not done',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
// Was "Rest length (seconds)"; the field shows the number.
|
const Expanded(child: Text('Rest length (seconds)')),
|
||||||
const Icon(Icons.timer, semanticLabel: 'Rest length (seconds)'),
|
|
||||||
const Spacer(),
|
|
||||||
SizedBox(
|
SizedBox(
|
||||||
width: 72,
|
width: 72,
|
||||||
child: TextField(
|
child: TextField(
|
||||||
@ -113,14 +112,16 @@ class _SandboxSectionState extends State<_SandboxSection> {
|
|||||||
controller: _rest,
|
controller: _rest,
|
||||||
keyboardType: TextInputType.number,
|
keyboardType: TextInputType.number,
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
decoration: const InputDecoration(isDense: true),
|
decoration: const InputDecoration(
|
||||||
|
isDense: true,
|
||||||
|
hintText: 'seconds',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => unawaited(_saveRest()),
|
onPressed: () => unawaited(_saveRest()),
|
||||||
// Spoken label distinct from the PC LINK "Save PC address".
|
child: const Text('Save'),
|
||||||
child: const Icon(Icons.save, semanticLabel: 'Save'),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@ -145,12 +146,14 @@ class _SandboxSectionState extends State<_SandboxSection> {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (_status case final s?) ...[
|
if (_status != null) ...[
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
_StatusGlyph(
|
Text(
|
||||||
key: const Key('sandbox-status'),
|
_status!,
|
||||||
ok: s.ok,
|
style: TextStyle(
|
||||||
spoken: s.spoken,
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
fontSize: AppTextSize.caption,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
|||||||
@ -13,13 +13,13 @@ part of 'settings_screen.dart';
|
|||||||
/// The SYNC section: progression status line plus the two sync routes.
|
/// The SYNC section: progression status line plus the two sync routes.
|
||||||
class _SyncSection extends StatelessWidget {
|
class _SyncSection extends StatelessWidget {
|
||||||
const _SyncSection({
|
const _SyncSection({
|
||||||
required this.restoredCount,
|
required this.progressionStatus,
|
||||||
required this.onOpenSyncSettings,
|
required this.onOpenSyncSettings,
|
||||||
required this.onOpenGitHubMirror,
|
required this.onOpenGitHubMirror,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Exercises the last progression pull restored, or null when none did.
|
/// Last progression-sync outcome, or null when there is nothing to report.
|
||||||
final int? restoredCount;
|
final String? progressionStatus;
|
||||||
|
|
||||||
/// Opens the Firebase sync settings screen.
|
/// Opens the Firebase sync settings screen.
|
||||||
final VoidCallback onOpenSyncSettings;
|
final VoidCallback onOpenSyncSettings;
|
||||||
@ -33,29 +33,15 @@ class _SyncSection extends StatelessWidget {
|
|||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
const _SectionHeader(Icons.sync, 'SYNC'),
|
const _SectionHeader('SYNC'),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
// textgate: was "Restored N exercise(s) from Firebase."; now a
|
if (progressionStatus != null) ...[
|
||||||
// download glyph and the count, in the success colour.
|
Text(
|
||||||
if (restoredCount != null) ...[
|
progressionStatus!,
|
||||||
Row(
|
style: TextStyle(
|
||||||
key: const Key('settings_restored'),
|
color: colorScheme.onSurfaceVariant,
|
||||||
children: [
|
fontSize: AppTextSize.caption,
|
||||||
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),
|
const SizedBox(height: 8),
|
||||||
],
|
],
|
||||||
@ -64,12 +50,14 @@ class _SyncSection extends StatelessWidget {
|
|||||||
color: colorScheme.surfaceContainerHigh,
|
color: colorScheme.surfaceContainerHigh,
|
||||||
child: Column(
|
child: Column(
|
||||||
children: [
|
children: [
|
||||||
// textgate: was "Sync settings" / "Firebase sync".
|
|
||||||
ListTile(
|
ListTile(
|
||||||
leading: Icon(
|
title: Text(
|
||||||
Icons.cloud,
|
'Sync settings',
|
||||||
color: colorScheme.onSurface,
|
style: TextStyle(color: colorScheme.onSurface),
|
||||||
semanticLabel: 'Sync settings',
|
),
|
||||||
|
subtitle: Text(
|
||||||
|
'Firebase sync',
|
||||||
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
),
|
),
|
||||||
trailing: Icon(
|
trailing: Icon(
|
||||||
Icons.chevron_right,
|
Icons.chevron_right,
|
||||||
@ -81,14 +69,14 @@ class _SyncSection extends StatelessWidget {
|
|||||||
height: 1,
|
height: 1,
|
||||||
color: colorScheme.onSurfaceVariant.withValues(alpha: 0.2),
|
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(
|
ListTile(
|
||||||
leading: Icon(
|
title: Text(
|
||||||
Icons.code,
|
'Advanced sync (GitHub)',
|
||||||
color: colorScheme.onSurfaceVariant,
|
style: TextStyle(color: colorScheme.onSurface),
|
||||||
semanticLabel: 'Advanced sync (GitHub)',
|
),
|
||||||
|
subtitle: Text(
|
||||||
|
'Cutover mirror — not recommended',
|
||||||
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
),
|
),
|
||||||
trailing: Icon(
|
trailing: Icon(
|
||||||
Icons.chevron_right,
|
Icons.chevron_right,
|
||||||
@ -119,35 +107,42 @@ class _OfflineBackupSection extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
// textgate: the explanation paragraph under the heading is gone.
|
const _SectionHeader('OFFLINE BACKUP'),
|
||||||
const _SectionHeader(Icons.sd_storage, '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,
|
||||||
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
if (storageGranted)
|
if (storageGranted)
|
||||||
// Was "Storage permission granted": storage glyph + green tick.
|
const Row(
|
||||||
Row(
|
|
||||||
children: [
|
children: [
|
||||||
const Icon(Icons.sd_storage, size: 20),
|
Icon(Icons.check_circle, size: 20),
|
||||||
const SizedBox(width: 4),
|
SizedBox(width: 8),
|
||||||
Icon(
|
Expanded(child: Text('Storage permission granted')),
|
||||||
Icons.check_circle,
|
|
||||||
size: 20,
|
|
||||||
color: Theme.of(context).extension<AppStatusColors>()!.success,
|
|
||||||
semanticLabel: 'Storage permission granted',
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
Align(
|
Align(
|
||||||
alignment: Alignment.centerLeft,
|
alignment: Alignment.centerLeft,
|
||||||
child: ElevatedButton(
|
child: ElevatedButton.icon(
|
||||||
onPressed: onGrantStorage,
|
onPressed: onGrantStorage,
|
||||||
child: const Icon(
|
icon: const Icon(Icons.sd_storage),
|
||||||
Icons.sd_storage,
|
label: const Text('Grant storage permission'),
|
||||||
semanticLabel: 'Grant storage permission',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
DataTransferButtons(
|
DataTransferButtons(
|
||||||
@ -181,14 +176,16 @@ class _SettingsAppBar extends StatelessWidget implements PreferredSizeWidget {
|
|||||||
final colorScheme = Theme.of(context).colorScheme;
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
return AppBar(
|
return AppBar(
|
||||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||||
title: const Icon(Icons.settings, size: 20, semanticLabel: 'Settings'),
|
title: Text('Settings', style: TextStyle(color: colorScheme.onSurface)),
|
||||||
iconTheme: IconThemeData(color: colorScheme.onSurface),
|
iconTheme: IconThemeData(color: colorScheme.onSurface),
|
||||||
actions: [
|
actions: [
|
||||||
const RunnerUpImportBadge(),
|
const RunnerUpImportBadge(),
|
||||||
IconButton(
|
TextButton(
|
||||||
onPressed: loading ? null : onReset,
|
onPressed: loading ? null : onReset,
|
||||||
color: colorScheme.error,
|
child: Text(
|
||||||
icon: const Icon(Icons.restart_alt, semanticLabel: 'Reset defaults'),
|
'Reset defaults',
|
||||||
|
style: TextStyle(color: colorScheme.error),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -25,7 +25,7 @@ class _SoundSection extends StatelessWidget {
|
|||||||
child: SwitchListTile(
|
child: SwitchListTile(
|
||||||
value: enabled,
|
value: enabled,
|
||||||
onChanged: onChanged,
|
onChanged: onChanged,
|
||||||
title: const Icon(Icons.volume_up, size: 20, semanticLabel: 'Sound'),
|
title: Text('Sound', style: TextStyle(color: colorScheme.onSurface)),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -200,16 +200,7 @@ extension _WorkoutScreenBreaks on _WorkoutScreenState {
|
|||||||
ExerciseState? _deloadRefused(String why) {
|
ExerciseState? _deloadRefused(String why) {
|
||||||
log('WorkoutScreen: deload not applied — $why', level: 900);
|
log('WorkoutScreen: deload not applied — $why', level: 900);
|
||||||
if (mounted) {
|
if (mounted) {
|
||||||
// Was the refusal reason as a sentence; it stays in the log above.
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(why)));
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Icon(
|
|
||||||
Icons.block,
|
|
||||||
color: Theme.of(context).colorScheme.error,
|
|
||||||
semanticLabel: 'Deload refused',
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -13,28 +13,21 @@ extension _WorkoutScreenDialogs on _WorkoutScreenState {
|
|||||||
context: context,
|
context: context,
|
||||||
builder: (_) => AlertDialog(
|
builder: (_) => AlertDialog(
|
||||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||||
// Was "Finish workout?" with Cancel / Finish buttons.
|
title: Text(
|
||||||
title: Icon(
|
'Finish workout?',
|
||||||
Icons.done_all,
|
style: TextStyle(color: colorScheme.onSurface),
|
||||||
color: status.success,
|
|
||||||
semanticLabel: 'Finish workout?',
|
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.pop(context, false),
|
onPressed: () => Navigator.pop(context, false),
|
||||||
child: Icon(
|
child: Text(
|
||||||
Icons.close,
|
'Cancel',
|
||||||
color: colorScheme.onSurfaceVariant,
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
semanticLabel: 'Cancel',
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.pop(context, true),
|
onPressed: () => Navigator.pop(context, true),
|
||||||
child: Icon(
|
child: Text('Finish', style: TextStyle(color: status.success)),
|
||||||
Icons.done_all,
|
|
||||||
color: status.success,
|
|
||||||
semanticLabel: 'Finish',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@ -49,29 +42,25 @@ extension _WorkoutScreenDialogs on _WorkoutScreenState {
|
|||||||
context: context,
|
context: context,
|
||||||
builder: (_) => AlertDialog(
|
builder: (_) => AlertDialog(
|
||||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||||
// Was "Reset workout?" / "All progress will be lost." with
|
title: Text(
|
||||||
// Cancel / Reset buttons: the reset glyph in the error colour.
|
'Reset workout?',
|
||||||
title: Icon(
|
style: TextStyle(color: colorScheme.onSurface),
|
||||||
Icons.restart_alt,
|
),
|
||||||
color: colorScheme.error,
|
content: Text(
|
||||||
semanticLabel: 'Reset workout? All progress will be lost.',
|
'All progress will be lost.',
|
||||||
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.pop(context, false),
|
onPressed: () => Navigator.pop(context, false),
|
||||||
child: Icon(
|
child: Text(
|
||||||
Icons.close,
|
'Cancel',
|
||||||
color: colorScheme.onSurfaceVariant,
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
semanticLabel: 'Cancel',
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.pop(context, true),
|
onPressed: () => Navigator.pop(context, true),
|
||||||
child: Icon(
|
child: Text('Reset', style: TextStyle(color: colorScheme.error)),
|
||||||
Icons.restart_alt,
|
|
||||||
color: colorScheme.error,
|
|
||||||
semanticLabel: 'Reset',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@ -123,10 +123,9 @@ extension _WorkoutScreenIntents on _WorkoutScreenState {
|
|||||||
if (result.needsPermissionWarning && mounted) {
|
if (result.needsPermissionWarning && mounted) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
const SnackBar(
|
const SnackBar(
|
||||||
content: Icon(
|
content: Text(
|
||||||
Icons.notifications_off,
|
'Notifications are off — the rest timer still runs and still '
|
||||||
size: 20,
|
'sounds, but there will be no status-bar countdown.',
|
||||||
semanticLabel: 'Notifications are off',
|
|
||||||
),
|
),
|
||||||
duration: Duration(seconds: 6),
|
duration: Duration(seconds: 6),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -39,56 +39,37 @@ class BreakNotificationCopy {
|
|||||||
/// and testable without a device.
|
/// and testable without a device.
|
||||||
abstract final class BreakNotificationText {
|
abstract final class BreakNotificationText {
|
||||||
/// Renders the notification for [snapshot] as of [now].
|
/// 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) {
|
static BreakNotificationCopy render(BreakSnapshot snapshot, DateTime now) {
|
||||||
if (snapshot.finished) {
|
if (snapshot.finished) {
|
||||||
// Was "Workout complete" / "Open the app to save it."
|
return const BreakNotificationCopy(
|
||||||
return const BreakNotificationCopy(doneGlyph, '');
|
'Workout complete',
|
||||||
|
'Open the app to save it.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
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) {
|
static String _title(BreakSnapshot s, DateTime now) {
|
||||||
final prefix = '$liftGlyph ${s.workoutType}';
|
final prefix = 'Workout ${s.workoutType}';
|
||||||
if (!s.hasBreak) {
|
if (!s.hasBreak) {
|
||||||
return prefix;
|
return '$prefix · lift';
|
||||||
}
|
}
|
||||||
final clock = BreakClock(
|
final clock = BreakClock(
|
||||||
endTime: DateTime.fromMillisecondsSinceEpoch(s.breakEndMs),
|
endTime: DateTime.fromMillisecondsSinceEpoch(s.breakEndMs),
|
||||||
durationSecs: s.breakDurationSecs,
|
durationSecs: s.breakDurationSecs,
|
||||||
);
|
);
|
||||||
final remaining = clock.remainingSecsAt(now);
|
final remaining = clock.remainingSecsAt(now);
|
||||||
if (remaining <= 0) return '$prefix · $breakOverGlyph';
|
if (remaining <= 0) return '$prefix · break over';
|
||||||
return '$prefix · $breakGlyph ${formatMmSs(remaining)}';
|
return '$prefix · break ${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) {
|
static String _body(BreakSnapshot s) {
|
||||||
if (!s.hasNextSet) return doneGlyph;
|
if (!s.hasNextSet) return 'Every set is done — finish the workout.';
|
||||||
return '→ ${s.nextExName} ${s.nextSetNumber}/${s.nextTotalSets}\n'
|
return 'Next: ${s.nextExName} — set ${s.nextSetNumber}/${s.nextTotalSets}\n'
|
||||||
'${s.nextReps} × ${formatWeight(s.nextWeight)} kg';
|
'${s.nextReps} reps @ ${formatWeight(s.nextWeight)} kg';
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Formats [totalSecs] as `m:ss`, e.g. 107 -> `1:47`.
|
/// Formats [totalSecs] as `m:ss`, e.g. 107 -> `1:47`.
|
||||||
|
|||||||
@ -30,9 +30,6 @@ const kBreakEndSilentChannelId = 'break_end_silent_v1';
|
|||||||
/// Notification id of the terminal "workout complete" message.
|
/// Notification id of the terminal "workout complete" message.
|
||||||
const kWorkoutDoneNotificationId = 8802;
|
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.
|
/// The real [BreakServicePort], running inside the foreground-service isolate.
|
||||||
class FlutterBreakServicePort implements BreakServicePort {
|
class FlutterBreakServicePort implements BreakServicePort {
|
||||||
/// Creates a port. Cheap: nothing happens until [ensureIsolateReady].
|
/// Creates a port. Cheap: nothing happens until [ensureIsolateReady].
|
||||||
@ -67,9 +64,7 @@ class FlutterBreakServicePort implements BreakServicePort {
|
|||||||
?.createNotificationChannel(
|
?.createNotificationChannel(
|
||||||
const AndroidNotificationChannel(
|
const AndroidNotificationChannel(
|
||||||
kBreakEndChannelId,
|
kBreakEndChannelId,
|
||||||
// Channel names are the app name only (textgate settled
|
'Break finished',
|
||||||
// decision 4). Was 'Break finished' / 'Break finished, no tone'.
|
|
||||||
_kChannelName,
|
|
||||||
description: 'Sounds when a rest period between sets is over.',
|
description: 'Sounds when a rest period between sets is over.',
|
||||||
importance: Importance.max,
|
importance: Importance.max,
|
||||||
sound: RawResourceAndroidNotificationSound('break_end'),
|
sound: RawResourceAndroidNotificationSound('break_end'),
|
||||||
@ -82,7 +77,7 @@ class FlutterBreakServicePort implements BreakServicePort {
|
|||||||
?.createNotificationChannel(
|
?.createNotificationChannel(
|
||||||
const AndroidNotificationChannel(
|
const AndroidNotificationChannel(
|
||||||
kBreakEndSilentChannelId,
|
kBreakEndSilentChannelId,
|
||||||
_kChannelName,
|
'Break finished, no tone',
|
||||||
importance: Importance.max,
|
importance: Importance.max,
|
||||||
playSound: false,
|
playSound: false,
|
||||||
),
|
),
|
||||||
@ -115,13 +110,12 @@ class FlutterBreakServicePort implements BreakServicePort {
|
|||||||
}
|
}
|
||||||
await _notifications.show(
|
await _notifications.show(
|
||||||
id: kBreakEndNotificationId,
|
id: kBreakEndNotificationId,
|
||||||
// Was "Break over" / "Back to the bar.".
|
title: 'Break over',
|
||||||
title: BreakNotificationText.breakOverGlyph,
|
body: 'Back to the bar.',
|
||||||
body: '',
|
|
||||||
notificationDetails: NotificationDetails(
|
notificationDetails: NotificationDetails(
|
||||||
android: AndroidNotificationDetails(
|
android: AndroidNotificationDetails(
|
||||||
sound ? kBreakEndChannelId : kBreakEndSilentChannelId,
|
sound ? kBreakEndChannelId : kBreakEndSilentChannelId,
|
||||||
_kChannelName,
|
sound ? 'Break finished' : 'Break finished, no tone',
|
||||||
playSound: sound,
|
playSound: sound,
|
||||||
importance: Importance.max,
|
importance: Importance.max,
|
||||||
priority: Priority.max,
|
priority: Priority.max,
|
||||||
@ -140,13 +134,12 @@ class FlutterBreakServicePort implements BreakServicePort {
|
|||||||
Future<void> finishAndStop() async {
|
Future<void> finishAndStop() async {
|
||||||
await _notifications.show(
|
await _notifications.show(
|
||||||
id: kWorkoutDoneNotificationId,
|
id: kWorkoutDoneNotificationId,
|
||||||
// Was "Workout complete" / "Open the app to save it.".
|
title: 'Workout complete',
|
||||||
title: BreakNotificationText.doneGlyph,
|
body: 'Open the app to save it.',
|
||||||
body: '',
|
|
||||||
notificationDetails: const NotificationDetails(
|
notificationDetails: const NotificationDetails(
|
||||||
android: AndroidNotificationDetails(
|
android: AndroidNotificationDetails(
|
||||||
kBreakEndChannelId,
|
kBreakEndChannelId,
|
||||||
_kChannelName,
|
'Break finished',
|
||||||
importance: Importance.high,
|
importance: Importance.high,
|
||||||
priority: Priority.high,
|
priority: Priority.high,
|
||||||
),
|
),
|
||||||
|
|||||||
@ -7,7 +7,6 @@ import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
|||||||
import 'package:workout_app/models/break_snapshot.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_queue.dart';
|
||||||
import 'package:workout_app/services/break_intent_store.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.dart';
|
||||||
import 'package:workout_app/services/break_service_port_flutter.dart';
|
import 'package:workout_app/services/break_service_port_flutter.dart';
|
||||||
import 'package:workout_app/services/break_task_handler.dart';
|
import 'package:workout_app/services/break_task_handler.dart';
|
||||||
@ -22,8 +21,7 @@ import 'package:workout_app/services/foreground_break_client.dart';
|
|||||||
const kWorkoutOngoingChannelId = 'workout_ongoing_v1';
|
const kWorkoutOngoingChannelId = 'workout_ongoing_v1';
|
||||||
|
|
||||||
/// Button labels, parallel to [BreakNotificationAction.inButtonOrder].
|
/// Button labels, parallel to [BreakNotificationAction.inButtonOrder].
|
||||||
/// Symbols only; was ['✓ Done', '− 1 rep', 'Skip break'].
|
const _buttonLabels = ['✓ Done', '− 1 rep', 'Skip break'];
|
||||||
const _buttonLabels = ['✓', '−1', '⏭'];
|
|
||||||
|
|
||||||
/// Entry point the plugin calls in the background isolate.
|
/// Entry point the plugin calls in the background isolate.
|
||||||
// coverage:ignore-start
|
// coverage:ignore-start
|
||||||
@ -59,7 +57,8 @@ class _BreakServiceTaskHandler extends TaskHandler {
|
|||||||
void onRepeatEvent(DateTime timestamp) => _handler.tick(timestamp);
|
void onRepeatEvent(DateTime timestamp) => _handler.tick(timestamp);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void onReceiveData(Object data) => _handler.receiveData(data, DateTime.now());
|
void onReceiveData(Object data) =>
|
||||||
|
_handler.receiveData(data, DateTime.now());
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void onNotificationButtonPressed(String id) =>
|
void onNotificationButtonPressed(String id) =>
|
||||||
@ -93,9 +92,7 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
|
|||||||
FlutterForegroundTask.init(
|
FlutterForegroundTask.init(
|
||||||
androidNotificationOptions: AndroidNotificationOptions(
|
androidNotificationOptions: AndroidNotificationOptions(
|
||||||
channelId: kWorkoutOngoingChannelId,
|
channelId: kWorkoutOngoingChannelId,
|
||||||
// App name only (textgate settled decision 4); was 'Workout in
|
channelName: 'Workout in progress',
|
||||||
// progress'.
|
|
||||||
channelName: BreakNotificationText.channelName,
|
|
||||||
channelDescription:
|
channelDescription:
|
||||||
'Shows the rest countdown and the next set while a workout '
|
'Shows the rest countdown and the next set while a workout '
|
||||||
'runs. Kept silent on purpose: the break-end alert has its own '
|
'runs. Kept silent on purpose: the break-end alert has its own '
|
||||||
@ -133,10 +130,8 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
|
|||||||
}
|
}
|
||||||
final result = await FlutterForegroundTask.startService(
|
final result = await FlutterForegroundTask.startService(
|
||||||
serviceTypes: [ForegroundServiceTypes.dataSync],
|
serviceTypes: [ForegroundServiceTypes.dataSync],
|
||||||
// Same prefix as BreakNotificationText; was 'Workout A' / 'Starting…'.
|
notificationTitle: 'Workout ${snapshot.workoutType}',
|
||||||
notificationTitle:
|
notificationText: 'Starting…',
|
||||||
'${BreakNotificationText.liftGlyph} ${snapshot.workoutType}',
|
|
||||||
notificationText: '…',
|
|
||||||
notificationButtons: [
|
notificationButtons: [
|
||||||
for (final (i, id) in BreakNotificationAction.inButtonOrder.indexed)
|
for (final (i, id) in BreakNotificationAction.inButtonOrder.indexed)
|
||||||
NotificationButton(id: id, text: _buttonLabels[i]),
|
NotificationButton(id: id, text: _buttonLabels[i]),
|
||||||
|
|||||||
@ -4,7 +4,6 @@ library;
|
|||||||
import 'dart:io' show Platform;
|
import 'dart:io' show Platform;
|
||||||
|
|
||||||
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
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';
|
import 'package:workout_app/services/foreground_run_client.dart';
|
||||||
|
|
||||||
/// Channel the ongoing run notification lives on.
|
/// Channel the ongoing run notification lives on.
|
||||||
@ -73,8 +72,7 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
|
|||||||
FlutterForegroundTask.init(
|
FlutterForegroundTask.init(
|
||||||
androidNotificationOptions: AndroidNotificationOptions(
|
androidNotificationOptions: AndroidNotificationOptions(
|
||||||
channelId: kRunOngoingChannelId,
|
channelId: kRunOngoingChannelId,
|
||||||
// App name only (textgate settled decision 4); was the runner emoji.
|
channelName: '\u{1F3C3}',
|
||||||
channelName: BreakNotificationText.channelName,
|
|
||||||
onlyAlertOnce: true,
|
onlyAlertOnce: true,
|
||||||
),
|
),
|
||||||
iosNotificationOptions: const IOSNotificationOptions(),
|
iosNotificationOptions: const IOSNotificationOptions(),
|
||||||
|
|||||||
@ -98,35 +98,28 @@ class BreakBanner extends StatelessWidget {
|
|||||||
visible: active,
|
visible: active,
|
||||||
child: TextButton(
|
child: TextButton(
|
||||||
onPressed: onSkip,
|
onPressed: onSkip,
|
||||||
child: Icon(
|
child: Text('Skip', style: TextStyle(color: colorScheme.primary)),
|
||||||
Icons.skip_next,
|
|
||||||
color: colorScheme.primary,
|
|
||||||
semanticLabel: 'Skip',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
_slot(
|
_slot(
|
||||||
visible: !finished,
|
visible: !finished,
|
||||||
child: TextButton(
|
child: TextButton(
|
||||||
onPressed: onReset,
|
onPressed: onReset,
|
||||||
child: Icon(
|
child: Text('Reset', style: TextStyle(color: colorScheme.error)),
|
||||||
Icons.restart_alt,
|
|
||||||
color: colorScheme.error,
|
|
||||||
semanticLabel: 'Reset',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
_slot(
|
_slot(
|
||||||
visible: !finished,
|
visible: !finished,
|
||||||
child: TextButton(
|
child: TextButton(
|
||||||
onPressed: canFinish ? onFinish : null,
|
onPressed: canFinish ? onFinish : null,
|
||||||
// Muted while finishing is not allowed yet, as the old label.
|
child: Text(
|
||||||
child: Icon(
|
'Finish',
|
||||||
Icons.done_all,
|
style: TextStyle(
|
||||||
color: canFinish
|
color: canFinish
|
||||||
? status.success
|
? status.success
|
||||||
: colorScheme.onSurfaceVariant,
|
: colorScheme.onSurfaceVariant,
|
||||||
semanticLabel: 'Finish',
|
fontWeight: FontWeight.bold,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -27,16 +27,21 @@ class WorkoutCalendar extends StatelessWidget {
|
|||||||
/// Called when the user taps the next-month chevron.
|
/// Called when the user taps the next-month chevron.
|
||||||
final VoidCallback onNextMonth;
|
final VoidCallback onNextMonth;
|
||||||
|
|
||||||
// textgate: weekday headers are dots (weekend dots hollow) and the
|
static const _weekHeaders = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
|
||||||
// month header is `08.2026`; the old words are spoken only.
|
|
||||||
static const _weekdaySemanticsLabels = [
|
static const _monthNames = [
|
||||||
'Monday',
|
'January',
|
||||||
'Tuesday',
|
'February',
|
||||||
'Wednesday',
|
'March',
|
||||||
'Thursday',
|
'April',
|
||||||
'Friday',
|
'May',
|
||||||
'Saturday',
|
'June',
|
||||||
'Sunday',
|
'July',
|
||||||
|
'August',
|
||||||
|
'September',
|
||||||
|
'October',
|
||||||
|
'November',
|
||||||
|
'December',
|
||||||
];
|
];
|
||||||
|
|
||||||
String _dateKey(int year, int m, int day) =>
|
String _dateKey(int year, int m, int day) =>
|
||||||
@ -76,7 +81,7 @@ class WorkoutCalendar extends StatelessWidget {
|
|||||||
onPressed: onPrevMonth,
|
onPressed: onPrevMonth,
|
||||||
),
|
),
|
||||||
Text(
|
Text(
|
||||||
'${m.toString().padLeft(2, '0')}.$year',
|
'${_monthNames[m - 1]} $year',
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: colorScheme.onSurface,
|
color: colorScheme.onSurface,
|
||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.bold,
|
||||||
@ -98,29 +103,22 @@ class WorkoutCalendar extends StatelessWidget {
|
|||||||
// Day-of-week headers
|
// Day-of-week headers
|
||||||
Row(
|
Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||||
children: [
|
children: _weekHeaders
|
||||||
for (var i = 0; i < 7; i++)
|
.map(
|
||||||
SizedBox(
|
(h) => SizedBox(
|
||||||
width: 30,
|
width: 30,
|
||||||
child: Semantics(
|
child: Text(
|
||||||
label: _weekdaySemanticsLabels[i],
|
h,
|
||||||
child: Center(
|
textAlign: TextAlign.center,
|
||||||
child: Container(
|
style: TextStyle(
|
||||||
width: 6,
|
color: colorScheme.onSurfaceVariant,
|
||||||
height: 6,
|
fontSize: AppTextSize.caption,
|
||||||
decoration: BoxDecoration(
|
fontWeight: FontWeight.bold,
|
||||||
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),
|
const SizedBox(height: 4),
|
||||||
// Day grid
|
// Day grid
|
||||||
|
|||||||
@ -89,15 +89,14 @@ class _ExerciseSettingsSheetState extends State<ExerciseSettingsSheet> {
|
|||||||
setState(() => _s = next);
|
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) {
|
String get _modeHint => switch (_s.mode) {
|
||||||
ProgressionMode.weight =>
|
ProgressionMode.weight =>
|
||||||
'+$kWeightIncrement kg · ${_s.maxWeight} kg ⇒ +1',
|
'+$kWeightIncrement kg per step; +1 rep once at the '
|
||||||
ProgressionMode.reps => '+1',
|
'${_s.maxWeight} kg cap',
|
||||||
|
ProgressionMode.reps => '+1 rep per step; the weight never changes',
|
||||||
ProgressionMode.doubleProgression =>
|
ProgressionMode.doubleProgression =>
|
||||||
'+1 … ${_s.repsHigh} ⇒ +$kWeightIncrement kg, ${_s.repsLow}',
|
'+1 rep per step up to ${_s.repsHigh}, then +$kWeightIncrement kg '
|
||||||
|
'and back to ${_s.repsLow}',
|
||||||
};
|
};
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@ -131,16 +130,15 @@ class _ExerciseSettingsSheetState extends State<ExerciseSettingsSheet> {
|
|||||||
segments: const [
|
segments: const [
|
||||||
ButtonSegment(
|
ButtonSegment(
|
||||||
value: ProgressionMode.weight,
|
value: ProgressionMode.weight,
|
||||||
// Was 'Weight' / 'Reps' / 'Reps→kg'.
|
label: Text('Weight'),
|
||||||
label: Icon(Icons.fitness_center, semanticLabel: 'Weight'),
|
|
||||||
),
|
),
|
||||||
ButtonSegment(
|
ButtonSegment(
|
||||||
value: ProgressionMode.reps,
|
value: ProgressionMode.reps,
|
||||||
label: Icon(Icons.repeat, semanticLabel: 'Reps'),
|
label: Text('Reps'),
|
||||||
),
|
),
|
||||||
ButtonSegment(
|
ButtonSegment(
|
||||||
value: ProgressionMode.doubleProgression,
|
value: ProgressionMode.doubleProgression,
|
||||||
label: Icon(Icons.trending_up, semanticLabel: 'Reps→kg'),
|
label: Text('Reps→kg'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
selected: {_s.mode},
|
selected: {_s.mode},
|
||||||
@ -162,14 +160,12 @@ class _ExerciseSettingsSheetState extends State<ExerciseSettingsSheet> {
|
|||||||
maintainAnimation: true,
|
maintainAnimation: true,
|
||||||
maintainState: true,
|
maintainState: true,
|
||||||
child: _SettingRow(
|
child: _SettingRow(
|
||||||
// Was "+kg at [N] reps, restart at [M]".
|
label: '+kg at',
|
||||||
label: '+',
|
|
||||||
icon: Icons.fitness_center,
|
|
||||||
name: 'Top reps',
|
name: 'Top reps',
|
||||||
value: _s.repsHigh,
|
value: _s.repsHigh,
|
||||||
min: _s.repsLow + 1,
|
min: _s.repsLow + 1,
|
||||||
max: _maxRepsHigh,
|
max: _maxRepsHigh,
|
||||||
suffix: '↺',
|
suffix: 'reps, restart at',
|
||||||
trailing: _Stepper(
|
trailing: _Stepper(
|
||||||
name: 'Restart reps',
|
name: 'Restart reps',
|
||||||
value: _s.repsLow,
|
value: _s.repsLow,
|
||||||
@ -183,22 +179,17 @@ class _ExerciseSettingsSheetState extends State<ExerciseSettingsSheet> {
|
|||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
SwitchListTile(
|
SwitchListTile(
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
// Was 'Warmup set'; the sun matches the warmup rest row.
|
title: const Text('Warmup set'),
|
||||||
title: const Align(
|
|
||||||
alignment: Alignment.centerLeft,
|
|
||||||
child: Icon(Icons.wb_sunny, semanticLabel: 'Warmup set'),
|
|
||||||
),
|
|
||||||
value: _s.hasWarmup,
|
value: _s.hasWarmup,
|
||||||
onChanged: (v) => _update(_s.copyWith(hasWarmup: v)),
|
onChanged: (v) => _update(_s.copyWith(hasWarmup: v)),
|
||||||
),
|
),
|
||||||
_SettingRow(
|
_SettingRow(
|
||||||
// Was "↑ after [N] wins, ↓ after [M]".
|
label: '↑ after',
|
||||||
label: '↑',
|
|
||||||
name: 'Wins needed',
|
name: 'Wins needed',
|
||||||
value: _s.successThreshold,
|
value: _s.successThreshold,
|
||||||
min: 1,
|
min: 1,
|
||||||
max: 5,
|
max: 5,
|
||||||
suffix: '↓',
|
suffix: 'wins, ↓ after',
|
||||||
trailing: _Stepper(
|
trailing: _Stepper(
|
||||||
name: 'Fails allowed',
|
name: 'Fails allowed',
|
||||||
value: _s.failThreshold,
|
value: _s.failThreshold,
|
||||||
|
|||||||
@ -18,16 +18,16 @@ class _DeloadRow extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final colorScheme = Theme.of(context).colorScheme;
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
final change = describeTargetChange(state, targetAfterFailure(state));
|
final change = describeTargetChange(state, targetAfterFailure(state));
|
||||||
final canDeload = change != kNoTargetChange;
|
final canDeload = change != 'same';
|
||||||
return SizedBox(
|
return SizedBox(
|
||||||
height: 40,
|
height: 40,
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
// Was "Deload <target> → <change>" / "Deload nothing lower to
|
|
||||||
// go to": the down-trend glyph is the button, the numbers stay.
|
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Text(
|
||||||
canDeload ? '${_target(state)} → $change' : '—',
|
canDeload
|
||||||
|
? 'Deload ${_target(state)} → $change'
|
||||||
|
: 'Deload nothing lower to go to',
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: colorScheme.onSurface,
|
color: colorScheme.onSurface,
|
||||||
fontSize: AppTextSize.label,
|
fontSize: AppTextSize.label,
|
||||||
@ -37,11 +37,7 @@ class _DeloadRow extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: canDeload ? onDeload : null,
|
onPressed: canDeload ? onDeload : null,
|
||||||
child: Icon(
|
child: const Text('Deload now'),
|
||||||
Icons.trending_down,
|
|
||||||
color: canDeload ? colorScheme.error : null,
|
|
||||||
semanticLabel: 'Deload now',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@ -66,33 +62,26 @@ Future<bool> _confirmDeload(BuildContext context, ExerciseState s) async {
|
|||||||
context: context,
|
context: context,
|
||||||
builder: (dialogContext) => AlertDialog(
|
builder: (dialogContext) => AlertDialog(
|
||||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||||
// Was "Deload <name>?" / "<target> → <change>\n\nStreaks reset. Only
|
title: Text(
|
||||||
// finished workouts raise it again.": glyph + the numbers.
|
'Deload ${s.name}?',
|
||||||
title: Icon(
|
style: TextStyle(color: colorScheme.onSurface),
|
||||||
Icons.trending_down,
|
|
||||||
color: colorScheme.error,
|
|
||||||
semanticLabel: 'Deload ${s.name}?',
|
|
||||||
),
|
),
|
||||||
content: Text(
|
content: Text(
|
||||||
'${_target(s)} → $change',
|
'${_target(s)} → $change\n\n'
|
||||||
|
'Streaks reset. Only finished workouts raise it again.',
|
||||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.pop(dialogContext, false),
|
onPressed: () => Navigator.pop(dialogContext, false),
|
||||||
child: Icon(
|
child: Text(
|
||||||
Icons.close,
|
'Cancel',
|
||||||
color: colorScheme.onSurfaceVariant,
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
semanticLabel: 'Cancel',
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.pop(dialogContext, true),
|
onPressed: () => Navigator.pop(dialogContext, true),
|
||||||
child: Icon(
|
child: Text('Deload', style: TextStyle(color: colorScheme.error)),
|
||||||
Icons.trending_down,
|
|
||||||
color: colorScheme.error,
|
|
||||||
semanticLabel: 'Deload',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@ -35,7 +35,7 @@ class _RestRows extends StatelessWidget {
|
|||||||
children: [
|
children: [
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
Text('✓', style: style),
|
Text('Rest ✓', style: style),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
_stepper(
|
_stepper(
|
||||||
'Success rest',
|
'Success rest',
|
||||||
@ -60,7 +60,7 @@ class _RestRows extends StatelessWidget {
|
|||||||
maintainState: true,
|
maintainState: true,
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
Text('☀', style: style),
|
Text('Warmup rest', style: style),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
_stepper(
|
_stepper(
|
||||||
'Warmup rest',
|
'Warmup rest',
|
||||||
|
|||||||
@ -14,14 +14,10 @@ class _SettingRow extends StatelessWidget {
|
|||||||
required this.suffix,
|
required this.suffix,
|
||||||
required this.trailing,
|
required this.trailing,
|
||||||
required this.onChanged,
|
required this.onChanged,
|
||||||
this.icon,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final String label;
|
final String label;
|
||||||
|
|
||||||
/// Optional glyph painted right after [label] (e.g. `+` then a weight).
|
|
||||||
final IconData? icon;
|
|
||||||
|
|
||||||
/// Semantic name of the leading stepper.
|
/// Semantic name of the leading stepper.
|
||||||
final String name;
|
final String name;
|
||||||
final int value;
|
final int value;
|
||||||
@ -40,8 +36,6 @@ class _SettingRow extends StatelessWidget {
|
|||||||
return Row(
|
return Row(
|
||||||
children: [
|
children: [
|
||||||
Text(label, style: style),
|
Text(label, style: style),
|
||||||
if (icon != null)
|
|
||||||
Icon(icon, size: AppTextSize.label, color: style.color),
|
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
_Stepper(
|
_Stepper(
|
||||||
name: name,
|
name: name,
|
||||||
@ -180,13 +174,7 @@ class _PauseRow extends StatelessWidget {
|
|||||||
child: Row(
|
child: Row(
|
||||||
children: until == null
|
children: until == null
|
||||||
? [
|
? [
|
||||||
// Was "Pause for [N] days": a calendar for the day count,
|
Text('Pause for', style: style),
|
||||||
// the pause glyph only on the button.
|
|
||||||
Icon(
|
|
||||||
Icons.calendar_today,
|
|
||||||
size: 18,
|
|
||||||
color: colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
_Stepper(
|
_Stepper(
|
||||||
name: 'Pause days',
|
name: 'Pause days',
|
||||||
@ -196,37 +184,23 @@ class _PauseRow extends StatelessWidget {
|
|||||||
onChanged: onDaysChanged,
|
onChanged: onDaysChanged,
|
||||||
),
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
|
Text('days', style: style),
|
||||||
const Spacer(),
|
const Spacer(),
|
||||||
TextButton(
|
TextButton(onPressed: onPause, child: const Text('Pause')),
|
||||||
onPressed: onPause,
|
|
||||||
child: const Icon(
|
|
||||||
Icons.pause,
|
|
||||||
size: 20,
|
|
||||||
semanticLabel: 'Pause',
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
]
|
||||||
: [
|
: [
|
||||||
// textgate: was "Paused — back on 11 Oct".
|
|
||||||
Icon(
|
Icon(
|
||||||
Icons.pause_circle_outline,
|
Icons.pause_circle_outline,
|
||||||
size: 18,
|
size: 18,
|
||||||
color: colorScheme.error,
|
color: colorScheme.error,
|
||||||
semanticLabel: 'Paused',
|
|
||||||
),
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
Icon(Icons.arrow_forward, size: 16, color: colorScheme.error),
|
Text(
|
||||||
const SizedBox(width: 4),
|
'Paused — back on ${formatShortDate(until)}',
|
||||||
Text(formatShortDate(until), style: style),
|
style: style,
|
||||||
const Spacer(),
|
|
||||||
TextButton(
|
|
||||||
onPressed: onResume,
|
|
||||||
child: const Icon(
|
|
||||||
Icons.play_arrow,
|
|
||||||
size: 20,
|
|
||||||
semanticLabel: 'Resume',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
|
const Spacer(),
|
||||||
|
TextButton(onPressed: onResume, child: const Text('Resume')),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@ -20,22 +20,18 @@ class _ModeChip extends StatelessWidget {
|
|||||||
|
|
||||||
static const double width = 64;
|
static const double width = 64;
|
||||||
|
|
||||||
// textgate: was 'kg' / 'reps'. The same mode glyphs as the settings
|
String get _text => switch (state.mode) {
|
||||||
// sheet's segmented control; double progression keeps its rep range.
|
ProgressionMode.weight => 'kg',
|
||||||
IconData? get _modeIcon => switch (state.mode) {
|
ProgressionMode.reps => 'reps',
|
||||||
ProgressionMode.weight => Icons.fitness_center,
|
ProgressionMode.doubleProgression => '${state.repsLow}→${state.repsHigh}',
|
||||||
ProgressionMode.reps => Icons.repeat,
|
|
||||||
ProgressionMode.doubleProgression => null,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
// Spoken only: excludeSemantics hides the painted children from it.
|
|
||||||
final semanticsLabel = '${state.name} progression settings';
|
|
||||||
return Semantics(
|
return Semantics(
|
||||||
container: true,
|
container: true,
|
||||||
button: true,
|
button: true,
|
||||||
label: semanticsLabel,
|
label: '${state.name} progression settings',
|
||||||
excludeSemantics: true,
|
excludeSemantics: true,
|
||||||
child: InkWell(
|
child: InkWell(
|
||||||
onTap: onTap,
|
onTap: onTap,
|
||||||
@ -54,17 +50,12 @@ class _ModeChip extends StatelessWidget {
|
|||||||
Icon(Icons.tune, size: 13, color: color),
|
Icon(Icons.tune, size: 13, color: color),
|
||||||
const SizedBox(width: 3),
|
const SizedBox(width: 3),
|
||||||
Flexible(
|
Flexible(
|
||||||
child: _modeIcon == null
|
child: Text(
|
||||||
? Text(
|
_text,
|
||||||
'${state.repsLow}→${state.repsHigh}',
|
maxLines: 1,
|
||||||
maxLines: 1,
|
overflow: TextOverflow.ellipsis,
|
||||||
overflow: TextOverflow.ellipsis,
|
style: TextStyle(color: color, fontSize: AppTextSize.caption),
|
||||||
style: TextStyle(
|
),
|
||||||
color: color,
|
|
||||||
fontSize: AppTextSize.caption,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: Icon(_modeIcon, size: 14, color: color),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@ -211,24 +202,16 @@ class _PausedRow extends StatelessWidget {
|
|||||||
height: ExerciseTile.setRowHeight,
|
height: ExerciseTile.setRowHeight,
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
// textgate: was "Paused — back on 11 Oct · counts as failed".
|
Icon(Icons.pause_circle_outline, size: 20, color: color),
|
||||||
// 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),
|
const SizedBox(width: 8),
|
||||||
Icon(Icons.arrow_forward, size: 16, color: color),
|
Expanded(
|
||||||
const SizedBox(width: 4),
|
child: Text(
|
||||||
Text(
|
'Paused — back on ${formatShortDate(until)} · counts as failed',
|
||||||
formatShortDate(until),
|
maxLines: 1,
|
||||||
key: const Key('paused_until'),
|
overflow: TextOverflow.ellipsis,
|
||||||
style: TextStyle(color: color, fontSize: AppTextSize.label),
|
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
Loading…
Reference in New Issue
Block a user