mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-24 19:06:24 +01:00
Compare commits
33 Commits
3476dd3afd
...
22294ec541
| Author | SHA1 | Date | |
|---|---|---|---|
| 22294ec541 | |||
| a7ca5bfbb4 | |||
| b6414c7f1c | |||
| ac7a7afa08 | |||
| 1e4719b4de | |||
| e2721b5a29 | |||
| 786d261d9e | |||
| a4b189ee3b | |||
| 1e72b61826 | |||
| 0c49039378 | |||
| 78db299086 | |||
| 99302c2be7 | |||
| 96f6e5f8cb | |||
| 2bb84f6d1b | |||
| 9e4c45dfa3 | |||
| 5977475021 | |||
| 9184a6bc33 | |||
| 3d992ef71b | |||
| 3a587d6cf9 | |||
| 8293dd88d0 | |||
| f74687064e | |||
| 40a2f28734 | |||
| 338ef5ed9b | |||
| d418994f6f | |||
| 38e8364306 | |||
| b8cf634fa6 | |||
| 76a4c6a0a7 | |||
| 8bc981da4e | |||
| 094a1fe5ed | |||
| f5c6c2fb9d | |||
| bdc405c8c9 | |||
| 43a8b1d0f6 | |||
| 0714c2264d |
4
.github/workflows/python-tests.yml
vendored
4
.github/workflows/python-tests.yml
vendored
@ -50,4 +50,6 @@ jobs:
|
||||
pip install -e . --no-deps
|
||||
|
||||
- name: Sport selector survives gatelock's recovery tick
|
||||
run: python3 scripts/verify_lock_popup_safety.py
|
||||
# Run as a module (like the screen-fits gate) so scripts/ resolves as a
|
||||
# package and the check can import the helpers it was split into.
|
||||
run: python3 -m scripts.verify_lock_popup_safety
|
||||
|
||||
@ -48,7 +48,9 @@ repos:
|
||||
types: [python]
|
||||
- id: requirements-sync
|
||||
name: requirements.txt covers all package imports
|
||||
entry: python3 scripts/check_requirements_sync.py
|
||||
# scripts/ became a real package (it now holds shared helpers), so
|
||||
# auto-detection sees two candidates -- name the one that ships.
|
||||
entry: python3 scripts/check_requirements_sync.py --package screen_locker
|
||||
language: system
|
||||
pass_filenames: false
|
||||
files: ^(screen_locker/.*\.py|requirements\.txt)$
|
||||
@ -182,10 +184,13 @@ repos:
|
||||
language: system
|
||||
types: [shell]
|
||||
- id: max-file-length
|
||||
name: Max file length (400 lines)
|
||||
name: Max file length (250 lines)
|
||||
entry: python3 scripts/check_file_length.py
|
||||
language: system
|
||||
types_or: [python, shell]
|
||||
# Dart was missing here until 2026-08-15, so the cap had never looked at
|
||||
# a single file in workout_app/ — the whole Flutter app was exempt from
|
||||
# the gate it was being refactored to satisfy.
|
||||
types_or: [python, shell, dart]
|
||||
- id: no-silent-failures
|
||||
name: Block silent failures (swallowed exceptions must log why)
|
||||
entry: python3 scripts/check_silent_failures.py
|
||||
|
||||
@ -9,333 +9,11 @@ was checked with `git -C ~/utils/gatelock rev-parse --show-toplevel` → prints
|
||||
**not its own git repo**. Per audit scope, no separate gatelock report was
|
||||
written; see the "Shared gatelock library" section at the end instead.
|
||||
|
||||
## Python/Tkinter lock UI (screen_locker/)
|
||||
Split into one file per audited surface to stay under the repo's 250-line
|
||||
cap; the findings themselves are unchanged.
|
||||
|
||||
Design-token entry point check: **no `ttk.Style()` call anywhere in the
|
||||
package** (confirmed via repo-wide grep) and `_constants.py` holds only
|
||||
business-logic constants (budgets, timeouts, file paths) — zero color/font/
|
||||
spacing tokens. Every color, font, and padding value is a literal typed
|
||||
directly at each `tk.Label`/`tk.Button`/`tk.Frame`/`tk.Entry` call site,
|
||||
independently, in 9 files. Evidence:
|
||||
## Sections
|
||||
|
||||
- Hex color literals: **100 occurrences, 23 distinct values**, across
|
||||
`screen_lock.py` (6), `_ui_widgets.py` (6), `_window_setup.py` (3),
|
||||
`status_view.py` (21), `_heat_skip.py` (7 + 4 module-level constants),
|
||||
`_manual_workout_dialog.py` (15), `_manual_workout_widgets.py` (12),
|
||||
`_sick_dialog.py` (18), `_temperature_status_mixin.py` (5).
|
||||
`#1a1a1a` alone (the background) appears **31 times** — and it is *also*
|
||||
already defined once, correctly, as `LockConfig.bg = "#1a1a1a"` in
|
||||
`~/utils/gatelock/gatelock/_window.py:71`. None of the 31 in-repo literals
|
||||
import or reference it; `LockWindow.setup()` in gatelock applies
|
||||
`config.bg` to the root window (`_window.py:143`), and then every
|
||||
screen-locker dialog re-hardcodes the same string as if gatelock's value
|
||||
didn't exist.
|
||||
- `font=("Arial", N[, "bold"])` literals: **25 occurrences**, 6 distinct
|
||||
size/weight combos, e.g. `_ui_widgets.py:45,64`, `_sick_dialog.py:111,121`,
|
||||
`_manual_workout_widgets.py:70,89,97,116,126,137,145,164,174`.
|
||||
`_heat_skip.py:12-17` breaks pattern entirely with its own local
|
||||
`_FONT = "monospace"` constant (line 17) plus four color constants
|
||||
(`_BG`, `_FG_MAIN`, `_FG_SUB`, `_BTN_SKIP`, `_BTN_NO`) — the only file in
|
||||
the package that centralizes *anything*, and it does so locally/unshared
|
||||
rather than in a common module.
|
||||
- `padx=`/`pady=` literals: **59 occurrences**, 13 distinct values (1, 2, 5,
|
||||
6, 8, 10, 12, 14, 15, 20, 28, 30) spread across 7 of the 9 files.
|
||||
|
||||
### Violations
|
||||
|
||||
- **Rule 4 (everything deliberate / single source of truth)** — No
|
||||
`ttk.Style()`, no shared colors/fonts/spacing module. Same visual decision
|
||||
(e.g. background `#1a1a1a`) is independently re-typed 31 times across 9
|
||||
files instead of imported once. `_heat_skip.py:12-17` even invents its own
|
||||
local token block, proving the pattern was known and simply not applied
|
||||
package-wide. Fixing any single visual value (e.g. rebranding the
|
||||
background) means editing up to 9 files by hand with no compiler/lint
|
||||
check that all sites were caught.
|
||||
- **Rule 1 (near-black/white, not pure)** — `bg="#1a1a1a"` (near-black,
|
||||
fine) is paired with pure white text: `_ui_widgets.py:38,57` default
|
||||
`color: str = "white"`, plus explicit `fg="white"` at `_window_setup.py:40`,
|
||||
`_sick_dialog.py:112,128,138` (X11 name `"white"` = `#FFFFFF`), and 6 more
|
||||
in `_manual_workout_widgets.py` (lines 90, 112→ label fg, 116, 137, 158,
|
||||
165). Pure-white-on-near-black is the harsh contrast this rule warns
|
||||
against; should be a near-white (e.g. `#f0f0f0`/`#eaeaea`).
|
||||
- **Rule 2 (saturate your neutrals)** — `#1a1a1a` and `#2a2a2a` have equal
|
||||
R=G=B (26,26,26 and 42,42,42): true zero-saturation gray, not tinted warm
|
||||
or cool. Generic gray per the rule's definition.
|
||||
- **Rule 9 (distinct brightness values in a palette)** — `#ffaa00` (warning/
|
||||
bonus amber, e.g. `screen_lock.py:319`, `status_view.py:181`) and
|
||||
`#ff8844` (network/temp-check failure, e.g. `status_view.py:121,243`,
|
||||
`_temperature_status_mixin.py:50,57,65`) are near-identical in hue and
|
||||
brightness despite signaling different states (bonus/pending vs.
|
||||
error/failure) — they will read as the same color at a glance.
|
||||
- **Rule 11 (mathematically related measurements)** — `padx`/`pady` values
|
||||
(1, 2, 5, 6, 8, 10, 12, 14, 15, 20, 28, 30) don't follow a consistent
|
||||
scale (not all multiples of 4 or 8); e.g. `pady=1` at `status_view.py:177`
|
||||
sits next to `pady=2` (`status_view.py:160`) and `pady=28`
|
||||
(`_heat_skip.py:74`) elsewhere — no discernible spacing system.
|
||||
- **Rule 20 (body text ≥16px)** — Multiple body-text sizes sit well under
|
||||
16px: `font_size=10` at `status_view.py:248,253,255` (the last one,
|
||||
line 255, also uses the lowest-contrast color in the file, `#666666`, for
|
||||
a 10px label — compounding readability), `font_size=11` at
|
||||
`status_view.py:199`, `_heat_skip.py:91,104` (`font=(_FONT, 11)`),
|
||||
`font_size=12` at `status_view.py:160,212,225,239,243`,
|
||||
`_temperature_status_mixin.py:43,50,57,65`, `_sick_dialog.py:135`
|
||||
(`font=("Arial", 12)` on the `tk.Text` justification box), `font_size=13`
|
||||
at `status_view.py:121,123,181`.
|
||||
- **Rule 21 (line length ~70 chars)** — No widget in the package sets
|
||||
`wraplength` (confirmed: zero matches for `wraplength` repo-wide), so long
|
||||
strings render as one unbroken line regardless of window width. Concrete
|
||||
case: `_sick_dialog.py:205-207`, the commitment-prompt text "If you say
|
||||
YES and skip via 'I'm sick' tomorrow, the sick day costs 2x normal." is
|
||||
~80 characters and will render as a single line at `font_size=16` with no
|
||||
wrap control.
|
||||
- **Rule 22 (button padding: horizontal ≈2x vertical)** — Only
|
||||
`_heat_skip.py:92,93,105,106` sets explicit button padding
|
||||
(`padx=14, pady=5`, ratio 2.8x — roughly compliant). Every other button in
|
||||
the package goes through `UIWidgetsMixin._button()`
|
||||
(`_ui_widgets.py:71-90`), which sets no `padx`/`pady` at all and relies on
|
||||
Tk's built-in default padding — a different, unspecified ratio. Button
|
||||
proportions are therefore inconsistent across dialogs, not a deliberate
|
||||
choice.
|
||||
- **Rule 27 (don't mix depth techniques)** — `UIWidgetsMixin._button()`
|
||||
(`_ui_widgets.py:71-90`) sets no `relief`, so every button in
|
||||
`status_view.py`, `_sick_dialog.py`, `_manual_workout_dialog.py`, and
|
||||
`_manual_workout_widgets.py` uses Tk's default `relief="raised"` (a faux
|
||||
3D bevel). `_heat_skip.py:94,107` explicitly overrides to
|
||||
`relief="flat"` for its two buttons only — one dialog in the app uses a
|
||||
flat depth style while every other dialog uses a raised/beveled one.
|
||||
|
||||
### Not applicable
|
||||
|
||||
- Rule 5 (optical alignment) — no asymmetric icon/shape glyphs requiring
|
||||
eye-adjusted centering; text/emoji labels only.
|
||||
- Rule 6 (letter-spacing/line-height by size) — Tk's `font=` tuple has no
|
||||
letter-spacing or line-height controls; not expressible in this stack.
|
||||
- Rule 7 (border contrast) — no widget in the package sets `borderwidth`
|
||||
or a visible border color (only one incidental `highlightthickness=0` at
|
||||
`_manual_workout_dialog.py:72`, which removes a border, not adds one).
|
||||
- Rule 8 (align with something else) — pack/grid layouts are internally
|
||||
consistent per-dialog; no cross-dialog layout grid to check against.
|
||||
- Rule 12 (order by visual weight) — button rows use uniform-weight buttons
|
||||
(same size/style, only color differs); no weight hierarchy to evaluate.
|
||||
- Rule 13 (12-column grid) — fixed 2-column form grid
|
||||
(`_manual_workout_widgets.py:26-49`) is a bespoke field layout, not a page
|
||||
grid system this rule targets.
|
||||
- Rule 14 (space between contrast edges, not bounding box) — cannot be
|
||||
verified from source without rendering; Tk widgets' effective visual
|
||||
edges vs. bounding boxes aren't determinable statically.
|
||||
- Rule 15 (closer elements lighter) — single flat z-plane throughout; no
|
||||
layered/stacked surfaces.
|
||||
- Rule 16 (shadow blur ≈ 2x offset) — no shadows anywhere in the package.
|
||||
- Rule 17 (simple on complex) — flat solid backgrounds behind all text;
|
||||
trivially compliant, nothing to flag.
|
||||
- Rule 18 (container brightness limits) — the one adjacent pair found,
|
||||
`#1a1a1a` (bg, luma 10.2%) vs. `#2a2a2a` (entry/spinbox fields, luma
|
||||
16.5%), differs by ~6.3 percentage points — within the ~12% dark-mode
|
||||
limit. Pass.
|
||||
- Rule 19 (outer padding ≥ inner padding) — the lock window has no bounded
|
||||
"container" with edge padding (content is `place(relx=0.5, rely=0.5,
|
||||
anchor="center")` on a fullscreen root); the outer/inner relationship this
|
||||
rule assumes doesn't apply to a centered-content-on-fullscreen-canvas
|
||||
layout.
|
||||
- Rule 23 (two typefaces max) — only "Arial" and "monospace"
|
||||
(`_heat_skip.py:17`) appear; 2 total, within the limit (the inconsistency
|
||||
of *where* each is used is captured under Rule 4 above, not this rule).
|
||||
- Rule 24 (nest corners) — no widget sets a corner radius (stock Tk widgets
|
||||
are rectangular); nothing to nest.
|
||||
- Rule 25 (avoid adjacent hard divides) — no borders/dividers used anywhere;
|
||||
nothing to conflict.
|
||||
- Rule 26 (no shadows in dark interfaces) — Pass by omission: no shadows
|
||||
exist in this dark-background UI.
|
||||
- Rule 28 (lower icon contrast next to text) — emoji glyphs (💪, 😷, ✓, ☀,
|
||||
⚠, 🔥) share the same `fg=` color as their surrounding text; Tk offers no
|
||||
per-glyph opacity control within one Label's text, so this can't be
|
||||
addressed without moving emoji into separate, independently-colored
|
||||
widgets.
|
||||
|
||||
### Notes
|
||||
|
||||
- The absence of any shared theme/constants module means every rule above
|
||||
that *did* pass (18, 26) did so incidentally, not by design — there's no
|
||||
guard rail keeping it that way as new dialogs get added.
|
||||
- `_heat_skip.py`'s local `_BG`/`_FG_MAIN`/`_FG_SUB`/`_BTN_SKIP`/`_BTN_NO`/
|
||||
`_FONT` constants are the one place in the package that already knows
|
||||
centralizing tokens is worth doing — promoting this pattern to a shared
|
||||
`screen_locker/_theme.py` (or, better, sourcing from gatelock's
|
||||
`LockConfig`) would fix Rule 4 and cascade-fix several of the violations
|
||||
above in one pass.
|
||||
|
||||
## Flutter app (stronglift_replacement/workout_app/)
|
||||
|
||||
Design-token entry point: `lib/main.dart:68-74` declares
|
||||
`ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo,
|
||||
brightness: Brightness.dark), useMaterial3: true)` — a real Material 3 seed
|
||||
theme exists. However, **`Theme.of(context)` / `colorScheme` is referenced
|
||||
zero times anywhere in `lib/screens/` or `lib/widgets/`** (confirmed via
|
||||
repo-wide grep). The theme is declared but never consumed — every one of the
|
||||
24 .dart files under `lib/` hardcodes colors directly instead.
|
||||
|
||||
- `Colors.*` literals: **~210 occurrences** across `screens/` and
|
||||
`widgets/`, 27 distinct named colors. Most common: `Colors.white` (98×),
|
||||
`Colors.grey.shade800` (18×), `Colors.redAccent` (12×),
|
||||
`Colors.greenAccent` (11×), `Colors.grey.shade900` (10×).
|
||||
- Raw hex `Color(0xFF...)` literals bypassing `Colors.*` entirely:
|
||||
`manual_workout_screen.dart:173,201` (`Color(0xFFFF4444)`) and
|
||||
`manual_workout_screen.dart:238,246` (`Color(0xFF88CCFF)`) — these are the
|
||||
**exact same hex values** independently hardcoded on the Python/Tkinter
|
||||
side (`#ff4444` and `#88ccff`, see e.g. `_sick_dialog.py:70`,
|
||||
`_manual_workout_dialog.py:58`), coincidentally kept in sync only because
|
||||
no one has touched either yet.
|
||||
- `fontSize:`/`fontWeight:` literals: 72 occurrences; `history_screen.dart`
|
||||
alone uses 12 distinct font sizes (9, 11, 12, 13, 14, 15, 16, 17, 18, 20,
|
||||
22, 26).
|
||||
|
||||
### Violations
|
||||
|
||||
- **Rule 4 (everything deliberate / single source of truth)** — `main.dart`
|
||||
builds a `ColorScheme.fromSeed`, but it is dead code from a theming
|
||||
standpoint: no screen or widget reads it. Every screen re-derives its own
|
||||
ad hoc dark palette from `Colors.grey.shade900/800/700` plus assorted
|
||||
accent colors, so a single rebrand (e.g. changing the seed color) would
|
||||
require manually editing all 24 files instead of one.
|
||||
- **Rule 1 (near-black/white, not pure)** — `Colors.white` (pure `#FFFFFF`)
|
||||
used 98 times for primary text/icons, e.g. `home_screen.dart:113,122,128,
|
||||
211,248,267`, `settings_screen.dart:231,278,430`,
|
||||
`history_screen.dart:209,410`. `Colors.black` also appears at
|
||||
`rep_circle.dart:76` (`Colors.black87`, near-pure) as text-on-white in the
|
||||
neutral rep-circle state. None of these are the theme's actual
|
||||
near-white/near-black — they're Flutter's pure-value constants.
|
||||
- **Rule 2 (saturate your neutrals)** — `Colors.grey.shade900/800/700/400`
|
||||
are Material's standard zero-saturation grays (equal R=G=B), used as the
|
||||
entire background/surface system in place of `colorScheme.surface`
|
||||
(which, being seeded from indigo, *would* be saturated). Bypassing the
|
||||
theme produces exactly the generic-gray outcome the theme was set up to
|
||||
avoid.
|
||||
- **Rule 9 (distinct brightness values)** — `Colors.redAccent` (errors) and
|
||||
`Colors.orangeAccent`/`Colors.orange.shade800` (pending/resume state) are
|
||||
both used as status-signal colors of similar brightness in adjacent UI
|
||||
(e.g. `home_screen.dart:222` orangeAccent for active-session text next to
|
||||
`Colors.greenAccent` for success at line 200 — three status colors of
|
||||
comparable weight competing in one card).
|
||||
- **Rule 18 (container brightness limits, dark ≤~12%)** — The repeated
|
||||
`Scaffold(backgroundColor: Colors.grey.shade900)` /
|
||||
`AppBar(backgroundColor: Colors.grey.shade800)` pairing (Material
|
||||
`shade900`=`#212121`, luma 12.9%; `shade800`=`#424242`, luma 25.9% — a
|
||||
~13-point jump) appears in every screen's `Scaffold`/`AppBar`:
|
||||
`home_screen.dart:104,106`, `settings_screen.dart:275,277`,
|
||||
`history_screen.dart:206,208`, `workout_screen.dart:495,498`,
|
||||
`manual_workout_screen.dart:154,156`. This exceeds the ~12% dark-interface
|
||||
guideline every time it's used.
|
||||
- **Rule 20 (body text ≥16px)** — Extensive small body text below 16px:
|
||||
`fontSize: 9` at `history_screen.dart:612`, `fontSize: 11` (11 occurrences,
|
||||
e.g. `home_screen.dart:311`, `history_screen.dart:333,486,612`,
|
||||
`settings_screen.dart:388`), `fontSize: 12` (14 occurrences),
|
||||
`fontSize: 13` (7 occurrences) — well under the 16px minimum for
|
||||
supporting/secondary text throughout.
|
||||
- **Rule 22 (button padding: horizontal ≈2x vertical)** — `home_screen.dart:
|
||||
242` and `:261` set `padding: const EdgeInsets.symmetric(vertical: 14)`
|
||||
on full-width `ElevatedButton`s with no `horizontal:` argument, which
|
||||
defaults `horizontal` to `0.0` — the inverse of "horizontal ≈2x vertical".
|
||||
- **Rule 26 (no shadows in dark interfaces)** — The app declares
|
||||
`brightness: Brightness.dark` (`main.dart:71`), yet `rep_circle.dart:
|
||||
105-111` adds an explicit `BoxShadow(color: Colors.black26, blurRadius: 4,
|
||||
offset: Offset(0, 2))` to the rep-tracking circle — the one shadow in the
|
||||
whole app, in a UI this rule says shouldn't have any.
|
||||
|
||||
### Not applicable
|
||||
|
||||
- Rule 5 (optical alignment) — standard Material icons/widgets are already
|
||||
optically centered by the framework; no custom asymmetric glyphs.
|
||||
- Rule 6 (letter-spacing/line-height by size) — the only `letterSpacing`
|
||||
uses found (`home_screen.dart:311` → 1.1, `history_screen.dart:333` → 1.3,
|
||||
`settings_screen.dart:388` → 1.4) are all on the same small `fontSize: 11`
|
||||
eyebrow-label text, consistently given positive tracking as the rule
|
||||
recommends for small text — no counter-example at larger sizes to check
|
||||
against, so marked N/A rather than a forced Pass.
|
||||
- Rule 7 (border contrast) — `Border.all(color: color.withValues(alpha:
|
||||
0.4))` (`settings_screen.dart:491`) derives border color from the same
|
||||
status color as the fill, by design (a tinted pill), not a
|
||||
container-edge border this rule targets.
|
||||
- Rule 8 (align with something else) — standard `Column`/`Row`/`ListView`
|
||||
layouts; no cross-screen alignment grid to check.
|
||||
- Rule 12 (order by visual weight) — screens are single-column flows
|
||||
(cards stacked top-to-bottom); no left/right or center/edge weight
|
||||
arrangement to evaluate.
|
||||
- Rule 13 (12-column grid) — mobile single-column layouts throughout; no
|
||||
multi-column grid system in use.
|
||||
- Rule 14 (space between contrast edges) — cannot be verified statically
|
||||
without rendering the widget tree.
|
||||
- Rule 15 (closer elements lighter) — `Card`s at `shade800` sit on
|
||||
`shade900` backgrounds (lighter-on-darker as they "lift"), which is
|
||||
directionally correct, but see Rule 18 above for the magnitude issue.
|
||||
- Rule 17 (simple on complex) — flat-colored cards/containers throughout;
|
||||
nothing complex to conflict with.
|
||||
- Rule 19 (outer padding ≥ inner padding) — spot-checked
|
||||
`home_screen.dart:143` (`EdgeInsets.all(24)` outer) vs. its nested
|
||||
`_WorkoutCard` internal padding (`EdgeInsets.all(16)`,
|
||||
`home_screen.dart:188`) — outer ≥ inner, consistent with the rule; not
|
||||
exhaustively checked across all 24 files.
|
||||
- Rule 21 (line length ~70 chars) — Flutter `Text` wraps by default at
|
||||
widget width; no unbounded-line risk equivalent to the Tk surface.
|
||||
- Rule 23 (two typefaces max) — no custom `fontFamily` set anywhere; the
|
||||
whole app uses the Material/system default typeface. Trivially compliant.
|
||||
- Rule 24 (nest corners) — `BorderRadius.circular(8)` is reused verbatim
|
||||
across unrelated containers (`home_screen.dart:301`,
|
||||
`calendar_widget.dart:63`, `history_screen.dart:402,643,705,772`,
|
||||
`settings_screen.dart:490,548,587`) but none of these visibly nest inside
|
||||
another rounded container in the surrounding code, so there's no
|
||||
outer/inner radius relationship to check.
|
||||
- Rule 25 (avoid adjacent hard divides) — only one `Divider` found
|
||||
(`exercise_tile.dart:115`), not adjacent to another border/divide.
|
||||
- Rule 27 (don't mix depth techniques) — the app consistently uses flat
|
||||
`Container`/`Card` fills with no shadow except the single instance flagged
|
||||
under Rule 26; effectively one depth style (none) throughout, so no
|
||||
mixing to flag.
|
||||
- Rule 28 (lower icon contrast next to text) — icons consistently use
|
||||
`Colors.white54`/`Colors.white38`/`Colors.white70` (already
|
||||
lower-contrast than adjacent full-white/near-white text) rather than full
|
||||
`Colors.white`, e.g. `exercise_tile.dart:150,160,167,177,248,252`,
|
||||
`history_screen.dart:331,486,507` — this one is actually already followed
|
||||
reasonably consistently. Pass.
|
||||
|
||||
### Notes
|
||||
|
||||
- Rule 4 is the dominant finding for this surface too: an unused
|
||||
`ColorScheme.fromSeed` plus ~210 ad hoc `Colors.*`/`Color(0x...)` literals
|
||||
means every other color/contrast rule (1, 2, 9, 18) is failing as a direct
|
||||
consequence of the same root cause, not independently. Routing all 24
|
||||
files through `Theme.of(context).colorScheme` (or a small shared
|
||||
`AppColors`/`AppTextStyles` class) would be the highest-leverage single
|
||||
fix.
|
||||
- The coincidental hex overlap between `Color(0xFFFF4444)`/`Color(0xFF88CCFF)`
|
||||
(Flutter) and `#ff4444`/`#88ccff` (Python/Tkinter) shows the two UI
|
||||
surfaces are visually related by convention only — there is no shared
|
||||
token file either could import from, on either language side.
|
||||
|
||||
## Shared gatelock library
|
||||
|
||||
`~/utils/gatelock` is **not** its own git repo — `git -C ~/utils/gatelock
|
||||
rev-parse --show-toplevel` resolves to `/home/kuhy/utils`, so it's a
|
||||
subdirectory of the `~/utils` monorepo. Per audit scope, gatelock itself was
|
||||
not walked against all 28 rules and no separate
|
||||
`~/utils/gatelock/DESIGN_AUDIT_TODO.md` was written.
|
||||
|
||||
What's relevant here: gatelock defines exactly **one** real design token —
|
||||
`LockConfig.bg: str = "#1a1a1a"` (`~/utils/gatelock/gatelock/_window.py:71`),
|
||||
applied via `self.root.configure(bg=self._config.bg, ...)` in
|
||||
`LockWindow.setup()` (`_window.py:143`). Both consumer repos re-hardcode
|
||||
this same literal instead of reading it back off their own `LockConfig`
|
||||
instance:
|
||||
|
||||
- **screen-locker** (this repo) — `#1a1a1a` appears 31 times across 9 files
|
||||
(see the Tkinter section above) despite `screen_lock.py:148-153`
|
||||
constructing a `LockConfig` instance (as `config`) just a few lines above
|
||||
each of those files' widget-creation call sites.
|
||||
- **diet-guard** — not inspected as part of this audit (out of scope for
|
||||
this repo's report), but per the shared-infra note in the task, it is the
|
||||
other known consumer of `LockConfig`/`LockWindow` and should be checked
|
||||
for the same duplication pattern if/when a design audit is run there.
|
||||
|
||||
Fixing the screen-locker Rule 4 finding above by having widget-creation code
|
||||
read `self._lock_config.bg` (threaded through from the `LockConfig` already
|
||||
built in `ScreenLocker.__init__`) instead of re-typing `"#1a1a1a"` would
|
||||
close this loop without needing any gatelock-side change.
|
||||
- [Python/Tkinter lock UI](docs/design-audit/python-tkinter-lock-ui.md) — `screen_locker/`
|
||||
- [Flutter workout app](docs/design-audit/flutter-workout-app.md) — `stronglift_replacement/workout_app/`
|
||||
- [Shared gatelock library](docs/design-audit/shared-gatelock-library.md) — `~/utils/gatelock`
|
||||
|
||||
146
docs/design-audit/flutter-workout-app.md
Normal file
146
docs/design-audit/flutter-workout-app.md
Normal file
@ -0,0 +1,146 @@
|
||||
## Flutter app (stronglift_replacement/workout_app/)
|
||||
|
||||
Design-token entry point: `lib/main.dart:68-74` declares
|
||||
`ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo,
|
||||
brightness: Brightness.dark), useMaterial3: true)` — a real Material 3 seed
|
||||
theme exists. However, **`Theme.of(context)` / `colorScheme` is referenced
|
||||
zero times anywhere in `lib/screens/` or `lib/widgets/`** (confirmed via
|
||||
repo-wide grep). The theme is declared but never consumed — every one of the
|
||||
24 .dart files under `lib/` hardcodes colors directly instead.
|
||||
|
||||
- `Colors.*` literals: **~210 occurrences** across `screens/` and
|
||||
`widgets/`, 27 distinct named colors. Most common: `Colors.white` (98×),
|
||||
`Colors.grey.shade800` (18×), `Colors.redAccent` (12×),
|
||||
`Colors.greenAccent` (11×), `Colors.grey.shade900` (10×).
|
||||
- Raw hex `Color(0xFF...)` literals bypassing `Colors.*` entirely:
|
||||
`manual_workout_screen.dart:173,201` (`Color(0xFFFF4444)`) and
|
||||
`manual_workout_screen.dart:238,246` (`Color(0xFF88CCFF)`) — these are the
|
||||
**exact same hex values** independently hardcoded on the Python/Tkinter
|
||||
side (`#ff4444` and `#88ccff`, see e.g. `_sick_dialog.py:70`,
|
||||
`_manual_workout_dialog.py:58`), coincidentally kept in sync only because
|
||||
no one has touched either yet.
|
||||
- `fontSize:`/`fontWeight:` literals: 72 occurrences; `history_screen.dart`
|
||||
alone uses 12 distinct font sizes (9, 11, 12, 13, 14, 15, 16, 17, 18, 20,
|
||||
22, 26).
|
||||
|
||||
### Violations
|
||||
|
||||
- **Rule 4 (everything deliberate / single source of truth)** — `main.dart`
|
||||
builds a `ColorScheme.fromSeed`, but it is dead code from a theming
|
||||
standpoint: no screen or widget reads it. Every screen re-derives its own
|
||||
ad hoc dark palette from `Colors.grey.shade900/800/700` plus assorted
|
||||
accent colors, so a single rebrand (e.g. changing the seed color) would
|
||||
require manually editing all 24 files instead of one.
|
||||
- **Rule 1 (near-black/white, not pure)** — `Colors.white` (pure `#FFFFFF`)
|
||||
used 98 times for primary text/icons, e.g. `home_screen.dart:113,122,128,
|
||||
211,248,267`, `settings_screen.dart:231,278,430`,
|
||||
`history_screen.dart:209,410`. `Colors.black` also appears at
|
||||
`rep_circle.dart:76` (`Colors.black87`, near-pure) as text-on-white in the
|
||||
neutral rep-circle state. None of these are the theme's actual
|
||||
near-white/near-black — they're Flutter's pure-value constants.
|
||||
- **Rule 2 (saturate your neutrals)** — `Colors.grey.shade900/800/700/400`
|
||||
are Material's standard zero-saturation grays (equal R=G=B), used as the
|
||||
entire background/surface system in place of `colorScheme.surface`
|
||||
(which, being seeded from indigo, *would* be saturated). Bypassing the
|
||||
theme produces exactly the generic-gray outcome the theme was set up to
|
||||
avoid.
|
||||
- **Rule 9 (distinct brightness values)** — `Colors.redAccent` (errors) and
|
||||
`Colors.orangeAccent`/`Colors.orange.shade800` (pending/resume state) are
|
||||
both used as status-signal colors of similar brightness in adjacent UI
|
||||
(e.g. `home_screen.dart:222` orangeAccent for active-session text next to
|
||||
`Colors.greenAccent` for success at line 200 — three status colors of
|
||||
comparable weight competing in one card).
|
||||
- **Rule 18 (container brightness limits, dark ≤~12%)** — The repeated
|
||||
`Scaffold(backgroundColor: Colors.grey.shade900)` /
|
||||
`AppBar(backgroundColor: Colors.grey.shade800)` pairing (Material
|
||||
`shade900`=`#212121`, luma 12.9%; `shade800`=`#424242`, luma 25.9% — a
|
||||
~13-point jump) appears in every screen's `Scaffold`/`AppBar`:
|
||||
`home_screen.dart:104,106`, `settings_screen.dart:275,277`,
|
||||
`history_screen.dart:206,208`, `workout_screen.dart:495,498`,
|
||||
`manual_workout_screen.dart:154,156`. This exceeds the ~12% dark-interface
|
||||
guideline every time it's used.
|
||||
- **Rule 20 (body text ≥16px)** — Extensive small body text below 16px:
|
||||
`fontSize: 9` at `history_screen.dart:612`, `fontSize: 11` (11 occurrences,
|
||||
e.g. `home_screen.dart:311`, `history_screen.dart:333,486,612`,
|
||||
`settings_screen.dart:388`), `fontSize: 12` (14 occurrences),
|
||||
`fontSize: 13` (7 occurrences) — well under the 16px minimum for
|
||||
supporting/secondary text throughout.
|
||||
- **Rule 22 (button padding: horizontal ≈2x vertical)** — `home_screen.dart:
|
||||
242` and `:261` set `padding: const EdgeInsets.symmetric(vertical: 14)`
|
||||
on full-width `ElevatedButton`s with no `horizontal:` argument, which
|
||||
defaults `horizontal` to `0.0` — the inverse of "horizontal ≈2x vertical".
|
||||
- **Rule 26 (no shadows in dark interfaces)** — The app declares
|
||||
`brightness: Brightness.dark` (`main.dart:71`), yet `rep_circle.dart:
|
||||
105-111` adds an explicit `BoxShadow(color: Colors.black26, blurRadius: 4,
|
||||
offset: Offset(0, 2))` to the rep-tracking circle — the one shadow in the
|
||||
whole app, in a UI this rule says shouldn't have any.
|
||||
|
||||
### Not applicable
|
||||
|
||||
- Rule 5 (optical alignment) — standard Material icons/widgets are already
|
||||
optically centered by the framework; no custom asymmetric glyphs.
|
||||
- Rule 6 (letter-spacing/line-height by size) — the only `letterSpacing`
|
||||
uses found (`home_screen.dart:311` → 1.1, `history_screen.dart:333` → 1.3,
|
||||
`settings_screen.dart:388` → 1.4) are all on the same small `fontSize: 11`
|
||||
eyebrow-label text, consistently given positive tracking as the rule
|
||||
recommends for small text — no counter-example at larger sizes to check
|
||||
against, so marked N/A rather than a forced Pass.
|
||||
- Rule 7 (border contrast) — `Border.all(color: color.withValues(alpha:
|
||||
0.4))` (`settings_screen.dart:491`) derives border color from the same
|
||||
status color as the fill, by design (a tinted pill), not a
|
||||
container-edge border this rule targets.
|
||||
- Rule 8 (align with something else) — standard `Column`/`Row`/`ListView`
|
||||
layouts; no cross-screen alignment grid to check.
|
||||
- Rule 12 (order by visual weight) — screens are single-column flows
|
||||
(cards stacked top-to-bottom); no left/right or center/edge weight
|
||||
arrangement to evaluate.
|
||||
- Rule 13 (12-column grid) — mobile single-column layouts throughout; no
|
||||
multi-column grid system in use.
|
||||
- Rule 14 (space between contrast edges) — cannot be verified statically
|
||||
without rendering the widget tree.
|
||||
- Rule 15 (closer elements lighter) — `Card`s at `shade800` sit on
|
||||
`shade900` backgrounds (lighter-on-darker as they "lift"), which is
|
||||
directionally correct, but see Rule 18 above for the magnitude issue.
|
||||
- Rule 17 (simple on complex) — flat-colored cards/containers throughout;
|
||||
nothing complex to conflict with.
|
||||
- Rule 19 (outer padding ≥ inner padding) — spot-checked
|
||||
`home_screen.dart:143` (`EdgeInsets.all(24)` outer) vs. its nested
|
||||
`_WorkoutCard` internal padding (`EdgeInsets.all(16)`,
|
||||
`home_screen.dart:188`) — outer ≥ inner, consistent with the rule; not
|
||||
exhaustively checked across all 24 files.
|
||||
- Rule 21 (line length ~70 chars) — Flutter `Text` wraps by default at
|
||||
widget width; no unbounded-line risk equivalent to the Tk surface.
|
||||
- Rule 23 (two typefaces max) — no custom `fontFamily` set anywhere; the
|
||||
whole app uses the Material/system default typeface. Trivially compliant.
|
||||
- Rule 24 (nest corners) — `BorderRadius.circular(8)` is reused verbatim
|
||||
across unrelated containers (`home_screen.dart:301`,
|
||||
`calendar_widget.dart:63`, `history_screen.dart:402,643,705,772`,
|
||||
`settings_screen.dart:490,548,587`) but none of these visibly nest inside
|
||||
another rounded container in the surrounding code, so there's no
|
||||
outer/inner radius relationship to check.
|
||||
- Rule 25 (avoid adjacent hard divides) — only one `Divider` found
|
||||
(`exercise_tile.dart:115`), not adjacent to another border/divide.
|
||||
- Rule 27 (don't mix depth techniques) — the app consistently uses flat
|
||||
`Container`/`Card` fills with no shadow except the single instance flagged
|
||||
under Rule 26; effectively one depth style (none) throughout, so no
|
||||
mixing to flag.
|
||||
- Rule 28 (lower icon contrast next to text) — icons consistently use
|
||||
`Colors.white54`/`Colors.white38`/`Colors.white70` (already
|
||||
lower-contrast than adjacent full-white/near-white text) rather than full
|
||||
`Colors.white`, e.g. `exercise_tile.dart:150,160,167,177,248,252`,
|
||||
`history_screen.dart:331,486,507` — this one is actually already followed
|
||||
reasonably consistently. Pass.
|
||||
|
||||
### Notes
|
||||
|
||||
- Rule 4 is the dominant finding for this surface too: an unused
|
||||
`ColorScheme.fromSeed` plus ~210 ad hoc `Colors.*`/`Color(0x...)` literals
|
||||
means every other color/contrast rule (1, 2, 9, 18) is failing as a direct
|
||||
consequence of the same root cause, not independently. Routing all 24
|
||||
files through `Theme.of(context).colorScheme` (or a small shared
|
||||
`AppColors`/`AppTextStyles` class) would be the highest-leverage single
|
||||
fix.
|
||||
- The coincidental hex overlap between `Color(0xFFFF4444)`/`Color(0xFF88CCFF)`
|
||||
(Flutter) and `#ff4444`/`#88ccff` (Python/Tkinter) shows the two UI
|
||||
surfaces are visually related by convention only — there is no shared
|
||||
token file either could import from, on either language side.
|
||||
154
docs/design-audit/python-tkinter-lock-ui.md
Normal file
154
docs/design-audit/python-tkinter-lock-ui.md
Normal file
@ -0,0 +1,154 @@
|
||||
## Python/Tkinter lock UI (screen_locker/)
|
||||
|
||||
Design-token entry point check: **no `ttk.Style()` call anywhere in the
|
||||
package** (confirmed via repo-wide grep) and `_constants.py` holds only
|
||||
business-logic constants (budgets, timeouts, file paths) — zero color/font/
|
||||
spacing tokens. Every color, font, and padding value is a literal typed
|
||||
directly at each `tk.Label`/`tk.Button`/`tk.Frame`/`tk.Entry` call site,
|
||||
independently, in 9 files. Evidence:
|
||||
|
||||
- Hex color literals: **100 occurrences, 23 distinct values**, across
|
||||
`screen_lock.py` (6), `_ui_widgets.py` (6), `_window_setup.py` (3),
|
||||
`status_view.py` (21), `_heat_skip.py` (7 + 4 module-level constants),
|
||||
`_manual_workout_dialog.py` (15), `_manual_workout_widgets.py` (12),
|
||||
`_sick_dialog.py` (18), `_temperature_status_mixin.py` (5).
|
||||
`#1a1a1a` alone (the background) appears **31 times** — and it is *also*
|
||||
already defined once, correctly, as `LockConfig.bg = "#1a1a1a"` in
|
||||
`~/utils/gatelock/gatelock/_window.py:71`. None of the 31 in-repo literals
|
||||
import or reference it; `LockWindow.setup()` in gatelock applies
|
||||
`config.bg` to the root window (`_window.py:143`), and then every
|
||||
screen-locker dialog re-hardcodes the same string as if gatelock's value
|
||||
didn't exist.
|
||||
- `font=("Arial", N[, "bold"])` literals: **25 occurrences**, 6 distinct
|
||||
size/weight combos, e.g. `_ui_widgets.py:45,64`, `_sick_dialog.py:111,121`,
|
||||
`_manual_workout_widgets.py:70,89,97,116,126,137,145,164,174`.
|
||||
`_heat_skip.py:12-17` breaks pattern entirely with its own local
|
||||
`_FONT = "monospace"` constant (line 17) plus four color constants
|
||||
(`_BG`, `_FG_MAIN`, `_FG_SUB`, `_BTN_SKIP`, `_BTN_NO`) — the only file in
|
||||
the package that centralizes *anything*, and it does so locally/unshared
|
||||
rather than in a common module.
|
||||
- `padx=`/`pady=` literals: **59 occurrences**, 13 distinct values (1, 2, 5,
|
||||
6, 8, 10, 12, 14, 15, 20, 28, 30) spread across 7 of the 9 files.
|
||||
|
||||
### Violations
|
||||
|
||||
- **Rule 4 (everything deliberate / single source of truth)** — No
|
||||
`ttk.Style()`, no shared colors/fonts/spacing module. Same visual decision
|
||||
(e.g. background `#1a1a1a`) is independently re-typed 31 times across 9
|
||||
files instead of imported once. `_heat_skip.py:12-17` even invents its own
|
||||
local token block, proving the pattern was known and simply not applied
|
||||
package-wide. Fixing any single visual value (e.g. rebranding the
|
||||
background) means editing up to 9 files by hand with no compiler/lint
|
||||
check that all sites were caught.
|
||||
- **Rule 1 (near-black/white, not pure)** — `bg="#1a1a1a"` (near-black,
|
||||
fine) is paired with pure white text: `_ui_widgets.py:38,57` default
|
||||
`color: str = "white"`, plus explicit `fg="white"` at `_window_setup.py:40`,
|
||||
`_sick_dialog.py:112,128,138` (X11 name `"white"` = `#FFFFFF`), and 6 more
|
||||
in `_manual_workout_widgets.py` (lines 90, 112→ label fg, 116, 137, 158,
|
||||
165). Pure-white-on-near-black is the harsh contrast this rule warns
|
||||
against; should be a near-white (e.g. `#f0f0f0`/`#eaeaea`).
|
||||
- **Rule 2 (saturate your neutrals)** — `#1a1a1a` and `#2a2a2a` have equal
|
||||
R=G=B (26,26,26 and 42,42,42): true zero-saturation gray, not tinted warm
|
||||
or cool. Generic gray per the rule's definition.
|
||||
- **Rule 9 (distinct brightness values in a palette)** — `#ffaa00` (warning/
|
||||
bonus amber, e.g. `screen_lock.py:319`, `status_view.py:181`) and
|
||||
`#ff8844` (network/temp-check failure, e.g. `status_view.py:121,243`,
|
||||
`_temperature_status_mixin.py:50,57,65`) are near-identical in hue and
|
||||
brightness despite signaling different states (bonus/pending vs.
|
||||
error/failure) — they will read as the same color at a glance.
|
||||
- **Rule 11 (mathematically related measurements)** — `padx`/`pady` values
|
||||
(1, 2, 5, 6, 8, 10, 12, 14, 15, 20, 28, 30) don't follow a consistent
|
||||
scale (not all multiples of 4 or 8); e.g. `pady=1` at `status_view.py:177`
|
||||
sits next to `pady=2` (`status_view.py:160`) and `pady=28`
|
||||
(`_heat_skip.py:74`) elsewhere — no discernible spacing system.
|
||||
- **Rule 20 (body text ≥16px)** — Multiple body-text sizes sit well under
|
||||
16px: `font_size=10` at `status_view.py:248,253,255` (the last one,
|
||||
line 255, also uses the lowest-contrast color in the file, `#666666`, for
|
||||
a 10px label — compounding readability), `font_size=11` at
|
||||
`status_view.py:199`, `_heat_skip.py:91,104` (`font=(_FONT, 11)`),
|
||||
`font_size=12` at `status_view.py:160,212,225,239,243`,
|
||||
`_temperature_status_mixin.py:43,50,57,65`, `_sick_dialog.py:135`
|
||||
(`font=("Arial", 12)` on the `tk.Text` justification box), `font_size=13`
|
||||
at `status_view.py:121,123,181`.
|
||||
- **Rule 21 (line length ~70 chars)** — No widget in the package sets
|
||||
`wraplength` (confirmed: zero matches for `wraplength` repo-wide), so long
|
||||
strings render as one unbroken line regardless of window width. Concrete
|
||||
case: `_sick_dialog.py:205-207`, the commitment-prompt text "If you say
|
||||
YES and skip via 'I'm sick' tomorrow, the sick day costs 2x normal." is
|
||||
~80 characters and will render as a single line at `font_size=16` with no
|
||||
wrap control.
|
||||
- **Rule 22 (button padding: horizontal ≈2x vertical)** — Only
|
||||
`_heat_skip.py:92,93,105,106` sets explicit button padding
|
||||
(`padx=14, pady=5`, ratio 2.8x — roughly compliant). Every other button in
|
||||
the package goes through `UIWidgetsMixin._button()`
|
||||
(`_ui_widgets.py:71-90`), which sets no `padx`/`pady` at all and relies on
|
||||
Tk's built-in default padding — a different, unspecified ratio. Button
|
||||
proportions are therefore inconsistent across dialogs, not a deliberate
|
||||
choice.
|
||||
- **Rule 27 (don't mix depth techniques)** — `UIWidgetsMixin._button()`
|
||||
(`_ui_widgets.py:71-90`) sets no `relief`, so every button in
|
||||
`status_view.py`, `_sick_dialog.py`, `_manual_workout_dialog.py`, and
|
||||
`_manual_workout_widgets.py` uses Tk's default `relief="raised"` (a faux
|
||||
3D bevel). `_heat_skip.py:94,107` explicitly overrides to
|
||||
`relief="flat"` for its two buttons only — one dialog in the app uses a
|
||||
flat depth style while every other dialog uses a raised/beveled one.
|
||||
|
||||
### Not applicable
|
||||
|
||||
- Rule 5 (optical alignment) — no asymmetric icon/shape glyphs requiring
|
||||
eye-adjusted centering; text/emoji labels only.
|
||||
- Rule 6 (letter-spacing/line-height by size) — Tk's `font=` tuple has no
|
||||
letter-spacing or line-height controls; not expressible in this stack.
|
||||
- Rule 7 (border contrast) — no widget in the package sets `borderwidth`
|
||||
or a visible border color (only one incidental `highlightthickness=0` at
|
||||
`_manual_workout_dialog.py:72`, which removes a border, not adds one).
|
||||
- Rule 8 (align with something else) — pack/grid layouts are internally
|
||||
consistent per-dialog; no cross-dialog layout grid to check against.
|
||||
- Rule 12 (order by visual weight) — button rows use uniform-weight buttons
|
||||
(same size/style, only color differs); no weight hierarchy to evaluate.
|
||||
- Rule 13 (12-column grid) — fixed 2-column form grid
|
||||
(`_manual_workout_widgets.py:26-49`) is a bespoke field layout, not a page
|
||||
grid system this rule targets.
|
||||
- Rule 14 (space between contrast edges, not bounding box) — cannot be
|
||||
verified from source without rendering; Tk widgets' effective visual
|
||||
edges vs. bounding boxes aren't determinable statically.
|
||||
- Rule 15 (closer elements lighter) — single flat z-plane throughout; no
|
||||
layered/stacked surfaces.
|
||||
- Rule 16 (shadow blur ≈ 2x offset) — no shadows anywhere in the package.
|
||||
- Rule 17 (simple on complex) — flat solid backgrounds behind all text;
|
||||
trivially compliant, nothing to flag.
|
||||
- Rule 18 (container brightness limits) — the one adjacent pair found,
|
||||
`#1a1a1a` (bg, luma 10.2%) vs. `#2a2a2a` (entry/spinbox fields, luma
|
||||
16.5%), differs by ~6.3 percentage points — within the ~12% dark-mode
|
||||
limit. Pass.
|
||||
- Rule 19 (outer padding ≥ inner padding) — the lock window has no bounded
|
||||
"container" with edge padding (content is `place(relx=0.5, rely=0.5,
|
||||
anchor="center")` on a fullscreen root); the outer/inner relationship this
|
||||
rule assumes doesn't apply to a centered-content-on-fullscreen-canvas
|
||||
layout.
|
||||
- Rule 23 (two typefaces max) — only "Arial" and "monospace"
|
||||
(`_heat_skip.py:17`) appear; 2 total, within the limit (the inconsistency
|
||||
of *where* each is used is captured under Rule 4 above, not this rule).
|
||||
- Rule 24 (nest corners) — no widget sets a corner radius (stock Tk widgets
|
||||
are rectangular); nothing to nest.
|
||||
- Rule 25 (avoid adjacent hard divides) — no borders/dividers used anywhere;
|
||||
nothing to conflict.
|
||||
- Rule 26 (no shadows in dark interfaces) — Pass by omission: no shadows
|
||||
exist in this dark-background UI.
|
||||
- Rule 28 (lower icon contrast next to text) — emoji glyphs (💪, 😷, ✓, ☀,
|
||||
⚠, 🔥) share the same `fg=` color as their surrounding text; Tk offers no
|
||||
per-glyph opacity control within one Label's text, so this can't be
|
||||
addressed without moving emoji into separate, independently-colored
|
||||
widgets.
|
||||
|
||||
### Notes
|
||||
|
||||
- The absence of any shared theme/constants module means every rule above
|
||||
that *did* pass (18, 26) did so incidentally, not by design — there's no
|
||||
guard rail keeping it that way as new dialogs get added.
|
||||
- `_heat_skip.py`'s local `_BG`/`_FG_MAIN`/`_FG_SUB`/`_BTN_SKIP`/`_BTN_NO`/
|
||||
`_FONT` constants are the one place in the package that already knows
|
||||
centralizing tokens is worth doing — promoting this pattern to a shared
|
||||
`screen_locker/_theme.py` (or, better, sourcing from gatelock's
|
||||
`LockConfig`) would fix Rule 4 and cascade-fix several of the violations
|
||||
above in one pass.
|
||||
28
docs/design-audit/shared-gatelock-library.md
Normal file
28
docs/design-audit/shared-gatelock-library.md
Normal file
@ -0,0 +1,28 @@
|
||||
## Shared gatelock library
|
||||
|
||||
`~/utils/gatelock` is **not** its own git repo — `git -C ~/utils/gatelock
|
||||
rev-parse --show-toplevel` resolves to `/home/kuhy/utils`, so it's a
|
||||
subdirectory of the `~/utils` monorepo. Per audit scope, gatelock itself was
|
||||
not walked against all 28 rules and no separate
|
||||
`~/utils/gatelock/DESIGN_AUDIT_TODO.md` was written.
|
||||
|
||||
What's relevant here: gatelock defines exactly **one** real design token —
|
||||
`LockConfig.bg: str = "#1a1a1a"` (`~/utils/gatelock/gatelock/_window.py:71`),
|
||||
applied via `self.root.configure(bg=self._config.bg, ...)` in
|
||||
`LockWindow.setup()` (`_window.py:143`). Both consumer repos re-hardcode
|
||||
this same literal instead of reading it back off their own `LockConfig`
|
||||
instance:
|
||||
|
||||
- **screen-locker** (this repo) — `#1a1a1a` appears 31 times across 9 files
|
||||
(see the Tkinter section above) despite `screen_lock.py:148-153`
|
||||
constructing a `LockConfig` instance (as `config`) just a few lines above
|
||||
each of those files' widget-creation call sites.
|
||||
- **diet-guard** — not inspected as part of this audit (out of scope for
|
||||
this repo's report), but per the shared-infra note in the task, it is the
|
||||
other known consumer of `LockConfig`/`LockWindow` and should be checked
|
||||
for the same duplication pattern if/when a design audit is run there.
|
||||
|
||||
Fixing the screen-locker Rule 4 finding above by having widget-creation code
|
||||
read `self._lock_config.bg` (threaded through from the `LockConfig` already
|
||||
built in `ScreenLocker.__init__`) instead of re-typing `"#1a1a1a"` would
|
||||
close this loop without needing any gatelock-side change.
|
||||
@ -55,7 +55,10 @@ unfixable = []
|
||||
"ANN", "ARG", "D", "DTZ011", "E501", "FBT",
|
||||
"PLC0415", "PLR0913", "PLR2004", "PTH", "RUF003", "S101", "SLF001",
|
||||
]
|
||||
"screen_locker/_runnerup_verification.py" = ["S314"]
|
||||
# The ET.parse call this covers moved to _runnerup_tcx.py when
|
||||
# _runnerup_verification.py was split for the 250-line cap. Same waiver, new
|
||||
# home -- the TCX files are pulled off the user's own phone by adb.
|
||||
"screen_locker/_runnerup_tcx.py" = ["S314"]
|
||||
# URL is always built from the hardcoded https:// _WTTR_URL constant with
|
||||
# only the (quoted) city interpolated — never user/attacker controlled.
|
||||
# ruff's S310 can't verify that via static analysis of a variable URL, so
|
||||
|
||||
@ -19,31 +19,24 @@ churn, not size alone — refactoring pays where code is read and changed often
|
||||
|
||||
<!-- BEGIN GENERATED VIOLATIONS -->
|
||||
|
||||
- **61 files** currently exceed 250 lines.
|
||||
- **9,084 lines** over the cap in total (the work left to do); longest file is **897** lines.
|
||||
- **10 files** currently exceed 250 lines.
|
||||
- **1,828 lines** over the cap in total (the work left to do); longest file is **740** lines.
|
||||
|
||||
ROI = lines x commits in the last year. Work top-down; a long file nobody edits
|
||||
has near-zero payoff and should not be first.
|
||||
|
||||
| lines | commits/yr | kind | file |
|
||||
| ----: | ---------: | :--- | :--- |
|
||||
| 771 | 12 | code | `stronglift_replacement/workout_app/lib/screens/settings_screen.dart` |
|
||||
| 781 | 10 | code | `stronglift_replacement/workout_app/lib/services/storage_service.dart` |
|
||||
| 897 | 8 | code | `stronglift_replacement/workout_app/lib/screens/history_screen.dart` |
|
||||
| 323 | 22 | code | `screen_locker/tests/conftest.py` |
|
||||
| 480 | 12 | code | `stronglift_replacement/workout_app/test/screens/settings_screen_test.dart` |
|
||||
| 503 | 13 | code | `stronglift_replacement/workout_app/lib/screens/settings_screen.dart` |
|
||||
| 633 | 9 | code | `stronglift_replacement/workout_app/lib/screens/workout_screen.dart` |
|
||||
| 343 | 16 | code | `screen_locker/tests/test_init_and_log.py` |
|
||||
| 740 | 7 | code | `stronglift_replacement/workout_app/test/services/workout_sync_service_test.dart` |
|
||||
| 370 | 14 | code | `screen_locker/_ui_flows.py` |
|
||||
| 380 | 13 | code | `screen_locker/_phone_verification.py` |
|
||||
| 759 | 5 | code | `stronglift_replacement/workout_app/test/services/storage_service_test.dart` |
|
||||
| 415 | 9 | code | `stronglift_replacement/workout_app/lib/services/workout_sync_service.dart` |
|
||||
| 357 | 9 | code | `screen_locker/_manual_workout_dialog.py` |
|
||||
| 384 | 8 | code | `screen_locker/_shutdown.py` |
|
||||
| 383 | 8 | code | `stronglift_replacement/workout_app/lib/screens/home_screen.dart` |
|
||||
|
||||
_(46 further files over 250 lines not listed — re-run `python3 scripts/refresh_refactor_todo.py` for the current set.)_
|
||||
| 322 | 10 | code | `stronglift_replacement/workout_app/lib/services/workout_sync_service.dart` |
|
||||
| 383 | 7 | code | `stronglift_replacement/workout_app/test/screens/home_screen_test.dart` |
|
||||
| 260 | 9 | code | `stronglift_replacement/workout_app/lib/screens/home_screen.dart` |
|
||||
| 386 | 5 | code | `stronglift_replacement/workout_app/test/screens/history_screen_test.dart` |
|
||||
| 362 | 4 | code | `stronglift_replacement/workout_app/test/screens/workout_screen_test.dart` |
|
||||
| 313 | 2 | code | `stronglift_replacement/workout_app/lib/screens/manual_workout_screen.dart` |
|
||||
| 426 | 1 | code | `stronglift_replacement/workout_app/test/services/progression_sync_service_test.dart` |
|
||||
|
||||
<!-- END GENERATED VIOLATIONS -->
|
||||
|
||||
|
||||
137
screen_locker/_adb_transport.py
Normal file
137
screen_locker/_adb_transport.py
Normal file
@ -0,0 +1,137 @@
|
||||
"""ADB transport for phone verification: connect, reconnect, run commands.
|
||||
|
||||
Split out of :mod:`screen_locker._phone_verification` to keep every file under
|
||||
the 250-line cap. Composed back into ``PhoneVerificationMixin`` there, so
|
||||
callers see no change.
|
||||
|
||||
Everything here is plumbing: reaching the phone and running a command on it.
|
||||
Deciding whether what came back counts as a workout stays in
|
||||
``_phone_verification``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ( # pylint: disable=no-name-in-module
|
||||
ThreadPoolExecutor,
|
||||
as_completed,
|
||||
)
|
||||
import contextlib
|
||||
import logging
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
|
||||
from screen_locker._constants import ADB_TIMEOUT
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AdbTransportMixin:
|
||||
"""Finds the phone over USB or wifi and runs adb commands against it."""
|
||||
|
||||
def _run_adb(self, args: list[str]) -> tuple[bool, str]:
|
||||
"""Run an ADB command and return success flag and stdout."""
|
||||
adb = shutil.which("adb") or "adb"
|
||||
# When multiple devices are connected (e.g. USB + wireless), pin to
|
||||
# the wireless device's serial to avoid "more than one device" errors.
|
||||
_discovery_cmds = {"devices", "connect", "disconnect", "kill-server"}
|
||||
serial = (
|
||||
self._get_wireless_serial()
|
||||
if args and args[0] not in _discovery_cmds
|
||||
else None
|
||||
)
|
||||
serial_args = ["-s", serial] if serial else []
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[adb, *serial_args, *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=ADB_TIMEOUT,
|
||||
check=False,
|
||||
)
|
||||
except (FileNotFoundError, OSError) as exc:
|
||||
_logger.warning("ADB not available: %s", exc)
|
||||
return False, ""
|
||||
except subprocess.TimeoutExpired:
|
||||
_logger.warning("ADB command timed out: %s", args)
|
||||
return False, ""
|
||||
return not result.returncode, result.stdout
|
||||
|
||||
def _adb_shell(self, command: str, *, root: bool = False) -> tuple[bool, str]:
|
||||
"""Run a shell command on the connected Android device."""
|
||||
if root:
|
||||
return self._run_adb(["shell", "su", "-c", command])
|
||||
return self._run_adb(["shell", command])
|
||||
|
||||
def _get_wireless_serial(self) -> str | None:
|
||||
"""Return the serial (ip:port) of the first connected wireless ADB device."""
|
||||
success, output = self._run_adb(["devices"])
|
||||
if not success:
|
||||
return None
|
||||
for line in output.strip().split("\n")[1:]:
|
||||
parts = line.split()
|
||||
if parts and ":" in parts[0] and "device" in line and "offline" not in line:
|
||||
return parts[0]
|
||||
return None
|
||||
|
||||
def _has_adb_device(self) -> bool:
|
||||
"""Return True if adb devices shows at least one connected device."""
|
||||
success, output = self._run_adb(["devices"])
|
||||
if not success:
|
||||
return False
|
||||
lines = output.strip().split("\n")[1:]
|
||||
return any("device" in line and "offline" not in line for line in lines)
|
||||
|
||||
def _try_adb_connect(self, address: str) -> bool:
|
||||
"""Run adb connect to address. Returns True on success."""
|
||||
_, output = self._run_adb(["connect", address])
|
||||
lower = output.lower()
|
||||
return "connected" in lower and "unable" not in lower and "failed" not in lower
|
||||
|
||||
def _get_local_subnet_prefix(self) -> str | None:
|
||||
"""Detect the local /24 network prefix (e.g. '192.168.1')."""
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock,
|
||||
):
|
||||
sock.connect(("8.8.8.8", 80))
|
||||
return ".".join(sock.getsockname()[0].split(".")[:3])
|
||||
return None
|
||||
|
||||
def _try_wireless_reconnect(self) -> bool:
|
||||
"""Scan local /24 subnet on port 5555 and attempt ADB connect to phone."""
|
||||
prefix = self._get_local_subnet_prefix()
|
||||
if prefix is None:
|
||||
_logger.info("Could not determine local subnet for wireless scan")
|
||||
return False
|
||||
|
||||
def probe(i: int) -> bool:
|
||||
ip = f"{prefix}.{i}"
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.create_connection((ip, 5555), timeout=0.5),
|
||||
):
|
||||
if self._try_adb_connect(f"{ip}:5555"):
|
||||
return self._has_adb_device()
|
||||
return False
|
||||
|
||||
_logger.info("Scanning %s.1-254:5555 for phone...", prefix)
|
||||
with ThreadPoolExecutor(max_workers=64) as executor:
|
||||
for future in as_completed(
|
||||
executor.submit(probe, i) for i in range(1, 255)
|
||||
):
|
||||
if future.result():
|
||||
return True
|
||||
return False
|
||||
|
||||
def _is_phone_connected(self) -> bool:
|
||||
"""Check if an Android device is connected via ADB.
|
||||
|
||||
If no device is visible, attempts wireless reconnection via subnet scan.
|
||||
"""
|
||||
if self._has_adb_device():
|
||||
return True
|
||||
_logger.info("No ADB device detected — attempting wireless reconnect...")
|
||||
return self._try_wireless_reconnect()
|
||||
|
||||
# ── ADB verification ──────────────────────────────────────────────────────
|
||||
131
screen_locker/_compliance_predicates.py
Normal file
131
screen_locker/_compliance_predicates.py
Normal file
@ -0,0 +1,131 @@
|
||||
"""Pure, read-only leaf predicates for the lock-decision chain.
|
||||
|
||||
Split out of :mod:`screen_locker._compliance_state` to keep every file under
|
||||
the 250-line cap. That module re-exports everything here, so existing
|
||||
importers are unaffected.
|
||||
|
||||
Nothing in this module touches ADB, sudo, subprocess, or the network, and
|
||||
nothing writes to disk.
|
||||
|
||||
Note for tests: the ``gatelock.log_integrity`` helpers are imported *here*
|
||||
now, so patch them at ``screen_locker._compliance_predicates.verify_entry_hmac``
|
||||
rather than at the old ``_compliance_state`` path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
|
||||
|
||||
from screen_locker._constants import (
|
||||
EARLY_BIRD_END_HOUR,
|
||||
EARLY_BIRD_END_MINUTE,
|
||||
EARLY_BIRD_START_HOUR,
|
||||
)
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._sick_tracker import is_sick_day as _is_sick_day
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from screen_locker._sick_tracker import SickHistory
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _today_str() -> str:
|
||||
"""Return today's date as ``YYYY-MM-DD`` in UTC."""
|
||||
return datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def is_scheduled_skip_today(
|
||||
scheduled_skips_file: Path, *, today: str | None = None
|
||||
) -> bool:
|
||||
"""Return True if *today* is listed in *scheduled_skips_file*."""
|
||||
if not scheduled_skips_file.exists():
|
||||
return False
|
||||
try:
|
||||
with scheduled_skips_file.open() as f:
|
||||
skips = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not read scheduled skips from %s: %s — treating today as NOT "
|
||||
"a scheduled skip (the lock chain continues)",
|
||||
scheduled_skips_file,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
return (today or _today_str()) in skips
|
||||
|
||||
|
||||
def has_logged_today(log_file: Path, *, today: str | None = None) -> bool:
|
||||
"""Return True if a validly-signed workout is logged for *today*.
|
||||
|
||||
The day may hold multiple workouts; return True if ANY of today's entries
|
||||
verifies (or is acceptably unsigned when no HMAC key is configured).
|
||||
"""
|
||||
entries = load_workout_log(log_file).get(today or _today_str(), [])
|
||||
if not entries:
|
||||
return False
|
||||
key_unavailable = compute_entry_hmac({"_probe": True}) is None
|
||||
for entry in entries:
|
||||
if verify_entry_hmac(entry):
|
||||
return True
|
||||
if key_unavailable and "hmac" not in entry:
|
||||
_logger.info("HMAC key unavailable — accepting unsigned entry")
|
||||
return True
|
||||
_logger.warning("HMAC verification failed for today's log entries")
|
||||
return False
|
||||
|
||||
|
||||
def is_early_bird_pending(pending_file: Path, *, today: str | None = None) -> bool:
|
||||
"""Return True if today has an unresolved early-bird pending marker."""
|
||||
if not pending_file.exists():
|
||||
return False
|
||||
try:
|
||||
with pending_file.open() as f:
|
||||
state = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not read the early-bird pending marker at %s: %s — treating "
|
||||
"it as not pending, so the lock chain proceeds as if no early bird "
|
||||
"was claimed today",
|
||||
pending_file,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
if not isinstance(state, dict) or state.get("date") != (today or _today_str()):
|
||||
return False
|
||||
if verify_entry_hmac(state):
|
||||
return True
|
||||
if compute_entry_hmac({"_probe": True}) is None and "hmac" not in state:
|
||||
_logger.info("HMAC key unavailable — accepting unsigned pending marker")
|
||||
return True
|
||||
_logger.warning("HMAC verification failed for early-bird pending marker")
|
||||
return False
|
||||
|
||||
|
||||
def is_sick_day_today(history: SickHistory, *, today: str | None = None) -> bool:
|
||||
"""Return True if today is recorded as a sick day.
|
||||
|
||||
Thin wrapper around ``_sick_tracker.is_sick_day`` kept here so callers of
|
||||
the status layer have one predicate module to import from.
|
||||
"""
|
||||
return _is_sick_day(history, today=today)
|
||||
|
||||
|
||||
def _early_bird_window_open(*, extended: bool, local_minutes: int) -> bool:
|
||||
"""Deliberate, independent reimplementation of ``_is_early_bird_time``.
|
||||
|
||||
Not shared with ``EarlyBirdMixin._is_early_bird_time`` because too many
|
||||
existing tests are pinned to its ``_get_local_time_minutes`` patch point.
|
||||
Kept here as a small, separate, pure re-implementation for the status
|
||||
layer only — see the module docstring in ``_early_bird.py``.
|
||||
"""
|
||||
start = EARLY_BIRD_START_HOUR * 60
|
||||
end = 9 * 60 if extended else EARLY_BIRD_END_HOUR * 60 + EARLY_BIRD_END_MINUTE
|
||||
return start <= local_minutes < end
|
||||
@ -18,212 +18,40 @@ surfaces the pending opportunity separately via ``AutoUpgradeOpportunity``.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
|
||||
|
||||
from screen_locker._constants import (
|
||||
EARLY_BIRD_END_HOUR,
|
||||
EARLY_BIRD_END_MINUTE,
|
||||
EARLY_BIRD_START_HOUR,
|
||||
from screen_locker._compliance_predicates import (
|
||||
_early_bird_window_open,
|
||||
has_logged_today,
|
||||
is_early_bird_pending,
|
||||
is_scheduled_skip_today,
|
||||
is_sick_day_today,
|
||||
)
|
||||
from screen_locker._compliance_trace import (
|
||||
AutoUpgradeOpportunity,
|
||||
LockExplanation,
|
||||
PredicateResult,
|
||||
_stage,
|
||||
describe_auto_upgrade_opportunity,
|
||||
)
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._sick_tracker import is_sick_day as _is_sick_day
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from screen_locker._sick_tracker import SickHistory
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _today_str() -> str:
|
||||
"""Return today's date as ``YYYY-MM-DD`` in UTC."""
|
||||
return datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PredicateResult:
|
||||
"""One evaluated step in a :class:`LockExplanation` trace."""
|
||||
|
||||
name: str
|
||||
fired: bool
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AutoUpgradeOpportunity:
|
||||
"""Describes whether the real locker would attempt a live auto-upgrade."""
|
||||
|
||||
would_attempt: bool
|
||||
via: str # "early_bird_expired" | "sick_day" | "none"
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LockExplanation:
|
||||
"""Read-only reconstruction of what the lock-decision chain would do."""
|
||||
|
||||
fired: bool
|
||||
stage: str
|
||||
reason: str
|
||||
trace: tuple[PredicateResult, ...]
|
||||
auto_upgrade: AutoUpgradeOpportunity
|
||||
heat_skip_evaluated: bool
|
||||
|
||||
|
||||
_NO_UPGRADE = AutoUpgradeOpportunity(
|
||||
would_attempt=False,
|
||||
via="none",
|
||||
reason="No pending auto-upgrade opportunity.",
|
||||
)
|
||||
|
||||
|
||||
def is_scheduled_skip_today(
|
||||
scheduled_skips_file: Path, *, today: str | None = None
|
||||
) -> bool:
|
||||
"""Return True if *today* is listed in *scheduled_skips_file*."""
|
||||
if not scheduled_skips_file.exists():
|
||||
return False
|
||||
try:
|
||||
with scheduled_skips_file.open() as f:
|
||||
skips = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not read scheduled skips from %s: %s — treating today as NOT "
|
||||
"a scheduled skip (the lock chain continues)",
|
||||
scheduled_skips_file,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
return (today or _today_str()) in skips
|
||||
|
||||
|
||||
def has_logged_today(log_file: Path, *, today: str | None = None) -> bool:
|
||||
"""Return True if a validly-signed workout is logged for *today*.
|
||||
|
||||
The day may hold multiple workouts; return True if ANY of today's entries
|
||||
verifies (or is acceptably unsigned when no HMAC key is configured).
|
||||
"""
|
||||
entries = load_workout_log(log_file).get(today or _today_str(), [])
|
||||
if not entries:
|
||||
return False
|
||||
key_unavailable = compute_entry_hmac({"_probe": True}) is None
|
||||
for entry in entries:
|
||||
if verify_entry_hmac(entry):
|
||||
return True
|
||||
if key_unavailable and "hmac" not in entry:
|
||||
_logger.info("HMAC key unavailable — accepting unsigned entry")
|
||||
return True
|
||||
_logger.warning("HMAC verification failed for today's log entries")
|
||||
return False
|
||||
|
||||
|
||||
def is_early_bird_pending(pending_file: Path, *, today: str | None = None) -> bool:
|
||||
"""Return True if today has an unresolved early-bird pending marker."""
|
||||
if not pending_file.exists():
|
||||
return False
|
||||
try:
|
||||
with pending_file.open() as f:
|
||||
state = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not read the early-bird pending marker at %s: %s — treating "
|
||||
"it as not pending, so the lock chain proceeds as if no early bird "
|
||||
"was claimed today",
|
||||
pending_file,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
if not isinstance(state, dict) or state.get("date") != (today or _today_str()):
|
||||
return False
|
||||
if verify_entry_hmac(state):
|
||||
return True
|
||||
if compute_entry_hmac({"_probe": True}) is None and "hmac" not in state:
|
||||
_logger.info("HMAC key unavailable — accepting unsigned pending marker")
|
||||
return True
|
||||
_logger.warning("HMAC verification failed for early-bird pending marker")
|
||||
return False
|
||||
|
||||
|
||||
def is_sick_day_today(history: SickHistory, *, today: str | None = None) -> bool:
|
||||
"""Return True if today is recorded as a sick day.
|
||||
|
||||
Thin wrapper around ``_sick_tracker.is_sick_day`` kept here so callers of
|
||||
the status layer have one predicate module to import from.
|
||||
"""
|
||||
return _is_sick_day(history, today=today)
|
||||
|
||||
|
||||
def _early_bird_window_open(*, extended: bool, local_minutes: int) -> bool:
|
||||
"""Deliberate, independent reimplementation of ``_is_early_bird_time``.
|
||||
|
||||
Not shared with ``EarlyBirdMixin._is_early_bird_time`` because too many
|
||||
existing tests are pinned to its ``_get_local_time_minutes`` patch point.
|
||||
Kept here as a small, separate, pure re-implementation for the status
|
||||
layer only — see the module docstring in ``_early_bird.py``.
|
||||
"""
|
||||
start = EARLY_BIRD_START_HOUR * 60
|
||||
end = 9 * 60 if extended else EARLY_BIRD_END_HOUR * 60 + EARLY_BIRD_END_MINUTE
|
||||
return start <= local_minutes < end
|
||||
|
||||
|
||||
def describe_auto_upgrade_opportunity(
|
||||
*,
|
||||
early_bird_pending: bool,
|
||||
early_bird_window_open: bool,
|
||||
is_sick_day: bool,
|
||||
) -> AutoUpgradeOpportunity:
|
||||
"""Describe what the real ``_try_auto_upgrade_*`` methods would attempt.
|
||||
|
||||
Read-only stand-in for ``AutoUpgradeMixin._check_today_state_exits``'s
|
||||
branching — never calls phone/RunnerUp verification and never writes to
|
||||
``workout_log.json``.
|
||||
"""
|
||||
if early_bird_pending and not early_bird_window_open:
|
||||
return AutoUpgradeOpportunity(
|
||||
would_attempt=True,
|
||||
via="early_bird_expired",
|
||||
reason=(
|
||||
"Early-bird window closed with no workout logged — the next "
|
||||
"lock run will try phone/RunnerUp verification before "
|
||||
"falling back to a full lock."
|
||||
),
|
||||
)
|
||||
if is_sick_day:
|
||||
return AutoUpgradeOpportunity(
|
||||
would_attempt=True,
|
||||
via="sick_day",
|
||||
reason=(
|
||||
"Sick day logged — the next lock run will try phone/RunnerUp "
|
||||
"verification to upgrade it to a real workout."
|
||||
),
|
||||
)
|
||||
return _NO_UPGRADE
|
||||
|
||||
|
||||
def _stage(
|
||||
*,
|
||||
fired: bool,
|
||||
stage: str,
|
||||
reason: str,
|
||||
trace: list[PredicateResult],
|
||||
auto_upgrade: AutoUpgradeOpportunity,
|
||||
) -> LockExplanation:
|
||||
"""Build a terminal :class:`LockExplanation` from the trace so far."""
|
||||
return LockExplanation(
|
||||
fired=fired,
|
||||
stage=stage,
|
||||
reason=reason,
|
||||
trace=tuple(trace),
|
||||
auto_upgrade=auto_upgrade,
|
||||
heat_skip_evaluated=False,
|
||||
)
|
||||
__all__ = [
|
||||
"AutoUpgradeOpportunity",
|
||||
"LockExplanation",
|
||||
"PredicateResult",
|
||||
"describe_auto_upgrade_opportunity",
|
||||
"explain_lock_decision",
|
||||
"has_logged_today",
|
||||
"is_early_bird_pending",
|
||||
"is_scheduled_skip_today",
|
||||
"is_sick_day_today",
|
||||
]
|
||||
|
||||
|
||||
def explain_lock_decision(
|
||||
|
||||
102
screen_locker/_compliance_trace.py
Normal file
102
screen_locker/_compliance_trace.py
Normal file
@ -0,0 +1,102 @@
|
||||
"""Trace dataclasses and auto-upgrade description for the lock explanation.
|
||||
|
||||
Split out of :mod:`screen_locker._compliance_state` to keep every file under
|
||||
the 250-line cap. Re-exported from there, so existing imports and patch
|
||||
targets for the predicate functions are unchanged.
|
||||
|
||||
Nothing here touches ADB, sudo, subprocess, the network or the disk.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PredicateResult:
|
||||
"""One evaluated step in a :class:`LockExplanation` trace."""
|
||||
|
||||
name: str
|
||||
fired: bool
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AutoUpgradeOpportunity:
|
||||
"""Describes whether the real locker would attempt a live auto-upgrade."""
|
||||
|
||||
would_attempt: bool
|
||||
via: str # "early_bird_expired" | "sick_day" | "none"
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LockExplanation:
|
||||
"""Read-only reconstruction of what the lock-decision chain would do."""
|
||||
|
||||
fired: bool
|
||||
stage: str
|
||||
reason: str
|
||||
trace: tuple[PredicateResult, ...]
|
||||
auto_upgrade: AutoUpgradeOpportunity
|
||||
heat_skip_evaluated: bool
|
||||
|
||||
|
||||
_NO_UPGRADE = AutoUpgradeOpportunity(
|
||||
would_attempt=False,
|
||||
via="none",
|
||||
reason="No pending auto-upgrade opportunity.",
|
||||
)
|
||||
|
||||
|
||||
def describe_auto_upgrade_opportunity(
|
||||
*,
|
||||
early_bird_pending: bool,
|
||||
early_bird_window_open: bool,
|
||||
is_sick_day: bool,
|
||||
) -> AutoUpgradeOpportunity:
|
||||
"""Describe what the real ``_try_auto_upgrade_*`` methods would attempt.
|
||||
|
||||
Read-only stand-in for ``AutoUpgradeMixin._check_today_state_exits``'s
|
||||
branching — never calls phone/RunnerUp verification and never writes to
|
||||
``workout_log.json``.
|
||||
"""
|
||||
if early_bird_pending and not early_bird_window_open:
|
||||
return AutoUpgradeOpportunity(
|
||||
would_attempt=True,
|
||||
via="early_bird_expired",
|
||||
reason=(
|
||||
"Early-bird window closed with no workout logged — the next "
|
||||
"lock run will try phone/RunnerUp verification before "
|
||||
"falling back to a full lock."
|
||||
),
|
||||
)
|
||||
if is_sick_day:
|
||||
return AutoUpgradeOpportunity(
|
||||
would_attempt=True,
|
||||
via="sick_day",
|
||||
reason=(
|
||||
"Sick day logged — the next lock run will try phone/RunnerUp "
|
||||
"verification to upgrade it to a real workout."
|
||||
),
|
||||
)
|
||||
return _NO_UPGRADE
|
||||
|
||||
|
||||
def _stage(
|
||||
*,
|
||||
fired: bool,
|
||||
stage: str,
|
||||
reason: str,
|
||||
trace: list[PredicateResult],
|
||||
auto_upgrade: AutoUpgradeOpportunity,
|
||||
) -> LockExplanation:
|
||||
"""Build a terminal :class:`LockExplanation` from the trace so far."""
|
||||
return LockExplanation(
|
||||
fired=fired,
|
||||
stage=stage,
|
||||
reason=reason,
|
||||
trace=tuple(trace),
|
||||
auto_upgrade=auto_upgrade,
|
||||
heat_skip_evaluated=False,
|
||||
)
|
||||
94
screen_locker/_http_workout_fetch.py
Normal file
94
screen_locker/_http_workout_fetch.py
Normal file
@ -0,0 +1,94 @@
|
||||
"""HTTP fallback for phone verification: find the app's server, fetch JSON.
|
||||
|
||||
Split out of :mod:`screen_locker._phone_verification` to keep every file under
|
||||
the 250-line cap. Composed back into ``PhoneVerificationMixin`` there, so
|
||||
callers see no change.
|
||||
|
||||
Used when adb cannot reach the phone but it is on the same wifi: the workout
|
||||
app serves the same JSON over ``WORKOUT_HTTP_PORT``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ( # pylint: disable=no-name-in-module
|
||||
ThreadPoolExecutor,
|
||||
as_completed,
|
||||
)
|
||||
import contextlib
|
||||
from http import client as _http_client
|
||||
import json
|
||||
import logging
|
||||
import socket
|
||||
|
||||
from screen_locker._constants import WORKOUT_HTTP_PORT
|
||||
|
||||
_HTTPConnection = _http_client.HTTPConnection
|
||||
_HTTPException = _http_client.HTTPException
|
||||
_HTTP_OK = _http_client.OK
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HttpWorkoutFetchMixin:
|
||||
"""Scans the local subnet for the workout app's HTTP server."""
|
||||
|
||||
def _scan_for_http_server(self) -> str | None:
|
||||
"""Scan local /24 subnet for the workout app HTTP server on port 8765.
|
||||
|
||||
Returns the first reachable URL or None.
|
||||
"""
|
||||
prefix = self._get_local_subnet_prefix()
|
||||
if prefix is None:
|
||||
return None
|
||||
|
||||
def probe(i: int) -> str | None:
|
||||
ip = f"{prefix}.{i}"
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.create_connection((ip, WORKOUT_HTTP_PORT), timeout=0.3),
|
||||
):
|
||||
return f"http://{ip}:{WORKOUT_HTTP_PORT}/workout"
|
||||
return None
|
||||
|
||||
_logger.info(
|
||||
"Scanning %s.1-254:%d for workout app...", prefix, WORKOUT_HTTP_PORT
|
||||
)
|
||||
with ThreadPoolExecutor(max_workers=64) as executor:
|
||||
for future in as_completed(
|
||||
executor.submit(probe, i) for i in range(1, 255)
|
||||
):
|
||||
result = future.result()
|
||||
if result is not None:
|
||||
return result
|
||||
return None
|
||||
|
||||
def _fetch_http_workout(self) -> dict | None:
|
||||
"""Fetch workout JSON from the app's HTTP server on the local network.
|
||||
|
||||
Uses http.client directly to avoid urllib URL-open security lint rules.
|
||||
The URL is always http://<local-ip>:8765/workout — no user input involved.
|
||||
"""
|
||||
url = self._scan_for_http_server()
|
||||
if url is None:
|
||||
return None
|
||||
# url is always "http://<ip>:<port>/workout" — constructed internally.
|
||||
try:
|
||||
_, _, hostport = url.partition("://")
|
||||
host, _, path = hostport.partition("/")
|
||||
hostname, _, port_str = host.partition(":")
|
||||
conn = _HTTPConnection(hostname, int(port_str), timeout=5)
|
||||
conn.request("GET", f"/{path}")
|
||||
resp = conn.getresponse()
|
||||
if resp.status != _HTTP_OK:
|
||||
return None
|
||||
return json.loads(resp.read().decode())
|
||||
except (_HTTPException, OSError, ValueError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"HTTP fetch of today's workout from %s failed (%s) — no data "
|
||||
"from the phone's HTTP server, so verification falls through",
|
||||
url,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
# ── Main verification entry point ─────────────────────────────────────────
|
||||
@ -15,14 +15,10 @@ see :class:`ManualWorkoutDraft` and :data:`SPORT_CHOICES`.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timezone
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._constants import (
|
||||
MANUAL_WORKOUT_BUDGET_PER_7_DAYS,
|
||||
MANUAL_WORKOUT_BUDGET_PER_30_DAYS,
|
||||
MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS,
|
||||
MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
|
||||
MANUAL_WORKOUT_RPE_MAX,
|
||||
@ -30,137 +26,36 @@ from screen_locker._constants import (
|
||||
MIN_WORKOUT_DURATION_MINUTES,
|
||||
WORKOUT_DURATION_ACCEPT_MINUTES,
|
||||
)
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._manual_workout_types import (
|
||||
MANUAL_WORKOUT_TYPE,
|
||||
SPORT_CHOICES,
|
||||
SPORT_LABELS,
|
||||
SPORT_OTHER,
|
||||
SPORT_TABLE_TENNIS,
|
||||
ManualWorkoutDraft,
|
||||
budget_summary,
|
||||
count_in_window,
|
||||
is_budget_exhausted,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
__all__ = [
|
||||
"MANUAL_WORKOUT_TYPE",
|
||||
"SPORT_CHOICES",
|
||||
"SPORT_LABELS",
|
||||
"SPORT_OTHER",
|
||||
"SPORT_TABLE_TENNIS",
|
||||
"ManualWorkoutDraft",
|
||||
"budget_summary",
|
||||
"build_entry",
|
||||
"build_sync_payload",
|
||||
"count_in_window",
|
||||
"is_budget_exhausted",
|
||||
"manual_sync_record_id",
|
||||
"validate_manual_workout",
|
||||
]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
MANUAL_WORKOUT_TYPE = "manual_workout"
|
||||
|
||||
SPORT_TABLE_TENNIS = "table_tennis"
|
||||
SPORT_OTHER = "other"
|
||||
SPORT_CHOICES: tuple[str, ...] = (SPORT_TABLE_TENNIS, SPORT_OTHER)
|
||||
SPORT_LABELS: dict[str, str] = {
|
||||
SPORT_TABLE_TENNIS: "Table tennis",
|
||||
SPORT_OTHER: "Other",
|
||||
}
|
||||
|
||||
|
||||
def _today_iso() -> str:
|
||||
"""Return today's date as ``YYYY-MM-DD`` (UTC)."""
|
||||
return datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _parse_iso(date_str: str) -> datetime | None:
|
||||
"""Parse ``YYYY-MM-DD`` into a UTC datetime, or return None."""
|
||||
try:
|
||||
return datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"Workout log has an unparsable date key %r (%s) — that day is "
|
||||
"IGNORED when counting the manual-workout budget",
|
||||
date_str,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def count_in_window(
|
||||
log_file: Path,
|
||||
days: int,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> int:
|
||||
"""Return how many ``manual_workout`` ENTRIES fall in the trailing window.
|
||||
|
||||
Counted per entry, not per day: each logged manual workout consumes its
|
||||
own budget slot, matching how each one also earns its own weekly-count
|
||||
and shutdown credit (see ``screen_locker._weekly_check.COUNTED_WORKOUT_TYPES``
|
||||
and ``screen_locker._workout_credit``) — the budget is the sole limiter on
|
||||
how many you can log, not a once-per-day collapse.
|
||||
"""
|
||||
today_str = today or _today_iso()
|
||||
today_dt = _parse_iso(today_str)
|
||||
if today_dt is None:
|
||||
return 0
|
||||
cutoff = today_dt - timedelta(days=days)
|
||||
count = 0
|
||||
for date_str, entries in load_workout_log(log_file).items():
|
||||
parsed = _parse_iso(date_str)
|
||||
if parsed is None or not (cutoff < parsed <= today_dt):
|
||||
continue
|
||||
count += sum(
|
||||
1
|
||||
for entry in entries
|
||||
if entry.get("workout_data", {}).get("type") == MANUAL_WORKOUT_TYPE
|
||||
)
|
||||
return count
|
||||
|
||||
|
||||
def is_budget_exhausted(
|
||||
log_file: Path,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> bool:
|
||||
"""Return True if either rolling window has reached its manual-workout budget."""
|
||||
return (
|
||||
count_in_window(log_file, 7, today=today) >= MANUAL_WORKOUT_BUDGET_PER_7_DAYS
|
||||
or count_in_window(log_file, 30, today=today)
|
||||
>= MANUAL_WORKOUT_BUDGET_PER_30_DAYS
|
||||
)
|
||||
|
||||
|
||||
def budget_summary(
|
||||
log_file: Path,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> str:
|
||||
"""One-line UI summary string for the manual-workout budget."""
|
||||
week = count_in_window(log_file, 7, today=today)
|
||||
month = count_in_window(log_file, 30, today=today)
|
||||
return (
|
||||
f"Manual: {week}/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS}w · "
|
||||
f"{month}/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}m"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ManualWorkoutDraft:
|
||||
"""User-supplied evidence fields for a manual (unverified) workout.
|
||||
|
||||
Fields shared by every sport come first (required unless noted).
|
||||
Sport-specific fields follow, grouped by which ``sport`` they apply to —
|
||||
only the group matching ``sport`` is validated/persisted.
|
||||
"""
|
||||
|
||||
sport: str
|
||||
start_time: str # "HH:MM"
|
||||
end_time: str # "HH:MM"
|
||||
location_name: str
|
||||
transport_method: str
|
||||
cost: str
|
||||
rpe: int
|
||||
went_well: str
|
||||
to_improve: str
|
||||
overall_feeling: str
|
||||
reservation_phone: str = ""
|
||||
techniques_practiced: str = ""
|
||||
warm_up_minutes: str = ""
|
||||
pain_or_injury: str = "none"
|
||||
# SPORT_TABLE_TENNIS fields
|
||||
matches_won: int = 0
|
||||
matches_lost: int = 0
|
||||
sets_won: int = 0
|
||||
sets_lost: int = 0
|
||||
racket: str = ""
|
||||
balls: str = ""
|
||||
# SPORT_OTHER fields
|
||||
activity_type_other: str = ""
|
||||
activity_details: str = ""
|
||||
equipment: str = ""
|
||||
|
||||
|
||||
def _parse_hhmm(value: str) -> datetime | None:
|
||||
"""Parse an ``HH:MM`` string into a datetime on an arbitrary fixed date."""
|
||||
|
||||
@ -21,9 +21,9 @@ import tkinter as tk
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._constants import (
|
||||
MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS,
|
||||
MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
|
||||
)
|
||||
from screen_locker._manual_workout_sport_fields import ManualWorkoutSportFieldsMixin
|
||||
from screen_locker._manual_workout_widgets import ManualWorkoutFormWidgetsMixin
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
@ -33,7 +33,10 @@ _SPORT_LABEL_TO_CODE = {
|
||||
}
|
||||
|
||||
|
||||
class ManualWorkoutDialogMixin(ManualWorkoutFormWidgetsMixin):
|
||||
class ManualWorkoutDialogMixin(
|
||||
ManualWorkoutFormWidgetsMixin,
|
||||
ManualWorkoutSportFieldsMixin,
|
||||
):
|
||||
"""Renders the manual-workout evidence form and handles submission."""
|
||||
|
||||
def _show_manual_workout_form(self) -> None:
|
||||
@ -66,40 +69,6 @@ class ManualWorkoutDialogMixin(ManualWorkoutFormWidgetsMixin):
|
||||
)
|
||||
self._build_manual_workout_form()
|
||||
|
||||
def _mw_scrollable_form(self) -> tk.Frame:
|
||||
"""Create the two-column form frame inside the surface's viewport.
|
||||
|
||||
This used to build its *own* ``Canvas`` + ``Scrollbar`` viewport, which
|
||||
had three problems that are all gone by deletion now that the surface
|
||||
container is itself a :class:`~gatelock.ScrollableSurface`:
|
||||
|
||||
1. **Scrolling was pointer-only.** ``tk.Canvas`` has no class-level key
|
||||
bindings, so ``::tk::FocusOK`` rejected it as a focus stop, and the
|
||||
canvas bound no ``<MouseWheel>``, ``<Prior>``/``<Next>`` or arrows.
|
||||
The scrollbar thumb had to be *dragged* -- inside a lock that cannot
|
||||
be dismissed without submitting this form.
|
||||
2. **Focus walked off-screen.** Canvas clipping does not unmap a child,
|
||||
so every below-the-fold field stayed ``winfo viewable`` and stayed in
|
||||
the tab ring while Tk never scrolled to follow focus. Tab led to
|
||||
fields the user could neither see nor bring into view.
|
||||
3. **The height was a magic fraction.** ``height=0.7 * toplevel`` sat
|
||||
above ~230-290px of fixed chrome (title, budget line, error label,
|
||||
and a 24pt button row), so the constraint was ``0.3 * H >= chrome``:
|
||||
satisfied at 1080p, violated at 768p, where SUBMIT/BACK were pushed
|
||||
off the bottom of a centred, unscrollable container.
|
||||
|
||||
Still built on the primary surface only -- an independently scrolled
|
||||
copy per monitor would show two different parts of one form.
|
||||
"""
|
||||
form = tk.Frame(self.container.first, bg=self._colors.bg)
|
||||
# No outer gap: the budget line above and the first section heading
|
||||
# below already separate the grid, and on a 1024x600 panel this form
|
||||
# fits by single-digit pixels.
|
||||
form.pack(fill="both", expand=True)
|
||||
form.grid_columnconfigure(0, weight=1, uniform="mw")
|
||||
form.grid_columnconfigure(1, weight=1, uniform="mw")
|
||||
return form
|
||||
|
||||
def _build_manual_workout_form(self) -> None:
|
||||
"""Build the two-column evidence form and submit/back buttons.
|
||||
|
||||
@ -200,114 +169,6 @@ class ManualWorkoutDialogMixin(ManualWorkoutFormWidgetsMixin):
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
|
||||
def _mw_sport_row(self, parent: tk.Widget) -> None:
|
||||
"""Add the sport-selector radio buttons; swaps the activity section.
|
||||
|
||||
CANONICAL ACCOUNT OF THE 2026-07-26 BUG -- other files point here.
|
||||
|
||||
This was a ``tk.OptionMenu``. A posted Tk menu is a separate
|
||||
override-redirect toplevel that takes the Tk grab for itself, and
|
||||
gatelock's 1 s recovery tick killed it within a second of opening:
|
||||
``_surfaces.enforce()`` lifts the lock surface over the menu, and
|
||||
``_reassert_grab()`` saw the grab sitting on the menu rather than the
|
||||
root and yanked it back. The selector stayed stuck on "Table tennis"
|
||||
while locked, and a walk got logged in the table-tennis form.
|
||||
|
||||
Radio buttons are ordinary children of the surface: they lift with it
|
||||
and live inside the root's grab tree, so neither mechanism can reach
|
||||
them. Nothing on a lock surface may open a popup window --
|
||||
``tests/test_no_popup_widgets.py`` enforces that statically and
|
||||
``scripts/verify_lock_popup_safety.py`` behaviourally.
|
||||
"""
|
||||
self._mw_sport_var = tk.StringVar(
|
||||
value=_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
|
||||
)
|
||||
row = tk.Frame(parent, bg=self._colors.bg)
|
||||
tk.Label(
|
||||
row,
|
||||
text="Sport:",
|
||||
font=self._colors.font("body"),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
for label in _manual_workout.SPORT_LABELS.values():
|
||||
tk.Radiobutton(
|
||||
row,
|
||||
text=label,
|
||||
value=label,
|
||||
variable=self._mw_sport_var,
|
||||
# Radiobutton's command takes no argument -- bind the label.
|
||||
command=lambda chosen=label: self._on_mw_sport_changed(chosen),
|
||||
font=self._colors.font("body"),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
activeforeground=self._colors.fg,
|
||||
activebackground=self._colors.bg,
|
||||
# Without selectcolor the indicator is a white blob on the dark
|
||||
# overlay; the OptionMenu was the one unstyled widget in this
|
||||
# form, which likely added to it reading as dead.
|
||||
selectcolor=self._colors.field_bg,
|
||||
highlightthickness=0,
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
self._mw_grid(parent, row, full=True)
|
||||
|
||||
def _on_mw_sport_changed(self, selected_label: str) -> None:
|
||||
"""Show the fields for the newly-selected sport, hide the other's.
|
||||
|
||||
Both frames share one grid slot; ``grid_remove`` hides a frame while
|
||||
remembering its cell options so ``grid`` restores it in place.
|
||||
"""
|
||||
sport = _SPORT_LABEL_TO_CODE.get(
|
||||
selected_label, _manual_workout.SPORT_TABLE_TENNIS
|
||||
)
|
||||
if sport == _manual_workout.SPORT_TABLE_TENNIS:
|
||||
self._mw_other_frame.grid_remove()
|
||||
self._mw_tt_frame.grid()
|
||||
else:
|
||||
self._mw_tt_frame.grid_remove()
|
||||
self._mw_other_frame.grid()
|
||||
|
||||
def _build_table_tennis_fields(self, parent: tk.Widget) -> None:
|
||||
"""Build the table-tennis-specific score/equipment fields."""
|
||||
self._mw_int_vars["matches_won"] = self._mw_int_field(parent, "Matches won:")
|
||||
self._mw_int_vars["matches_lost"] = self._mw_int_field(parent, "Matches lost:")
|
||||
self._mw_int_vars["sets_won"] = self._mw_int_field(parent, "Sets won:")
|
||||
self._mw_int_vars["sets_lost"] = self._mw_int_field(parent, "Sets lost:")
|
||||
self._mw_vars["racket"] = self._mw_entry(parent, "Racket used:")
|
||||
self._mw_vars["balls"] = self._mw_entry(parent, "Balls used:")
|
||||
|
||||
def _build_other_sport_fields(self, parent: tk.Widget) -> None:
|
||||
"""Build the generic "other sport" fields."""
|
||||
self._mw_vars["activity_type_other"] = self._mw_entry(
|
||||
parent, "What sport/activity:"
|
||||
)
|
||||
self._mw_text_widgets["activity_details"] = self._mw_textbox(
|
||||
parent,
|
||||
f"What was done (min {MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS} chars):",
|
||||
)
|
||||
self._mw_vars["equipment"] = self._mw_entry(
|
||||
parent, "Equipment used (optional):"
|
||||
)
|
||||
|
||||
def _current_mw_sport(self) -> str:
|
||||
"""Return the internal sport code for the currently-selected label."""
|
||||
return _SPORT_LABEL_TO_CODE.get(
|
||||
self._mw_sport_var.get(), _manual_workout.SPORT_TABLE_TENNIS
|
||||
)
|
||||
|
||||
def _mw_int_value(self, key: str) -> int:
|
||||
"""Read an int Spinbox var, defaulting to 0 on an invalid value."""
|
||||
try:
|
||||
return int(self._mw_int_vars[key].get())
|
||||
except (tk.TclError, ValueError) as exc:
|
||||
_logger.warning(
|
||||
"Manual workout field %r holds a non-integer value (%s) — "
|
||||
"recording it as 0",
|
||||
key,
|
||||
exc,
|
||||
)
|
||||
return 0
|
||||
|
||||
def _submit_manual_workout_form(self) -> None:
|
||||
"""Validate the form and either show an error or save + notify host."""
|
||||
try:
|
||||
|
||||
135
screen_locker/_manual_workout_sport_fields.py
Normal file
135
screen_locker/_manual_workout_sport_fields.py
Normal file
@ -0,0 +1,135 @@
|
||||
"""Sport-specific rows of the manual-workout evidence form.
|
||||
|
||||
Split out of :mod:`screen_locker._manual_workout_dialog` to keep every file
|
||||
under the 250-line cap. Composed back into ``ManualWorkoutDialogMixin`` there,
|
||||
so both host classes (``ScreenLocker`` and ``StatusWindow``) are unchanged.
|
||||
|
||||
Choosing a sport swaps in that sport's fields rather than showing one generic
|
||||
free-text blob -- see ``_manual_workout.SPORT_CHOICES``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import tkinter as tk
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._constants import MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_SPORT_LABEL_TO_CODE = {
|
||||
label: code for code, label in _manual_workout.SPORT_LABELS.items()
|
||||
}
|
||||
|
||||
|
||||
class ManualWorkoutSportFieldsMixin:
|
||||
"""Builds the sport picker and the per-sport detail rows."""
|
||||
|
||||
def _mw_sport_row(self, parent: tk.Widget) -> None:
|
||||
"""Add the sport-selector radio buttons; swaps the activity section.
|
||||
|
||||
CANONICAL ACCOUNT OF THE 2026-07-26 BUG -- other files point here.
|
||||
|
||||
This was a ``tk.OptionMenu``. A posted Tk menu is a separate
|
||||
override-redirect toplevel that takes the Tk grab for itself, and
|
||||
gatelock's 1 s recovery tick killed it within a second of opening:
|
||||
``_surfaces.enforce()`` lifts the lock surface over the menu, and
|
||||
``_reassert_grab()`` saw the grab sitting on the menu rather than the
|
||||
root and yanked it back. The selector stayed stuck on "Table tennis"
|
||||
while locked, and a walk got logged in the table-tennis form.
|
||||
|
||||
Radio buttons are ordinary children of the surface: they lift with it
|
||||
and live inside the root's grab tree, so neither mechanism can reach
|
||||
them. Nothing on a lock surface may open a popup window --
|
||||
``tests/test_no_popup_widgets.py`` enforces that statically and
|
||||
``scripts/verify_lock_popup_safety.py`` behaviourally.
|
||||
"""
|
||||
self._mw_sport_var = tk.StringVar(
|
||||
value=_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
|
||||
)
|
||||
row = tk.Frame(parent, bg=self._colors.bg)
|
||||
tk.Label(
|
||||
row,
|
||||
text="Sport:",
|
||||
font=self._colors.font("body"),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
for label in _manual_workout.SPORT_LABELS.values():
|
||||
tk.Radiobutton(
|
||||
row,
|
||||
text=label,
|
||||
value=label,
|
||||
variable=self._mw_sport_var,
|
||||
# Radiobutton's command takes no argument -- bind the label.
|
||||
command=lambda chosen=label: self._on_mw_sport_changed(chosen),
|
||||
font=self._colors.font("body"),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
activeforeground=self._colors.fg,
|
||||
activebackground=self._colors.bg,
|
||||
# Without selectcolor the indicator is a white blob on the dark
|
||||
# overlay; the OptionMenu was the one unstyled widget in this
|
||||
# form, which likely added to it reading as dead.
|
||||
selectcolor=self._colors.field_bg,
|
||||
highlightthickness=0,
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
self._mw_grid(parent, row, full=True)
|
||||
|
||||
def _on_mw_sport_changed(self, selected_label: str) -> None:
|
||||
"""Show the fields for the newly-selected sport, hide the other's.
|
||||
|
||||
Both frames share one grid slot; ``grid_remove`` hides a frame while
|
||||
remembering its cell options so ``grid`` restores it in place.
|
||||
"""
|
||||
sport = _SPORT_LABEL_TO_CODE.get(
|
||||
selected_label, _manual_workout.SPORT_TABLE_TENNIS
|
||||
)
|
||||
if sport == _manual_workout.SPORT_TABLE_TENNIS:
|
||||
self._mw_other_frame.grid_remove()
|
||||
self._mw_tt_frame.grid()
|
||||
else:
|
||||
self._mw_tt_frame.grid_remove()
|
||||
self._mw_other_frame.grid()
|
||||
|
||||
def _build_table_tennis_fields(self, parent: tk.Widget) -> None:
|
||||
"""Build the table-tennis-specific score/equipment fields."""
|
||||
self._mw_int_vars["matches_won"] = self._mw_int_field(parent, "Matches won:")
|
||||
self._mw_int_vars["matches_lost"] = self._mw_int_field(parent, "Matches lost:")
|
||||
self._mw_int_vars["sets_won"] = self._mw_int_field(parent, "Sets won:")
|
||||
self._mw_int_vars["sets_lost"] = self._mw_int_field(parent, "Sets lost:")
|
||||
self._mw_vars["racket"] = self._mw_entry(parent, "Racket used:")
|
||||
self._mw_vars["balls"] = self._mw_entry(parent, "Balls used:")
|
||||
|
||||
def _build_other_sport_fields(self, parent: tk.Widget) -> None:
|
||||
"""Build the generic "other sport" fields."""
|
||||
self._mw_vars["activity_type_other"] = self._mw_entry(
|
||||
parent, "What sport/activity:"
|
||||
)
|
||||
self._mw_text_widgets["activity_details"] = self._mw_textbox(
|
||||
parent,
|
||||
f"What was done (min {MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS} chars):",
|
||||
)
|
||||
self._mw_vars["equipment"] = self._mw_entry(
|
||||
parent, "Equipment used (optional):"
|
||||
)
|
||||
|
||||
def _current_mw_sport(self) -> str:
|
||||
"""Return the internal sport code for the currently-selected label."""
|
||||
return _SPORT_LABEL_TO_CODE.get(
|
||||
self._mw_sport_var.get(), _manual_workout.SPORT_TABLE_TENNIS
|
||||
)
|
||||
|
||||
def _mw_int_value(self, key: str) -> int:
|
||||
"""Read an int Spinbox var, defaulting to 0 on an invalid value."""
|
||||
try:
|
||||
return int(self._mw_int_vars[key].get())
|
||||
except (tk.TclError, ValueError) as exc:
|
||||
_logger.warning(
|
||||
"Manual workout field %r holds a non-integer value (%s) — "
|
||||
"recording it as 0",
|
||||
key,
|
||||
exc,
|
||||
)
|
||||
return 0
|
||||
151
screen_locker/_manual_workout_types.py
Normal file
151
screen_locker/_manual_workout_types.py
Normal file
@ -0,0 +1,151 @@
|
||||
"""Manual-workout sports, the draft record, and rolling budget accounting.
|
||||
|
||||
Split out of :mod:`screen_locker._manual_workout` to keep every file under the
|
||||
250-line cap. Everything here is re-exported from there, so callers and their
|
||||
patch targets are unchanged.
|
||||
|
||||
The budget is what stops a manual entry from being an unlimited escape hatch:
|
||||
manual workouts are self-reported, so only a few count in any rolling window.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._constants import (
|
||||
MANUAL_WORKOUT_BUDGET_PER_7_DAYS,
|
||||
MANUAL_WORKOUT_BUDGET_PER_30_DAYS,
|
||||
)
|
||||
from screen_locker._log_io import load_workout_log
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
MANUAL_WORKOUT_TYPE = "manual_workout"
|
||||
|
||||
SPORT_TABLE_TENNIS = "table_tennis"
|
||||
SPORT_OTHER = "other"
|
||||
SPORT_CHOICES: tuple[str, ...] = (SPORT_TABLE_TENNIS, SPORT_OTHER)
|
||||
SPORT_LABELS: dict[str, str] = {
|
||||
SPORT_TABLE_TENNIS: "Table tennis",
|
||||
SPORT_OTHER: "Other",
|
||||
}
|
||||
|
||||
|
||||
def _today_iso() -> str:
|
||||
"""Return today's date as ``YYYY-MM-DD`` (UTC)."""
|
||||
return datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _parse_iso(date_str: str) -> datetime | None:
|
||||
"""Parse ``YYYY-MM-DD`` into a UTC datetime, or return None."""
|
||||
try:
|
||||
return datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"Workout log has an unparsable date key %r (%s) — that day is "
|
||||
"IGNORED when counting the manual-workout budget",
|
||||
date_str,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def count_in_window(
|
||||
log_file: Path,
|
||||
days: int,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> int:
|
||||
"""Return how many ``manual_workout`` ENTRIES fall in the trailing window.
|
||||
|
||||
Counted per entry, not per day: each logged manual workout consumes its
|
||||
own budget slot, matching how each one also earns its own weekly-count
|
||||
and shutdown credit (see ``screen_locker._weekly_check.COUNTED_WORKOUT_TYPES``
|
||||
and ``screen_locker._workout_credit``) — the budget is the sole limiter on
|
||||
how many you can log, not a once-per-day collapse.
|
||||
"""
|
||||
today_str = today or _today_iso()
|
||||
today_dt = _parse_iso(today_str)
|
||||
if today_dt is None:
|
||||
return 0
|
||||
cutoff = today_dt - timedelta(days=days)
|
||||
count = 0
|
||||
for date_str, entries in load_workout_log(log_file).items():
|
||||
parsed = _parse_iso(date_str)
|
||||
if parsed is None or not (cutoff < parsed <= today_dt):
|
||||
continue
|
||||
count += sum(
|
||||
1
|
||||
for entry in entries
|
||||
if entry.get("workout_data", {}).get("type") == MANUAL_WORKOUT_TYPE
|
||||
)
|
||||
return count
|
||||
|
||||
|
||||
def is_budget_exhausted(
|
||||
log_file: Path,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> bool:
|
||||
"""Return True if either rolling window has reached its manual-workout budget."""
|
||||
return (
|
||||
count_in_window(log_file, 7, today=today) >= MANUAL_WORKOUT_BUDGET_PER_7_DAYS
|
||||
or count_in_window(log_file, 30, today=today)
|
||||
>= MANUAL_WORKOUT_BUDGET_PER_30_DAYS
|
||||
)
|
||||
|
||||
|
||||
def budget_summary(
|
||||
log_file: Path,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> str:
|
||||
"""One-line UI summary string for the manual-workout budget."""
|
||||
week = count_in_window(log_file, 7, today=today)
|
||||
month = count_in_window(log_file, 30, today=today)
|
||||
return (
|
||||
f"Manual: {week}/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS}w · "
|
||||
f"{month}/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}m"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ManualWorkoutDraft:
|
||||
"""User-supplied evidence fields for a manual (unverified) workout.
|
||||
|
||||
Fields shared by every sport come first (required unless noted).
|
||||
Sport-specific fields follow, grouped by which ``sport`` they apply to —
|
||||
only the group matching ``sport`` is validated/persisted.
|
||||
"""
|
||||
|
||||
sport: str
|
||||
start_time: str # "HH:MM"
|
||||
end_time: str # "HH:MM"
|
||||
location_name: str
|
||||
transport_method: str
|
||||
cost: str
|
||||
rpe: int
|
||||
went_well: str
|
||||
to_improve: str
|
||||
overall_feeling: str
|
||||
reservation_phone: str = ""
|
||||
techniques_practiced: str = ""
|
||||
warm_up_minutes: str = ""
|
||||
pain_or_injury: str = "none"
|
||||
# SPORT_TABLE_TENNIS fields
|
||||
matches_won: int = 0
|
||||
matches_lost: int = 0
|
||||
sets_won: int = 0
|
||||
sets_lost: int = 0
|
||||
racket: str = ""
|
||||
balls: str = ""
|
||||
# SPORT_OTHER fields
|
||||
activity_type_other: str = ""
|
||||
activity_details: str = ""
|
||||
equipment: str = ""
|
||||
@ -208,3 +208,37 @@ class ManualWorkoutFormWidgetsMixin:
|
||||
**self._colors.focus_kwargs(),
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
self._mw_grid(parent, row)
|
||||
|
||||
def _mw_scrollable_form(self) -> tk.Frame:
|
||||
"""Create the two-column form frame inside the surface's viewport.
|
||||
|
||||
This used to build its *own* ``Canvas`` + ``Scrollbar`` viewport, which
|
||||
had three problems that are all gone by deletion now that the surface
|
||||
container is itself a :class:`~gatelock.ScrollableSurface`:
|
||||
|
||||
1. **Scrolling was pointer-only.** ``tk.Canvas`` has no class-level key
|
||||
bindings, so ``::tk::FocusOK`` rejected it as a focus stop, and the
|
||||
canvas bound no ``<MouseWheel>``, ``<Prior>``/``<Next>`` or arrows.
|
||||
The scrollbar thumb had to be *dragged* -- inside a lock that cannot
|
||||
be dismissed without submitting this form.
|
||||
2. **Focus walked off-screen.** Canvas clipping does not unmap a child,
|
||||
so every below-the-fold field stayed ``winfo viewable`` and stayed in
|
||||
the tab ring while Tk never scrolled to follow focus. Tab led to
|
||||
fields the user could neither see nor bring into view.
|
||||
3. **The height was a magic fraction.** ``height=0.7 * toplevel`` sat
|
||||
above ~230-290px of fixed chrome (title, budget line, error label,
|
||||
and a 24pt button row), so the constraint was ``0.3 * H >= chrome``:
|
||||
satisfied at 1080p, violated at 768p, where SUBMIT/BACK were pushed
|
||||
off the bottom of a centred, unscrollable container.
|
||||
|
||||
Still built on the primary surface only -- an independently scrolled
|
||||
copy per monitor would show two different parts of one form.
|
||||
"""
|
||||
form = tk.Frame(self.container.first, bg=self._colors.bg)
|
||||
# No outer gap: the budget line above and the first section heading
|
||||
# below already separate the grid, and on a 1024x600 panel this form
|
||||
# fits by single-digit pixels.
|
||||
form.pack(fill="both", expand=True)
|
||||
form.grid_columnconfigure(0, weight=1, uniform="mw")
|
||||
form.grid_columnconfigure(1, weight=1, uniform="mw")
|
||||
return form
|
||||
|
||||
@ -2,29 +2,21 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ( # pylint: disable=no-name-in-module
|
||||
ThreadPoolExecutor,
|
||||
as_completed,
|
||||
)
|
||||
import contextlib
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from http import client as _http_client
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from screen_locker._adb_transport import AdbTransportMixin
|
||||
from screen_locker._constants import (
|
||||
ADB_TIMEOUT,
|
||||
MIN_WORKOUT_DURATION_MINUTES,
|
||||
WORKOUT_APP_JSON_REMOTES,
|
||||
WORKOUT_DURATION_ACCEPT_MINUTES,
|
||||
WORKOUT_HTTP_PORT,
|
||||
)
|
||||
from screen_locker._http_workout_fetch import HttpWorkoutFetchMixin
|
||||
from screen_locker._log_mixin import write_signed_entry
|
||||
from screen_locker._time_check import check_clock_skew
|
||||
from screen_locker._workout_sync import pull_synced_workout
|
||||
@ -36,116 +28,9 @@ _HTTP_OK = _http_client.OK
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PhoneVerificationMixin:
|
||||
class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
|
||||
"""Mixin providing phone-based workout verification via ADB."""
|
||||
|
||||
def _run_adb(self, args: list[str]) -> tuple[bool, str]:
|
||||
"""Run an ADB command and return success flag and stdout."""
|
||||
adb = shutil.which("adb") or "adb"
|
||||
# When multiple devices are connected (e.g. USB + wireless), pin to
|
||||
# the wireless device's serial to avoid "more than one device" errors.
|
||||
_discovery_cmds = {"devices", "connect", "disconnect", "kill-server"}
|
||||
serial = (
|
||||
self._get_wireless_serial()
|
||||
if args and args[0] not in _discovery_cmds
|
||||
else None
|
||||
)
|
||||
serial_args = ["-s", serial] if serial else []
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[adb, *serial_args, *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=ADB_TIMEOUT,
|
||||
check=False,
|
||||
)
|
||||
except (FileNotFoundError, OSError) as exc:
|
||||
_logger.warning("ADB not available: %s", exc)
|
||||
return False, ""
|
||||
except subprocess.TimeoutExpired:
|
||||
_logger.warning("ADB command timed out: %s", args)
|
||||
return False, ""
|
||||
return not result.returncode, result.stdout
|
||||
|
||||
def _adb_shell(self, command: str, *, root: bool = False) -> tuple[bool, str]:
|
||||
"""Run a shell command on the connected Android device."""
|
||||
if root:
|
||||
return self._run_adb(["shell", "su", "-c", command])
|
||||
return self._run_adb(["shell", command])
|
||||
|
||||
def _get_wireless_serial(self) -> str | None:
|
||||
"""Return the serial (ip:port) of the first connected wireless ADB device."""
|
||||
success, output = self._run_adb(["devices"])
|
||||
if not success:
|
||||
return None
|
||||
for line in output.strip().split("\n")[1:]:
|
||||
parts = line.split()
|
||||
if parts and ":" in parts[0] and "device" in line and "offline" not in line:
|
||||
return parts[0]
|
||||
return None
|
||||
|
||||
def _has_adb_device(self) -> bool:
|
||||
"""Return True if adb devices shows at least one connected device."""
|
||||
success, output = self._run_adb(["devices"])
|
||||
if not success:
|
||||
return False
|
||||
lines = output.strip().split("\n")[1:]
|
||||
return any("device" in line and "offline" not in line for line in lines)
|
||||
|
||||
def _try_adb_connect(self, address: str) -> bool:
|
||||
"""Run adb connect to address. Returns True on success."""
|
||||
_, output = self._run_adb(["connect", address])
|
||||
lower = output.lower()
|
||||
return "connected" in lower and "unable" not in lower and "failed" not in lower
|
||||
|
||||
def _get_local_subnet_prefix(self) -> str | None:
|
||||
"""Detect the local /24 network prefix (e.g. '192.168.1')."""
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock,
|
||||
):
|
||||
sock.connect(("8.8.8.8", 80))
|
||||
return ".".join(sock.getsockname()[0].split(".")[:3])
|
||||
return None
|
||||
|
||||
def _try_wireless_reconnect(self) -> bool:
|
||||
"""Scan local /24 subnet on port 5555 and attempt ADB connect to phone."""
|
||||
prefix = self._get_local_subnet_prefix()
|
||||
if prefix is None:
|
||||
_logger.info("Could not determine local subnet for wireless scan")
|
||||
return False
|
||||
|
||||
def probe(i: int) -> bool:
|
||||
ip = f"{prefix}.{i}"
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.create_connection((ip, 5555), timeout=0.5),
|
||||
):
|
||||
if self._try_adb_connect(f"{ip}:5555"):
|
||||
return self._has_adb_device()
|
||||
return False
|
||||
|
||||
_logger.info("Scanning %s.1-254:5555 for phone...", prefix)
|
||||
with ThreadPoolExecutor(max_workers=64) as executor:
|
||||
for future in as_completed(
|
||||
executor.submit(probe, i) for i in range(1, 255)
|
||||
):
|
||||
if future.result():
|
||||
return True
|
||||
return False
|
||||
|
||||
def _is_phone_connected(self) -> bool:
|
||||
"""Check if an Android device is connected via ADB.
|
||||
|
||||
If no device is visible, attempts wireless reconnection via subnet scan.
|
||||
"""
|
||||
if self._has_adb_device():
|
||||
return True
|
||||
_logger.info("No ADB device detected — attempting wireless reconnect...")
|
||||
return self._try_wireless_reconnect()
|
||||
|
||||
# ── ADB verification ──────────────────────────────────────────────────────
|
||||
|
||||
def _pull_workout_app_json(self) -> dict | None:
|
||||
"""Pull workout_result.json from the phone (ADB, no root needed).
|
||||
|
||||
@ -258,67 +143,6 @@ class PhoneVerificationMixin:
|
||||
|
||||
# ── HTTP fallback (no ADB / developer options required) ───────────────────
|
||||
|
||||
def _scan_for_http_server(self) -> str | None:
|
||||
"""Scan local /24 subnet for the workout app HTTP server on port 8765.
|
||||
|
||||
Returns the first reachable URL or None.
|
||||
"""
|
||||
prefix = self._get_local_subnet_prefix()
|
||||
if prefix is None:
|
||||
return None
|
||||
|
||||
def probe(i: int) -> str | None:
|
||||
ip = f"{prefix}.{i}"
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.create_connection((ip, WORKOUT_HTTP_PORT), timeout=0.3),
|
||||
):
|
||||
return f"http://{ip}:{WORKOUT_HTTP_PORT}/workout"
|
||||
return None
|
||||
|
||||
_logger.info(
|
||||
"Scanning %s.1-254:%d for workout app...", prefix, WORKOUT_HTTP_PORT
|
||||
)
|
||||
with ThreadPoolExecutor(max_workers=64) as executor:
|
||||
for future in as_completed(
|
||||
executor.submit(probe, i) for i in range(1, 255)
|
||||
):
|
||||
result = future.result()
|
||||
if result is not None:
|
||||
return result
|
||||
return None
|
||||
|
||||
def _fetch_http_workout(self) -> dict | None:
|
||||
"""Fetch workout JSON from the app's HTTP server on the local network.
|
||||
|
||||
Uses http.client directly to avoid urllib URL-open security lint rules.
|
||||
The URL is always http://<local-ip>:8765/workout — no user input involved.
|
||||
"""
|
||||
url = self._scan_for_http_server()
|
||||
if url is None:
|
||||
return None
|
||||
# url is always "http://<ip>:<port>/workout" — constructed internally.
|
||||
try:
|
||||
_, _, hostport = url.partition("://")
|
||||
host, _, path = hostport.partition("/")
|
||||
hostname, _, port_str = host.partition(":")
|
||||
conn = _HTTPConnection(hostname, int(port_str), timeout=5)
|
||||
conn.request("GET", f"/{path}")
|
||||
resp = conn.getresponse()
|
||||
if resp.status != _HTTP_OK:
|
||||
return None
|
||||
return json.loads(resp.read().decode())
|
||||
except (_HTTPException, OSError, ValueError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"HTTP fetch of today's workout from %s failed (%s) — no data "
|
||||
"from the phone's HTTP server, so verification falls through",
|
||||
url,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
# ── Main verification entry point ─────────────────────────────────────────
|
||||
|
||||
def _verify_phone_workout(self) -> tuple[str, str]:
|
||||
"""Verify today's workout: GitHub sync first, ADB/HTTP as fallback.
|
||||
|
||||
|
||||
90
screen_locker/_runnerup_backfill.py
Normal file
90
screen_locker/_runnerup_backfill.py
Normal file
@ -0,0 +1,90 @@
|
||||
"""Backfilling the workout log from RunnerUp exports already on the phone.
|
||||
|
||||
Split out of :mod:`screen_locker._runnerup_verification` to keep every file
|
||||
under the 250-line cap. Composed back into ``RunnerUpVerificationMixin``
|
||||
there, so callers see no change.
|
||||
|
||||
Used by the weekly scan: a run exported days ago still counts, so the log is
|
||||
filled in from whatever RunnerUp kept rather than only from today's check.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._log_mixin import write_signed_entry
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RunnerUpBackfillMixin:
|
||||
"""Fills the log from RunnerUp exports for a date or a whole week."""
|
||||
|
||||
def _try_fill_runnerup_for_date(self, date_str: str, log_file: Path) -> bool:
|
||||
"""Append a verified RunnerUp entry for ``date_str`` if not already logged.
|
||||
|
||||
Appends via the write chokepoint, which dedups by ``workout_id``
|
||||
(``runnerup_verified:{date}``): re-scanning a day whose run is already
|
||||
recorded is a no-op, but a day that only holds, say, a manual workout
|
||||
still gets the run appended alongside it (multiple workouts per day).
|
||||
|
||||
Returns True if a new verified entry was appended for ``date_str``.
|
||||
"""
|
||||
for remote in self._find_runnerup_exports_for_date(date_str):
|
||||
data = self._pull_and_parse_tcx(remote)
|
||||
if data is None:
|
||||
continue
|
||||
status, msg = self._validate_runnerup_data(data)
|
||||
if status != "verified":
|
||||
_logger.warning(
|
||||
"RunnerUp export %s for %s did not qualify (%s): %s",
|
||||
remote,
|
||||
date_str,
|
||||
status,
|
||||
msg,
|
||||
)
|
||||
continue
|
||||
workout_data = {
|
||||
"type": "runnerup_verified",
|
||||
"source": f"Auto-scanned: {msg}",
|
||||
"distance_km": round(data["distance_m"] / 1000, 2),
|
||||
"duration_minutes": round(data["duration_seconds"] / 60, 1),
|
||||
}
|
||||
if write_signed_entry(log_file, date_str, workout_data).appended:
|
||||
_logger.info("Auto-filled RunnerUp entry for %s: %s", date_str, msg)
|
||||
return True
|
||||
return False
|
||||
return False
|
||||
|
||||
def _scan_and_fill_week_runnerup(self, log_file: Path) -> int:
|
||||
"""Scan the current ISO week for RunnerUp runs and append any not logged.
|
||||
|
||||
Returns the count of newly appended entries (0 if phone not connected).
|
||||
"""
|
||||
if not self._has_adb_device():
|
||||
_logger.info(
|
||||
"Phone not connected; skipping auto-scan for past RunnerUp exports."
|
||||
)
|
||||
return 0
|
||||
|
||||
now = datetime.now(tz=timezone.utc).astimezone()
|
||||
today = now.date()
|
||||
week_start = today - timedelta(days=today.weekday())
|
||||
|
||||
filled = 0
|
||||
current = week_start
|
||||
while current <= today:
|
||||
if self._try_fill_runnerup_for_date(current.strftime("%Y-%m-%d"), log_file):
|
||||
filled += 1
|
||||
current += timedelta(days=1)
|
||||
|
||||
return filled
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Shared validation
|
||||
# ------------------------------------------------------------------
|
||||
96
screen_locker/_runnerup_tcx.py
Normal file
96
screen_locker/_runnerup_tcx.py
Normal file
@ -0,0 +1,96 @@
|
||||
"""Pulling a RunnerUp TCX export off the phone and parsing it.
|
||||
|
||||
Split out of :mod:`screen_locker._runnerup_verification` to keep every file
|
||||
under the 250-line cap. Composed back into ``RunnerUpVerificationMixin``
|
||||
there, so callers see no change.
|
||||
|
||||
TCX is the no-root path: RunnerUp writes these exports to shared storage, so
|
||||
they can be read without touching the app's private database.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
from typing import Any
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
# TCX XML namespace used by Garmin/RunnerUp.
|
||||
_TCX_NS = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"
|
||||
|
||||
_SPORT_NAMES: dict[int, str] = {
|
||||
0: "Running",
|
||||
1: "Cycling",
|
||||
2: "Other",
|
||||
3: "Orienteering",
|
||||
4: "Walking",
|
||||
5: "Skiing",
|
||||
6: "Swimming",
|
||||
7: "Stationary Bike",
|
||||
}
|
||||
|
||||
# TCX uses sport name strings; map back to integer codes for unified validation.
|
||||
_TCX_SPORT_TO_INT: dict[str, int] = {v: k for k, v in _SPORT_NAMES.items()}
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RunnerUpTcxMixin:
|
||||
"""Pulls and parses RunnerUp's TCX exports over adb."""
|
||||
|
||||
def _pull_and_parse_tcx(self, remote_path: str) -> dict[str, Any] | None:
|
||||
"""Pull a remote TCX file and parse it. Returns activity dict or None."""
|
||||
tmp_dir = tempfile.mkdtemp(prefix="runnerup_tcx_")
|
||||
local_path = str(Path(tmp_dir) / "activity.tcx")
|
||||
try:
|
||||
ok, _ = self._run_adb(["pull", remote_path, local_path])
|
||||
if not ok or not Path(local_path).exists():
|
||||
_logger.info("Failed to pull TCX file: %s", remote_path)
|
||||
return None
|
||||
return self._parse_tcx(local_path)
|
||||
finally:
|
||||
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||
|
||||
def _parse_tcx(self, tcx_path: str) -> dict[str, Any] | None:
|
||||
"""Parse a local TCX file and return activity summary dict.
|
||||
|
||||
Sums ``TotalTimeSeconds`` and ``DistanceMeters`` across all Laps so
|
||||
multi-segment runs (pause/resume) are counted in full.
|
||||
"""
|
||||
try:
|
||||
tree = ET.parse(tcx_path)
|
||||
except ET.ParseError as exc:
|
||||
_logger.warning(
|
||||
"TCX file %s is not valid XML (%s) — the run it describes CANNOT "
|
||||
"be verified and will not count",
|
||||
tcx_path,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
root = tree.getroot()
|
||||
activity = root.find(f".//{{{_TCX_NS}}}Activity")
|
||||
if activity is None:
|
||||
_logger.info("No Activity element in TCX file")
|
||||
return None
|
||||
|
||||
sport_str = activity.get("Sport", "")
|
||||
sport_int = _TCX_SPORT_TO_INT.get(sport_str, -1)
|
||||
|
||||
total_seconds = 0.0
|
||||
total_distance = 0.0
|
||||
for lap in activity.findall(f"{{{_TCX_NS}}}Lap"):
|
||||
t_elem = lap.find(f"{{{_TCX_NS}}}TotalTimeSeconds")
|
||||
d_elem = lap.find(f"{{{_TCX_NS}}}DistanceMeters")
|
||||
if t_elem is not None and t_elem.text:
|
||||
total_seconds += float(t_elem.text)
|
||||
if d_elem is not None and d_elem.text:
|
||||
total_distance += float(d_elem.text)
|
||||
|
||||
return {
|
||||
"sport": sport_int,
|
||||
"duration_seconds": int(total_seconds),
|
||||
"distance_m": total_distance,
|
||||
}
|
||||
@ -7,13 +7,9 @@ Root DB fallback lives in ``_runnerup_db.py``.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timezone
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
from typing import Any
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from screen_locker._constants import (
|
||||
MIN_RUN_DISTANCE_KM,
|
||||
@ -23,8 +19,9 @@ from screen_locker._constants import (
|
||||
RUNNERUP_EXPORT_DIRS,
|
||||
WORKOUT_DURATION_ACCEPT_MINUTES,
|
||||
)
|
||||
from screen_locker._log_mixin import write_signed_entry
|
||||
from screen_locker._runnerup_backfill import RunnerUpBackfillMixin
|
||||
from screen_locker._runnerup_db import RunnerUpDbMixin
|
||||
from screen_locker._runnerup_tcx import RunnerUpTcxMixin
|
||||
from screen_locker._time_check import check_clock_skew
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
@ -41,13 +38,13 @@ _SPORT_NAMES: dict[int, str] = {
|
||||
}
|
||||
|
||||
# TCX uses sport name strings; map back to integer codes for unified validation.
|
||||
_TCX_SPORT_TO_INT: dict[str, int] = {v: k for k, v in _SPORT_NAMES.items()}
|
||||
|
||||
# TCX XML namespace used by Garmin/RunnerUp.
|
||||
_TCX_NS = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"
|
||||
|
||||
|
||||
class RunnerUpVerificationMixin(RunnerUpDbMixin):
|
||||
class RunnerUpVerificationMixin(
|
||||
RunnerUpDbMixin,
|
||||
RunnerUpTcxMixin,
|
||||
RunnerUpBackfillMixin,
|
||||
):
|
||||
"""Mixin providing RunnerUp-based workout verification via ADB."""
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@ -74,61 +71,6 @@ class RunnerUpVerificationMixin(RunnerUpDbMixin):
|
||||
found.append(remote)
|
||||
return found
|
||||
|
||||
def _pull_and_parse_tcx(self, remote_path: str) -> dict[str, Any] | None:
|
||||
"""Pull a remote TCX file and parse it. Returns activity dict or None."""
|
||||
tmp_dir = tempfile.mkdtemp(prefix="runnerup_tcx_")
|
||||
local_path = str(Path(tmp_dir) / "activity.tcx")
|
||||
try:
|
||||
ok, _ = self._run_adb(["pull", remote_path, local_path])
|
||||
if not ok or not Path(local_path).exists():
|
||||
_logger.info("Failed to pull TCX file: %s", remote_path)
|
||||
return None
|
||||
return self._parse_tcx(local_path)
|
||||
finally:
|
||||
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||
|
||||
def _parse_tcx(self, tcx_path: str) -> dict[str, Any] | None:
|
||||
"""Parse a local TCX file and return activity summary dict.
|
||||
|
||||
Sums ``TotalTimeSeconds`` and ``DistanceMeters`` across all Laps so
|
||||
multi-segment runs (pause/resume) are counted in full.
|
||||
"""
|
||||
try:
|
||||
tree = ET.parse(tcx_path)
|
||||
except ET.ParseError as exc:
|
||||
_logger.warning(
|
||||
"TCX file %s is not valid XML (%s) — the run it describes CANNOT "
|
||||
"be verified and will not count",
|
||||
tcx_path,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
root = tree.getroot()
|
||||
activity = root.find(f".//{{{_TCX_NS}}}Activity")
|
||||
if activity is None:
|
||||
_logger.info("No Activity element in TCX file")
|
||||
return None
|
||||
|
||||
sport_str = activity.get("Sport", "")
|
||||
sport_int = _TCX_SPORT_TO_INT.get(sport_str, -1)
|
||||
|
||||
total_seconds = 0.0
|
||||
total_distance = 0.0
|
||||
for lap in activity.findall(f"{{{_TCX_NS}}}Lap"):
|
||||
t_elem = lap.find(f"{{{_TCX_NS}}}TotalTimeSeconds")
|
||||
d_elem = lap.find(f"{{{_TCX_NS}}}DistanceMeters")
|
||||
if t_elem is not None and t_elem.text:
|
||||
total_seconds += float(t_elem.text)
|
||||
if d_elem is not None and d_elem.text:
|
||||
total_distance += float(d_elem.text)
|
||||
|
||||
return {
|
||||
"sport": sport_int,
|
||||
"duration_seconds": int(total_seconds),
|
||||
"distance_m": total_distance,
|
||||
}
|
||||
|
||||
def _verify_runnerup_via_files(self) -> tuple[str, str] | None:
|
||||
"""Try to verify today's run via TCX export files.
|
||||
|
||||
@ -167,70 +109,6 @@ class RunnerUpVerificationMixin(RunnerUpDbMixin):
|
||||
"RunnerUp TCX export found but could not be read",
|
||||
)
|
||||
|
||||
def _try_fill_runnerup_for_date(self, date_str: str, log_file: Path) -> bool:
|
||||
"""Append a verified RunnerUp entry for ``date_str`` if not already logged.
|
||||
|
||||
Appends via the write chokepoint, which dedups by ``workout_id``
|
||||
(``runnerup_verified:{date}``): re-scanning a day whose run is already
|
||||
recorded is a no-op, but a day that only holds, say, a manual workout
|
||||
still gets the run appended alongside it (multiple workouts per day).
|
||||
|
||||
Returns True if a new verified entry was appended for ``date_str``.
|
||||
"""
|
||||
for remote in self._find_runnerup_exports_for_date(date_str):
|
||||
data = self._pull_and_parse_tcx(remote)
|
||||
if data is None:
|
||||
continue
|
||||
status, msg = self._validate_runnerup_data(data)
|
||||
if status != "verified":
|
||||
_logger.warning(
|
||||
"RunnerUp export %s for %s did not qualify (%s): %s",
|
||||
remote,
|
||||
date_str,
|
||||
status,
|
||||
msg,
|
||||
)
|
||||
continue
|
||||
workout_data = {
|
||||
"type": "runnerup_verified",
|
||||
"source": f"Auto-scanned: {msg}",
|
||||
"distance_km": round(data["distance_m"] / 1000, 2),
|
||||
"duration_minutes": round(data["duration_seconds"] / 60, 1),
|
||||
}
|
||||
if write_signed_entry(log_file, date_str, workout_data).appended:
|
||||
_logger.info("Auto-filled RunnerUp entry for %s: %s", date_str, msg)
|
||||
return True
|
||||
return False
|
||||
return False
|
||||
|
||||
def _scan_and_fill_week_runnerup(self, log_file: Path) -> int:
|
||||
"""Scan the current ISO week for RunnerUp runs and append any not logged.
|
||||
|
||||
Returns the count of newly appended entries (0 if phone not connected).
|
||||
"""
|
||||
if not self._has_adb_device():
|
||||
_logger.info(
|
||||
"Phone not connected; skipping auto-scan for past RunnerUp exports."
|
||||
)
|
||||
return 0
|
||||
|
||||
now = datetime.now(tz=timezone.utc).astimezone()
|
||||
today = now.date()
|
||||
week_start = today - timedelta(days=today.weekday())
|
||||
|
||||
filled = 0
|
||||
current = week_start
|
||||
while current <= today:
|
||||
if self._try_fill_runnerup_for_date(current.strftime("%Y-%m-%d"), log_file):
|
||||
filled += 1
|
||||
current += timedelta(days=1)
|
||||
|
||||
return filled
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Shared validation
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _validate_runnerup_data(self, data: dict[str, Any]) -> tuple[str, str]:
|
||||
"""Validate a RunnerUp activity against configured thresholds.
|
||||
|
||||
|
||||
@ -2,21 +2,17 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
import logging
|
||||
import subprocess
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._constants import (
|
||||
ADJUST_SHUTDOWN_SCRIPT,
|
||||
ALARM_DAYS,
|
||||
RTCWAKE_BIN,
|
||||
SHUTDOWN_CONFIG_FILE,
|
||||
SICK_DAY_STATE_FILE,
|
||||
WAKE_AFTER_HOURS,
|
||||
)
|
||||
from screen_locker._shutdown_sick_state import SickDayStateMixin
|
||||
from screen_locker._wake_alarm import WakeAlarmMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
@ -52,7 +48,7 @@ def read_shutdown_config(path: Path) -> tuple[int, int, int] | None:
|
||||
)
|
||||
|
||||
|
||||
class ShutdownMixin:
|
||||
class ShutdownMixin(SickDayStateMixin, WakeAlarmMixin):
|
||||
"""Mixin providing shutdown schedule adjustment functionality."""
|
||||
|
||||
def _apply_earlier_shutdown(self, today: str) -> bool:
|
||||
@ -139,102 +135,6 @@ class ShutdownMixin:
|
||||
)
|
||||
return False
|
||||
|
||||
def _sick_mode_used_today(self) -> bool:
|
||||
"""Check if sick mode was already used today."""
|
||||
if not SICK_DAY_STATE_FILE.exists():
|
||||
return False
|
||||
|
||||
try:
|
||||
with SICK_DAY_STATE_FILE.open() as f:
|
||||
state = json.load(f)
|
||||
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
return state.get("date") == today
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not read sick-day state from %s: %s — treating sick mode "
|
||||
"as UNUSED today, which may allow a second sick day",
|
||||
SICK_DAY_STATE_FILE,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
|
||||
def _save_sick_day_state(
|
||||
self,
|
||||
date: str,
|
||||
orig_mon_wed: int,
|
||||
orig_thu_sun: int,
|
||||
) -> bool:
|
||||
"""Save sick day state with original config values.
|
||||
|
||||
Returns True if saved successfully, False otherwise.
|
||||
"""
|
||||
state = {
|
||||
"date": date,
|
||||
"original_mon_wed_hour": orig_mon_wed,
|
||||
"original_thu_sun_hour": orig_thu_sun,
|
||||
}
|
||||
try:
|
||||
with SICK_DAY_STATE_FILE.open("w") as f:
|
||||
json.dump(state, f, indent=2)
|
||||
except OSError as e:
|
||||
_logger.warning("Failed to save sick day state: %s", e)
|
||||
return False
|
||||
|
||||
_logger.info("Saved sick day state for %s", date)
|
||||
return True
|
||||
|
||||
def _load_sick_day_state(self) -> tuple[str, int, int] | None:
|
||||
"""Load sick day state file.
|
||||
|
||||
Returns (date, orig_mon_wed_hour, orig_thu_sun_hour) or None.
|
||||
"""
|
||||
with SICK_DAY_STATE_FILE.open() as f:
|
||||
state = json.load(f)
|
||||
date = state.get("date")
|
||||
orig_mw = state.get("original_mon_wed_hour")
|
||||
orig_ts = state.get("original_thu_sun_hour")
|
||||
if date is None or orig_mw is None or orig_ts is None:
|
||||
return None
|
||||
return (str(date), int(orig_mw), int(orig_ts))
|
||||
|
||||
def _write_restored_config(
|
||||
self,
|
||||
orig_mw: int,
|
||||
orig_ts: int,
|
||||
state_date: str,
|
||||
) -> None:
|
||||
"""Write restored config values and clean up state file."""
|
||||
config_values = self._read_shutdown_config()
|
||||
if config_values:
|
||||
_, _, morning_end = config_values
|
||||
_logger.info(
|
||||
"Restoring original shutdown config from %s",
|
||||
state_date,
|
||||
)
|
||||
self._write_shutdown_config(
|
||||
orig_mw,
|
||||
orig_ts,
|
||||
morning_end,
|
||||
restore=True,
|
||||
)
|
||||
SICK_DAY_STATE_FILE.unlink()
|
||||
_logger.info("Removed stale sick day state from %s", state_date)
|
||||
|
||||
def _restore_original_config_if_needed(self) -> None:
|
||||
"""Restore original config if sick day state is from a previous day."""
|
||||
if not SICK_DAY_STATE_FILE.exists():
|
||||
return
|
||||
try:
|
||||
loaded = self._load_sick_day_state()
|
||||
if loaded is None:
|
||||
return
|
||||
state_date, orig_mw, orig_ts = loaded
|
||||
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
if state_date != today:
|
||||
self._write_restored_config(orig_mw, orig_ts, state_date)
|
||||
except (OSError, json.JSONDecodeError) as e:
|
||||
_logger.warning("Error checking sick day state: %s", e)
|
||||
|
||||
def _read_shutdown_config(self) -> tuple[int, int, int] | None:
|
||||
"""Read shutdown config. Returns (mw_hour, ts_hour, me_hour) or None."""
|
||||
return read_shutdown_config(SHUTDOWN_CONFIG_FILE)
|
||||
@ -310,75 +210,3 @@ class ShutdownMixin:
|
||||
result.stdout.strip(),
|
||||
)
|
||||
return True
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# rtcwake integration for weekend wake alarm
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _is_tomorrow_alarm_day() -> bool:
|
||||
"""Check if tomorrow is an alarm day."""
|
||||
tomorrow = datetime.now(tz=timezone.utc) + timedelta(days=1)
|
||||
return tomorrow.weekday() in ALARM_DAYS
|
||||
|
||||
@staticmethod
|
||||
def _compute_wake_timestamp() -> int:
|
||||
"""Compute the UTC epoch timestamp for the next wake alarm.
|
||||
|
||||
Returns:
|
||||
Epoch seconds WAKE_AFTER_HOURS from now.
|
||||
"""
|
||||
wake_time = datetime.now(tz=timezone.utc) + timedelta(
|
||||
hours=WAKE_AFTER_HOURS,
|
||||
)
|
||||
return calendar.timegm(wake_time.utctimetuple())
|
||||
|
||||
@staticmethod
|
||||
def _schedule_rtcwake() -> bool:
|
||||
"""Set rtcwake to power on the PC after WAKE_AFTER_HOURS.
|
||||
|
||||
Uses ``rtcwake -m disk`` to hibernate immediately while programming
|
||||
the RTC to restore power at wake_epoch. Hibernate is completely
|
||||
silent and dark (state written to swap file), making it suitable
|
||||
when the PC is in a bedroom.
|
||||
|
||||
Returns:
|
||||
True if rtcwake was set successfully, False otherwise.
|
||||
"""
|
||||
wake_epoch = ShutdownMixin._compute_wake_timestamp()
|
||||
cmd = [
|
||||
"/usr/bin/sudo",
|
||||
RTCWAKE_BIN,
|
||||
"-m",
|
||||
"disk",
|
||||
"-t",
|
||||
str(wake_epoch),
|
||||
]
|
||||
try:
|
||||
subprocess.run(
|
||||
cmd,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
except subprocess.SubprocessError as exc:
|
||||
_logger.warning("Failed to set rtcwake: %s", exc)
|
||||
return False
|
||||
_logger.info(
|
||||
"rtcwake set: PC will wake at epoch %d",
|
||||
wake_epoch,
|
||||
)
|
||||
return True
|
||||
|
||||
def schedule_wake_if_needed(self) -> bool:
|
||||
"""Schedule rtcwake if tomorrow is an alarm day.
|
||||
|
||||
Call this at shutdown time.
|
||||
|
||||
Returns:
|
||||
True if wake was scheduled, False if not needed or failed.
|
||||
"""
|
||||
if not self._is_tomorrow_alarm_day():
|
||||
_logger.info("Tomorrow is not an alarm day — skipping rtcwake")
|
||||
return False
|
||||
return self._schedule_rtcwake()
|
||||
|
||||
119
screen_locker/_shutdown_sick_state.py
Normal file
119
screen_locker/_shutdown_sick_state.py
Normal file
@ -0,0 +1,119 @@
|
||||
"""Sick-day shutdown state: persistence and next-day restoration.
|
||||
|
||||
Split out of :mod:`screen_locker._shutdown` to keep every file under the
|
||||
250-line cap. Composed back into ``ShutdownMixin`` there, so callers see no
|
||||
change.
|
||||
|
||||
Tracks the shutdown hours that were in force before a sick day moved them
|
||||
earlier, so the following day can put them back.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
|
||||
from screen_locker._constants import SICK_DAY_STATE_FILE
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SickDayStateMixin:
|
||||
"""Persists and restores the pre-sick-day shutdown configuration."""
|
||||
|
||||
def _sick_mode_used_today(self) -> bool:
|
||||
"""Check if sick mode was already used today."""
|
||||
if not SICK_DAY_STATE_FILE.exists():
|
||||
return False
|
||||
|
||||
try:
|
||||
with SICK_DAY_STATE_FILE.open() as f:
|
||||
state = json.load(f)
|
||||
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
return state.get("date") == today
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not read sick-day state from %s: %s — treating sick mode "
|
||||
"as UNUSED today, which may allow a second sick day",
|
||||
SICK_DAY_STATE_FILE,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
|
||||
def _save_sick_day_state(
|
||||
self,
|
||||
date: str,
|
||||
orig_mon_wed: int,
|
||||
orig_thu_sun: int,
|
||||
) -> bool:
|
||||
"""Save sick day state with original config values.
|
||||
|
||||
Returns True if saved successfully, False otherwise.
|
||||
"""
|
||||
state = {
|
||||
"date": date,
|
||||
"original_mon_wed_hour": orig_mon_wed,
|
||||
"original_thu_sun_hour": orig_thu_sun,
|
||||
}
|
||||
try:
|
||||
with SICK_DAY_STATE_FILE.open("w") as f:
|
||||
json.dump(state, f, indent=2)
|
||||
except OSError as e:
|
||||
_logger.warning("Failed to save sick day state: %s", e)
|
||||
return False
|
||||
|
||||
_logger.info("Saved sick day state for %s", date)
|
||||
return True
|
||||
|
||||
def _load_sick_day_state(self) -> tuple[str, int, int] | None:
|
||||
"""Load sick day state file.
|
||||
|
||||
Returns (date, orig_mon_wed_hour, orig_thu_sun_hour) or None.
|
||||
"""
|
||||
with SICK_DAY_STATE_FILE.open() as f:
|
||||
state = json.load(f)
|
||||
date = state.get("date")
|
||||
orig_mw = state.get("original_mon_wed_hour")
|
||||
orig_ts = state.get("original_thu_sun_hour")
|
||||
if date is None or orig_mw is None or orig_ts is None:
|
||||
return None
|
||||
return (str(date), int(orig_mw), int(orig_ts))
|
||||
|
||||
def _write_restored_config(
|
||||
self,
|
||||
orig_mw: int,
|
||||
orig_ts: int,
|
||||
state_date: str,
|
||||
) -> None:
|
||||
"""Write restored config values and clean up state file."""
|
||||
config_values = self._read_shutdown_config()
|
||||
if config_values:
|
||||
_, _, morning_end = config_values
|
||||
_logger.info(
|
||||
"Restoring original shutdown config from %s",
|
||||
state_date,
|
||||
)
|
||||
self._write_shutdown_config(
|
||||
orig_mw,
|
||||
orig_ts,
|
||||
morning_end,
|
||||
restore=True,
|
||||
)
|
||||
SICK_DAY_STATE_FILE.unlink()
|
||||
_logger.info("Removed stale sick day state from %s", state_date)
|
||||
|
||||
def _restore_original_config_if_needed(self) -> None:
|
||||
"""Restore original config if sick day state is from a previous day."""
|
||||
if not SICK_DAY_STATE_FILE.exists():
|
||||
return
|
||||
try:
|
||||
loaded = self._load_sick_day_state()
|
||||
if loaded is None:
|
||||
return
|
||||
state_date, orig_mw, orig_ts = loaded
|
||||
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
if state_date != today:
|
||||
self._write_restored_config(orig_mw, orig_ts, state_date)
|
||||
except (OSError, json.JSONDecodeError) as e:
|
||||
_logger.warning("Error checking sick day state: %s", e)
|
||||
125
screen_locker/_sick_budget.py
Normal file
125
screen_locker/_sick_budget.py
Normal file
@ -0,0 +1,125 @@
|
||||
"""The sick-day record and the rolling budget computed from it.
|
||||
|
||||
Split out of :mod:`screen_locker._sick_tracker` to keep every file under the
|
||||
250-line cap. Re-exported from there, so callers and their patch targets are
|
||||
unchanged.
|
||||
|
||||
Everything here is pure: it reads a :class:`SickHistory` already in memory.
|
||||
Loading and saving that history stays in ``_sick_tracker``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from screen_locker._constants import (
|
||||
SICK_BUDGET_PER_7_DAYS,
|
||||
SICK_BUDGET_PER_30_DAYS,
|
||||
SICK_BUDGET_PER_90_DAYS,
|
||||
SICK_LOCKOUT_MULTIPLIER_PER_RECENT,
|
||||
SICK_LOCKOUT_SECONDS,
|
||||
)
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SickHistory:
|
||||
"""Persistent sick-day bookkeeping."""
|
||||
|
||||
sick_days: list[str] = field(default_factory=list)
|
||||
debt: int = 0
|
||||
commitments: dict[str, bool] = field(default_factory=dict)
|
||||
broken_commitments: list[str] = field(default_factory=list)
|
||||
justifications: list[dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
def _today_iso() -> str:
|
||||
"""Return today's date as ``YYYY-MM-DD`` (UTC)."""
|
||||
return datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _parse_iso(date_str: str) -> datetime | None:
|
||||
"""Parse ``YYYY-MM-DD`` into a UTC datetime, or return None."""
|
||||
try:
|
||||
return datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"Sick history holds an unparsable date %r (%s) — that entry is "
|
||||
"IGNORED when counting sick days",
|
||||
date_str,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def is_sick_day(history: SickHistory, *, today: str | None = None) -> bool:
|
||||
"""Return True if today is recorded as a sick day."""
|
||||
today_str = today or _today_iso()
|
||||
return today_str in history.sick_days
|
||||
|
||||
|
||||
def count_in_window(
|
||||
history: SickHistory,
|
||||
days: int,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> int:
|
||||
"""Return how many ``sick_days`` fall in the trailing ``days`` window."""
|
||||
today_str = today or _today_iso()
|
||||
today_dt = _parse_iso(today_str)
|
||||
if today_dt is None:
|
||||
return 0
|
||||
cutoff = today_dt - timedelta(days=days)
|
||||
count = 0
|
||||
for entry in history.sick_days:
|
||||
parsed = _parse_iso(entry)
|
||||
if parsed is None:
|
||||
continue
|
||||
if cutoff < parsed <= today_dt:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def is_budget_exhausted(
|
||||
history: SickHistory,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> bool:
|
||||
"""Return True if any rolling window has reached its sick budget."""
|
||||
return (
|
||||
count_in_window(history, 7, today=today) >= SICK_BUDGET_PER_7_DAYS
|
||||
or count_in_window(history, 30, today=today) >= SICK_BUDGET_PER_30_DAYS
|
||||
or count_in_window(history, 90, today=today) >= SICK_BUDGET_PER_90_DAYS
|
||||
)
|
||||
|
||||
|
||||
def compute_lockout_seconds(
|
||||
history: SickHistory,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> int:
|
||||
"""Escalating sick countdown: ``base * 2 ** recent_count_in_30d``."""
|
||||
recent = count_in_window(history, 30, today=today)
|
||||
multiplier = SICK_LOCKOUT_MULTIPLIER_PER_RECENT**recent
|
||||
return SICK_LOCKOUT_SECONDS * multiplier
|
||||
|
||||
|
||||
def budget_summary(
|
||||
history: SickHistory,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> str:
|
||||
"""One-line UI summary string for budget + debt."""
|
||||
week = count_in_window(history, 7, today=today)
|
||||
month = count_in_window(history, 30, today=today)
|
||||
quarter = count_in_window(history, 90, today=today)
|
||||
return (
|
||||
f"Sick: {week}/{SICK_BUDGET_PER_7_DAYS}w · "
|
||||
f"{month}/{SICK_BUDGET_PER_30_DAYS}m · "
|
||||
f"{quarter}/{SICK_BUDGET_PER_90_DAYS}q · "
|
||||
f"Debt: {history.debt}"
|
||||
)
|
||||
90
screen_locker/_sick_commitment.py
Normal file
90
screen_locker/_sick_commitment.py
Normal file
@ -0,0 +1,90 @@
|
||||
"""The next-day commitment prompt shown after a sick day.
|
||||
|
||||
Split out of :mod:`screen_locker._sick_dialog` to keep every file under the
|
||||
250-line cap. Composed back into ``SickDialogMixin`` there, so callers see no
|
||||
change.
|
||||
|
||||
Taking a sick day asks for a commitment to train tomorrow; breaking it is
|
||||
recorded and costs budget, which is what stops sick days being free.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker import _sick_tracker
|
||||
from screen_locker._constants import COMMITMENT_PROMPT_TIMEOUT_SECONDS
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
|
||||
class SickCommitmentMixin:
|
||||
"""Asks for, times out, and records the next-day training commitment."""
|
||||
|
||||
def _show_commitment_prompt(self, *, on_done: Callable[[], None]) -> None:
|
||||
"""Ask the user to commit to working out tomorrow.
|
||||
|
||||
Calls ``on_done()`` once the user answers or the timeout elapses.
|
||||
"""
|
||||
self.clear_container()
|
||||
self._label(
|
||||
"Commit to working out tomorrow?",
|
||||
role="display",
|
||||
color=self._colors.warning,
|
||||
pad="md",
|
||||
)
|
||||
# ~80 chars at font_size 16 would render as one unbroken line past the
|
||||
# ~70-char readable range (rule 21) -- wrap it explicitly.
|
||||
prompt = self._text(
|
||||
"If you say YES and skip via 'I'm sick' tomorrow, "
|
||||
"the sick day costs 2x normal.",
|
||||
role="body",
|
||||
)
|
||||
prompt.config(wraplength=560, justify="center")
|
||||
self._commitment_done_fn = on_done
|
||||
self._commitment_remaining = COMMITMENT_PROMPT_TIMEOUT_SECONDS
|
||||
self._commitment_timer_label = self._text(
|
||||
f"Auto-skipping in {COMMITMENT_PROMPT_TIMEOUT_SECONDS}s",
|
||||
color=self._colors.muted,
|
||||
)
|
||||
row = self._button_row()
|
||||
self._button(
|
||||
row,
|
||||
"YES",
|
||||
bg=self._colors.success,
|
||||
command=lambda: self._answer_commitment(commit=True),
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
self._button(
|
||||
row,
|
||||
"NO",
|
||||
bg=self._colors.field_bg,
|
||||
command=lambda: self._answer_commitment(commit=False),
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
self._tick_commitment_timeout()
|
||||
|
||||
def _tick_commitment_timeout(self) -> None:
|
||||
"""Advance commitment auto-skip timer; default to NO when it expires."""
|
||||
if self._commitment_remaining <= 0:
|
||||
self._answer_commitment(commit=False)
|
||||
return
|
||||
self._commitment_timer_label.config(
|
||||
text=f"Auto-skipping in {self._commitment_remaining}s",
|
||||
)
|
||||
self._commitment_remaining -= 1
|
||||
self.root.after(1000, self._tick_commitment_timeout)
|
||||
|
||||
def _answer_commitment(self, *, commit: bool) -> None:
|
||||
"""Persist the commitment answer and call the completion callback."""
|
||||
# Disable timer re-entry by zeroing remaining.
|
||||
self._commitment_remaining = -1
|
||||
if commit:
|
||||
history = _sick_tracker.load_history()
|
||||
_sick_tracker.record_commitment_for_tomorrow(history)
|
||||
_sick_tracker.save_history(history)
|
||||
done = getattr(self, "_commitment_done_fn", None)
|
||||
if done is not None:
|
||||
self._commitment_done_fn = None
|
||||
done()
|
||||
@ -10,22 +10,20 @@ from gatelock import escape_text_tab_trap
|
||||
|
||||
from screen_locker import _sick_tracker
|
||||
from screen_locker._constants import (
|
||||
COMMITMENT_PROMPT_TIMEOUT_SECONDS,
|
||||
SICK_COMMITMENT_FORCED_READ_SECONDS,
|
||||
SICK_JUSTIFICATION_MIN_CHARS,
|
||||
)
|
||||
from screen_locker._sick_commitment import SickCommitmentMixin
|
||||
from screen_locker._surface_group import FrameGroup, TextGroup
|
||||
from screen_locker._ui_widgets import disable_paste as _disable_paste
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from screen_locker._sick_tracker import SickHistory
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SickDialogMixin:
|
||||
class SickDialogMixin(SickCommitmentMixin):
|
||||
"""Renders the sick-day justification screen and commitment prompts."""
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@ -209,70 +207,3 @@ class SickDialogMixin:
|
||||
# ------------------------------------------------------------------
|
||||
# Commitment prompt (after a verified workout)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _show_commitment_prompt(self, *, on_done: Callable[[], None]) -> None:
|
||||
"""Ask the user to commit to working out tomorrow.
|
||||
|
||||
Calls ``on_done()`` once the user answers or the timeout elapses.
|
||||
"""
|
||||
self.clear_container()
|
||||
self._label(
|
||||
"Commit to working out tomorrow?",
|
||||
role="display",
|
||||
color=self._colors.warning,
|
||||
pad="md",
|
||||
)
|
||||
# ~80 chars at font_size 16 would render as one unbroken line past the
|
||||
# ~70-char readable range (rule 21) -- wrap it explicitly.
|
||||
prompt = self._text(
|
||||
"If you say YES and skip via 'I'm sick' tomorrow, "
|
||||
"the sick day costs 2x normal.",
|
||||
role="body",
|
||||
)
|
||||
prompt.config(wraplength=560, justify="center")
|
||||
self._commitment_done_fn = on_done
|
||||
self._commitment_remaining = COMMITMENT_PROMPT_TIMEOUT_SECONDS
|
||||
self._commitment_timer_label = self._text(
|
||||
f"Auto-skipping in {COMMITMENT_PROMPT_TIMEOUT_SECONDS}s",
|
||||
color=self._colors.muted,
|
||||
)
|
||||
row = self._button_row()
|
||||
self._button(
|
||||
row,
|
||||
"YES",
|
||||
bg=self._colors.success,
|
||||
command=lambda: self._answer_commitment(commit=True),
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
self._button(
|
||||
row,
|
||||
"NO",
|
||||
bg=self._colors.field_bg,
|
||||
command=lambda: self._answer_commitment(commit=False),
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
self._tick_commitment_timeout()
|
||||
|
||||
def _tick_commitment_timeout(self) -> None:
|
||||
"""Advance commitment auto-skip timer; default to NO when it expires."""
|
||||
if self._commitment_remaining <= 0:
|
||||
self._answer_commitment(commit=False)
|
||||
return
|
||||
self._commitment_timer_label.config(
|
||||
text=f"Auto-skipping in {self._commitment_remaining}s",
|
||||
)
|
||||
self._commitment_remaining -= 1
|
||||
self.root.after(1000, self._tick_commitment_timeout)
|
||||
|
||||
def _answer_commitment(self, *, commit: bool) -> None:
|
||||
"""Persist the commitment answer and call the completion callback."""
|
||||
# Disable timer re-entry by zeroing remaining.
|
||||
self._commitment_remaining = -1
|
||||
if commit:
|
||||
history = _sick_tracker.load_history()
|
||||
_sick_tracker.record_commitment_for_tomorrow(history)
|
||||
_sick_tracker.save_history(history)
|
||||
done = getattr(self, "_commitment_done_fn", None)
|
||||
if done is not None:
|
||||
self._commitment_done_fn = None
|
||||
done()
|
||||
|
||||
@ -6,7 +6,7 @@ state via :func:`save_history`.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import logging
|
||||
@ -15,50 +15,41 @@ from typing import Any
|
||||
from gatelock.log_integrity import compute_entry_hmac
|
||||
|
||||
from screen_locker._constants import (
|
||||
SICK_BUDGET_PER_7_DAYS,
|
||||
SICK_BUDGET_PER_30_DAYS,
|
||||
SICK_BUDGET_PER_90_DAYS,
|
||||
SICK_COMMITMENT_PENALTY_DAYS,
|
||||
SICK_HISTORY_FILE,
|
||||
SICK_HISTORY_REVIEW_COUNT,
|
||||
SICK_JUSTIFICATION_MIN_CHARS,
|
||||
SICK_LOCKOUT_MULTIPLIER_PER_RECENT,
|
||||
SICK_LOCKOUT_SECONDS,
|
||||
)
|
||||
from screen_locker._sick_budget import (
|
||||
SickHistory,
|
||||
_parse_iso,
|
||||
_today_iso,
|
||||
budget_summary,
|
||||
compute_lockout_seconds,
|
||||
count_in_window,
|
||||
is_budget_exhausted,
|
||||
is_sick_day,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"SickHistory",
|
||||
"add_sick_day",
|
||||
"budget_summary",
|
||||
"clear_one_debt",
|
||||
"compute_lockout_seconds",
|
||||
"count_in_window",
|
||||
"had_commitment_for_today",
|
||||
"is_budget_exhausted",
|
||||
"is_sick_day",
|
||||
"load_history",
|
||||
"mark_commitment_broken",
|
||||
"record_commitment_for_tomorrow",
|
||||
"save_history",
|
||||
]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SickHistory:
|
||||
"""Persistent sick-day bookkeeping."""
|
||||
|
||||
sick_days: list[str] = field(default_factory=list)
|
||||
debt: int = 0
|
||||
commitments: dict[str, bool] = field(default_factory=dict)
|
||||
broken_commitments: list[str] = field(default_factory=list)
|
||||
justifications: list[dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
def _today_iso() -> str:
|
||||
"""Return today's date as ``YYYY-MM-DD`` (UTC)."""
|
||||
return datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _parse_iso(date_str: str) -> datetime | None:
|
||||
"""Parse ``YYYY-MM-DD`` into a UTC datetime, or return None."""
|
||||
try:
|
||||
return datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"Sick history holds an unparsable date %r (%s) — that entry is "
|
||||
"IGNORED when counting sick days",
|
||||
date_str,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def load_history() -> SickHistory:
|
||||
"""Read the persistent sick-day history file.
|
||||
|
||||
@ -99,75 +90,6 @@ def save_history(history: SickHistory) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def is_sick_day(history: SickHistory, *, today: str | None = None) -> bool:
|
||||
"""Return True if today is recorded as a sick day."""
|
||||
today_str = today or _today_iso()
|
||||
return today_str in history.sick_days
|
||||
|
||||
|
||||
def count_in_window(
|
||||
history: SickHistory,
|
||||
days: int,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> int:
|
||||
"""Return how many ``sick_days`` fall in the trailing ``days`` window."""
|
||||
today_str = today or _today_iso()
|
||||
today_dt = _parse_iso(today_str)
|
||||
if today_dt is None:
|
||||
return 0
|
||||
cutoff = today_dt - timedelta(days=days)
|
||||
count = 0
|
||||
for entry in history.sick_days:
|
||||
parsed = _parse_iso(entry)
|
||||
if parsed is None:
|
||||
continue
|
||||
if cutoff < parsed <= today_dt:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def is_budget_exhausted(
|
||||
history: SickHistory,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> bool:
|
||||
"""Return True if any rolling window has reached its sick budget."""
|
||||
return (
|
||||
count_in_window(history, 7, today=today) >= SICK_BUDGET_PER_7_DAYS
|
||||
or count_in_window(history, 30, today=today) >= SICK_BUDGET_PER_30_DAYS
|
||||
or count_in_window(history, 90, today=today) >= SICK_BUDGET_PER_90_DAYS
|
||||
)
|
||||
|
||||
|
||||
def compute_lockout_seconds(
|
||||
history: SickHistory,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> int:
|
||||
"""Escalating sick countdown: ``base * 2 ** recent_count_in_30d``."""
|
||||
recent = count_in_window(history, 30, today=today)
|
||||
multiplier = SICK_LOCKOUT_MULTIPLIER_PER_RECENT**recent
|
||||
return SICK_LOCKOUT_SECONDS * multiplier
|
||||
|
||||
|
||||
def budget_summary(
|
||||
history: SickHistory,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> str:
|
||||
"""One-line UI summary string for budget + debt."""
|
||||
week = count_in_window(history, 7, today=today)
|
||||
month = count_in_window(history, 30, today=today)
|
||||
quarter = count_in_window(history, 90, today=today)
|
||||
return (
|
||||
f"Sick: {week}/{SICK_BUDGET_PER_7_DAYS}w · "
|
||||
f"{month}/{SICK_BUDGET_PER_30_DAYS}m · "
|
||||
f"{quarter}/{SICK_BUDGET_PER_90_DAYS}q · "
|
||||
f"Debt: {history.debt}"
|
||||
)
|
||||
|
||||
|
||||
def add_sick_day(history: SickHistory, *, today: str | None = None) -> int:
|
||||
"""Append today's date and increment debt. Returns new debt.
|
||||
|
||||
|
||||
@ -10,13 +10,37 @@ status view are built on.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._compliance_state import LockExplanation, explain_lock_decision
|
||||
from screen_locker._compliance_state import explain_lock_decision
|
||||
from screen_locker._status_projection import (
|
||||
_shutdown_projection,
|
||||
format_summary_line,
|
||||
)
|
||||
from screen_locker._status_types import (
|
||||
DayStatus,
|
||||
ManualWorkoutBudgetStatus,
|
||||
ShutdownProjection,
|
||||
ShutdownProjectionDay,
|
||||
SickBudgetStatus,
|
||||
StatusSnapshot,
|
||||
WeeklySummary,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"DayStatus",
|
||||
"ManualWorkoutBudgetStatus",
|
||||
"ShutdownProjection",
|
||||
"ShutdownProjectionDay",
|
||||
"SickBudgetStatus",
|
||||
"StatusSnapshot",
|
||||
"WeeklySummary",
|
||||
"format_summary_line",
|
||||
"gather_status",
|
||||
]
|
||||
from screen_locker._constants import (
|
||||
EARLY_BIRD_PENDING_FILE,
|
||||
EXTRA_BENEFITS_FILE,
|
||||
@ -32,12 +56,9 @@ from screen_locker._constants import (
|
||||
from screen_locker._extra_benefits import (
|
||||
current_streak,
|
||||
has_extended_early_bird,
|
||||
preview_bonus_if_week_ended_now,
|
||||
weekly_shutdown_bonus_hours,
|
||||
)
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._shutdown import read_shutdown_config
|
||||
from screen_locker._shutdown_base import get_base_hours
|
||||
from screen_locker._sick_tracker import (
|
||||
count_in_window,
|
||||
is_budget_exhausted,
|
||||
@ -49,7 +70,6 @@ from screen_locker._weekly_check import (
|
||||
MANUAL_WORKOUT_TYPE,
|
||||
VERIFIED_WORKOUT_TYPES,
|
||||
WEEKLY_WORKOUT_MINIMUM,
|
||||
count_weekly_workouts,
|
||||
is_relaxed_day,
|
||||
)
|
||||
|
||||
@ -57,97 +77,6 @@ if TYPE_CHECKING:
|
||||
from screen_locker._sick_tracker import SickHistory
|
||||
|
||||
_DEFAULT_LOG_FILE = Path(__file__).resolve().parent / "workout_log.json"
|
||||
_RELAXED_DAY_EXPLANATION = (
|
||||
"Shutdown time and the screen lock are two separate systems: the lock "
|
||||
"decides whether you must log a workout right now; shutdown time only "
|
||||
"controls how late the PC stays on tonight."
|
||||
)
|
||||
_WEEKDAY_LABELS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
||||
_MON_WED_WEEKDAYS = frozenset({0, 1, 2})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DayStatus:
|
||||
"""One day's workout outcome (a day may hold several workouts)."""
|
||||
|
||||
date: str
|
||||
label: str
|
||||
entry_types: tuple[str, ...]
|
||||
source: str
|
||||
counted: bool
|
||||
day_count: int
|
||||
is_sick_day: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WeeklySummary:
|
||||
"""This ISO week's workout compliance so far."""
|
||||
|
||||
days: tuple[DayStatus, ...]
|
||||
counted_count: int
|
||||
minimum: int
|
||||
remaining: int
|
||||
extra: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SickBudgetStatus:
|
||||
"""Rolling sick-day budget usage."""
|
||||
|
||||
used_7d: int
|
||||
budget_7d: int
|
||||
used_30d: int
|
||||
budget_30d: int
|
||||
used_90d: int
|
||||
budget_90d: int
|
||||
debt: int
|
||||
exhausted: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ManualWorkoutBudgetStatus:
|
||||
"""Rolling manual-workout budget usage."""
|
||||
|
||||
used_7d: int
|
||||
budget_7d: int
|
||||
used_30d: int
|
||||
budget_30d: int
|
||||
exhausted: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ShutdownProjectionDay:
|
||||
"""One labeled row in a shutdown-time projection."""
|
||||
|
||||
label: str
|
||||
hour: int
|
||||
speculative: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ShutdownProjection:
|
||||
"""Tonight's live config plus deterministic/speculative week projections."""
|
||||
|
||||
tonight: tuple[int, int, int] | None
|
||||
rest_of_week: tuple[ShutdownProjectionDay, ...]
|
||||
next_week_preview: tuple[ShutdownProjectionDay, ...]
|
||||
explanation: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StatusSnapshot:
|
||||
"""Everything the status view needs, gathered in one read-only pass."""
|
||||
|
||||
today: DayStatus
|
||||
week: WeeklySummary
|
||||
bonus_hours_this_week: int
|
||||
streak: int
|
||||
early_bird_extended: bool
|
||||
shutdown: ShutdownProjection
|
||||
lock_explanation: LockExplanation
|
||||
sick_budget: SickBudgetStatus
|
||||
manual_workout_budget: ManualWorkoutBudgetStatus
|
||||
generated_at: str
|
||||
|
||||
|
||||
def _day_status(day_date: date, entries: list[dict], sick_days: set[str]) -> DayStatus:
|
||||
@ -237,51 +166,6 @@ def _manual_workout_budget_status(
|
||||
)
|
||||
|
||||
|
||||
def _week_rows(
|
||||
mon_wed_hour: int, thu_sun_hour: int, *, speculative: bool
|
||||
) -> tuple[ShutdownProjectionDay, ...]:
|
||||
"""Build 7 labeled rows, one per weekday, from a Mon-Wed/Thu-Sun band pair."""
|
||||
return tuple(
|
||||
ShutdownProjectionDay(
|
||||
label=label,
|
||||
hour=mon_wed_hour if weekday in _MON_WED_WEEKDAYS else thu_sun_hour,
|
||||
speculative=speculative,
|
||||
)
|
||||
for weekday, label in enumerate(_WEEKDAY_LABELS)
|
||||
)
|
||||
|
||||
|
||||
def _shutdown_projection(
|
||||
*,
|
||||
shutdown_base_file: Path,
|
||||
shutdown_config_file: Path,
|
||||
extra_benefits_file: Path,
|
||||
log_file: Path,
|
||||
today_local: datetime,
|
||||
) -> ShutdownProjection:
|
||||
"""Build the shutdown-time projection: tonight, rest of week, next week."""
|
||||
tonight = read_shutdown_config(shutdown_config_file)
|
||||
base_mw, base_ts = get_base_hours(shutdown_base_file)
|
||||
bonus = weekly_shutdown_bonus_hours(extra_benefits_file, today=today_local)
|
||||
rest_of_week = _week_rows(base_mw + bonus, base_ts + bonus, speculative=False)
|
||||
|
||||
this_week_count = count_weekly_workouts(log_file, today=today_local)
|
||||
streak = current_streak(extra_benefits_file)
|
||||
_would_be_streak, would_be_bonus = preview_bonus_if_week_ended_now(
|
||||
this_week_count, streak
|
||||
)
|
||||
next_week_preview = _week_rows(
|
||||
base_mw + would_be_bonus, base_ts + would_be_bonus, speculative=True
|
||||
)
|
||||
|
||||
return ShutdownProjection(
|
||||
tonight=tonight,
|
||||
rest_of_week=rest_of_week,
|
||||
next_week_preview=next_week_preview,
|
||||
explanation=_RELAXED_DAY_EXPLANATION,
|
||||
)
|
||||
|
||||
|
||||
def gather_status(
|
||||
*,
|
||||
log_file: Path = _DEFAULT_LOG_FILE,
|
||||
@ -340,31 +224,3 @@ def gather_status(
|
||||
manual_workout_budget=_manual_workout_budget_status(log_file, today=today_str),
|
||||
generated_at=instant.isoformat(),
|
||||
)
|
||||
|
||||
|
||||
def _tonight_hour(snapshot: StatusSnapshot) -> int | None:
|
||||
"""Pick the shutdown hour band (Mon-Wed vs Thu-Sun) matching today.
|
||||
|
||||
Uses ``snapshot.generated_at`` (not a fresh ``datetime.now()``) so the
|
||||
summary line is a pure function of the snapshot it was handed.
|
||||
"""
|
||||
if snapshot.shutdown.tonight is None:
|
||||
return None
|
||||
mon_wed_hour, thu_sun_hour, _morning = snapshot.shutdown.tonight
|
||||
generated_weekday = (
|
||||
datetime.fromisoformat(snapshot.generated_at).astimezone().weekday()
|
||||
)
|
||||
return mon_wed_hour if generated_weekday in _MON_WED_WEEKDAYS else thu_sun_hour
|
||||
|
||||
|
||||
def format_summary_line(snapshot: StatusSnapshot) -> str:
|
||||
"""Cheap one-liner for the i3blocks summary (e.g. before/after a click)."""
|
||||
week = snapshot.week
|
||||
mark = "✓" if week.remaining == 0 else "…"
|
||||
tonight_hour = _tonight_hour(snapshot)
|
||||
tonight_str = f"{tonight_hour:02d}:00" if tonight_hour is not None else "?"
|
||||
sick = snapshot.sick_budget
|
||||
return (
|
||||
f"{mark} {week.counted_count}/{week.minimum} workouts · "
|
||||
f"{tonight_str} tonight · sick {sick.used_7d}/{sick.budget_7d}"
|
||||
)
|
||||
|
||||
110
screen_locker/_status_projection.py
Normal file
110
screen_locker/_status_projection.py
Normal file
@ -0,0 +1,110 @@
|
||||
"""Shutdown projection and the one-line i3blocks summary.
|
||||
|
||||
Split out of :mod:`screen_locker._status_data` to keep every file under the
|
||||
250-line cap. ``format_summary_line`` is re-exported from there, so
|
||||
``status_view`` and the i3blocks CLI are unaffected.
|
||||
|
||||
Projects what time the PC will shut down on each remaining day of the week,
|
||||
and renders the compact status line.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._extra_benefits import (
|
||||
current_streak,
|
||||
preview_bonus_if_week_ended_now,
|
||||
weekly_shutdown_bonus_hours,
|
||||
)
|
||||
from screen_locker._shutdown import read_shutdown_config
|
||||
from screen_locker._shutdown_base import get_base_hours
|
||||
from screen_locker._status_types import ShutdownProjection, ShutdownProjectionDay
|
||||
from screen_locker._weekly_check import count_weekly_workouts
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from screen_locker._status_types import StatusSnapshot
|
||||
|
||||
_RELAXED_DAY_EXPLANATION = (
|
||||
"Shutdown time and the screen lock are two separate systems: the lock "
|
||||
"decides whether you must log a workout right now; shutdown time only "
|
||||
"controls how late the PC stays on tonight."
|
||||
)
|
||||
_WEEKDAY_LABELS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
||||
_MON_WED_WEEKDAYS = frozenset({0, 1, 2})
|
||||
|
||||
|
||||
def _week_rows(
|
||||
mon_wed_hour: int, thu_sun_hour: int, *, speculative: bool
|
||||
) -> tuple[ShutdownProjectionDay, ...]:
|
||||
"""Build 7 labeled rows, one per weekday, from a Mon-Wed/Thu-Sun band pair."""
|
||||
return tuple(
|
||||
ShutdownProjectionDay(
|
||||
label=label,
|
||||
hour=mon_wed_hour if weekday in _MON_WED_WEEKDAYS else thu_sun_hour,
|
||||
speculative=speculative,
|
||||
)
|
||||
for weekday, label in enumerate(_WEEKDAY_LABELS)
|
||||
)
|
||||
|
||||
|
||||
def _shutdown_projection(
|
||||
*,
|
||||
shutdown_base_file: Path,
|
||||
shutdown_config_file: Path,
|
||||
extra_benefits_file: Path,
|
||||
log_file: Path,
|
||||
today_local: datetime,
|
||||
) -> ShutdownProjection:
|
||||
"""Build the shutdown-time projection: tonight, rest of week, next week."""
|
||||
tonight = read_shutdown_config(shutdown_config_file)
|
||||
base_mw, base_ts = get_base_hours(shutdown_base_file)
|
||||
bonus = weekly_shutdown_bonus_hours(extra_benefits_file, today=today_local)
|
||||
rest_of_week = _week_rows(base_mw + bonus, base_ts + bonus, speculative=False)
|
||||
|
||||
this_week_count = count_weekly_workouts(log_file, today=today_local)
|
||||
streak = current_streak(extra_benefits_file)
|
||||
_would_be_streak, would_be_bonus = preview_bonus_if_week_ended_now(
|
||||
this_week_count, streak
|
||||
)
|
||||
next_week_preview = _week_rows(
|
||||
base_mw + would_be_bonus, base_ts + would_be_bonus, speculative=True
|
||||
)
|
||||
|
||||
return ShutdownProjection(
|
||||
tonight=tonight,
|
||||
rest_of_week=rest_of_week,
|
||||
next_week_preview=next_week_preview,
|
||||
explanation=_RELAXED_DAY_EXPLANATION,
|
||||
)
|
||||
|
||||
|
||||
def _tonight_hour(snapshot: StatusSnapshot) -> int | None:
|
||||
"""Pick the shutdown hour band (Mon-Wed vs Thu-Sun) matching today.
|
||||
|
||||
Uses ``snapshot.generated_at`` (not a fresh ``datetime.now()``) so the
|
||||
summary line is a pure function of the snapshot it was handed.
|
||||
"""
|
||||
if snapshot.shutdown.tonight is None:
|
||||
return None
|
||||
mon_wed_hour, thu_sun_hour, _morning = snapshot.shutdown.tonight
|
||||
generated_weekday = (
|
||||
datetime.fromisoformat(snapshot.generated_at).astimezone().weekday()
|
||||
)
|
||||
return mon_wed_hour if generated_weekday in _MON_WED_WEEKDAYS else thu_sun_hour
|
||||
|
||||
|
||||
def format_summary_line(snapshot: StatusSnapshot) -> str:
|
||||
"""Cheap one-liner for the i3blocks summary (e.g. before/after a click)."""
|
||||
week = snapshot.week
|
||||
mark = "✓" if week.remaining == 0 else "…"
|
||||
tonight_hour = _tonight_hour(snapshot)
|
||||
tonight_str = f"{tonight_hour:02d}:00" if tonight_hour is not None else "?"
|
||||
sick = snapshot.sick_budget
|
||||
return (
|
||||
f"{mark} {week.counted_count}/{week.minimum} workouts · "
|
||||
f"{tonight_str} tonight · sick {sick.used_7d}/{sick.budget_7d}"
|
||||
)
|
||||
177
screen_locker/_status_sections.py
Normal file
177
screen_locker/_status_sections.py
Normal file
@ -0,0 +1,177 @@
|
||||
"""The individual rendered sections of the status window.
|
||||
|
||||
Split out of :mod:`screen_locker.status_view` to keep every file under the
|
||||
250-line cap. Composed into ``StatusWindow`` there, alongside the other view
|
||||
mixins, so the class's public surface is unchanged.
|
||||
|
||||
Every method here is display-only: it reads the snapshot it is handed and
|
||||
paints widgets. Nothing in this module writes to disk or reaches the network.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._sync_status import format_sync_line, gather_sync_status
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import tkinter as tk
|
||||
|
||||
from screen_locker._compliance_state import LockExplanation
|
||||
from screen_locker._status_data import (
|
||||
DayStatus,
|
||||
ManualWorkoutBudgetStatus,
|
||||
ShutdownProjection,
|
||||
SickBudgetStatus,
|
||||
WeeklySummary,
|
||||
)
|
||||
|
||||
|
||||
class StatusSectionsMixin:
|
||||
"""Renders each section of the status window from a snapshot."""
|
||||
|
||||
def _section_today(self, parent: tk.Widget, day: DayStatus) -> None:
|
||||
"""Render today's outcome."""
|
||||
del parent
|
||||
mark = "✓" if day.counted else ("😷" if day.is_sick_day else "—")
|
||||
entry_str = ", ".join(day.entry_types) or (
|
||||
"sick day" if day.is_sick_day else "no entry yet"
|
||||
)
|
||||
self._text(
|
||||
f"{mark} Today ({day.label}): {entry_str}",
|
||||
role="body",
|
||||
color=self._colors.success if day.counted else self._colors.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.muted, pad="xs")
|
||||
|
||||
def _section_week(self, parent: tk.Widget, week: WeeklySummary) -> None:
|
||||
"""Render this ISO week's per-day breakdown and totals."""
|
||||
del parent
|
||||
self._label(
|
||||
f"This Week: {week.counted_count}/{week.minimum}", role="body", pad="sm"
|
||||
)
|
||||
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.muted,
|
||||
pad="xs",
|
||||
)
|
||||
if week.remaining > 0:
|
||||
self._text(
|
||||
f"Need {week.remaining} more this week.",
|
||||
role="body",
|
||||
color=self._colors.warning,
|
||||
)
|
||||
elif week.extra > 0:
|
||||
self._text(
|
||||
f"{week.extra} above the weekly minimum!",
|
||||
role="body",
|
||||
color=self._colors.success,
|
||||
)
|
||||
|
||||
def _section_lock_explanation(
|
||||
self, parent: tk.Widget, expl: LockExplanation
|
||||
) -> None:
|
||||
"""Render why the lock did/didn't fire today, plus its evaluation trace."""
|
||||
del parent
|
||||
self._label("Why the lock did/didn't fire", role="body", pad="sm")
|
||||
self._text(
|
||||
expl.reason,
|
||||
role="body",
|
||||
color=self._colors.danger if expl.fired else self._colors.success,
|
||||
)
|
||||
if expl.auto_upgrade.would_attempt:
|
||||
self._text(
|
||||
f"Pending auto-upgrade: {expl.auto_upgrade.reason}",
|
||||
role="label",
|
||||
color=self._colors.warning,
|
||||
)
|
||||
|
||||
def _section_sick_budget(self, parent: tk.Widget, sick: SickBudgetStatus) -> None:
|
||||
"""Render rolling sick-day budget usage."""
|
||||
del parent
|
||||
self._label("Sick Budget", role="body", pad="sm")
|
||||
self._text(
|
||||
f"{sick.used_7d}/{sick.budget_7d} week · {sick.used_30d}/{sick.budget_30d} "
|
||||
f"month · {sick.used_90d}/{sick.budget_90d} quarter · debt {sick.debt}",
|
||||
role="body",
|
||||
color=self._colors.danger if sick.exhausted else self._colors.muted,
|
||||
)
|
||||
|
||||
def _section_manual_workout_budget(
|
||||
self, parent: tk.Widget, manual: ManualWorkoutBudgetStatus
|
||||
) -> None:
|
||||
"""Render rolling manual-workout budget usage."""
|
||||
del parent
|
||||
self._label("Manual Workout Budget", role="body", pad="sm")
|
||||
self._text(
|
||||
f"{manual.used_7d}/{manual.budget_7d} week · "
|
||||
f"{manual.used_30d}/{manual.budget_30d} month",
|
||||
role="body",
|
||||
color=self._colors.danger if manual.exhausted else self._colors.muted,
|
||||
)
|
||||
|
||||
def _section_sync_backend(self, parent: tk.Widget) -> None:
|
||||
"""Render which backend this machine syncs through.
|
||||
|
||||
Read from local state only (see :mod:`screen_locker._sync_status`), so
|
||||
opening or refreshing the window never makes a network call. Coloured
|
||||
by ``healthy`` rather than by backend: "configured but never pushed"
|
||||
looks fine everywhere else and produces no data, which is exactly the
|
||||
state worth surfacing here.
|
||||
"""
|
||||
del parent
|
||||
status = gather_sync_status()
|
||||
self._label("Sync backend", role="body", pad="sm")
|
||||
self._text(
|
||||
format_sync_line(status),
|
||||
role="body",
|
||||
color=self._colors.muted if status.healthy else self._colors.danger,
|
||||
)
|
||||
|
||||
def _section_shutdown(
|
||||
self, parent: tk.Widget, shutdown: ShutdownProjection
|
||||
) -> None:
|
||||
"""Render tonight's live config, rest-of-week, and next-week preview."""
|
||||
del parent
|
||||
self._label("Shutdown Time", role="body", pad="sm")
|
||||
if shutdown.tonight is not None:
|
||||
mon_wed_hour, thu_sun_hour, _morning = shutdown.tonight
|
||||
self._text(
|
||||
f"Live config — Mon-Wed {mon_wed_hour:02d}:00, "
|
||||
f"Thu-Sun {thu_sun_hour:02d}:00",
|
||||
role="body",
|
||||
)
|
||||
else:
|
||||
self._text(
|
||||
"Live shutdown config unavailable.",
|
||||
role="body",
|
||||
color=self._colors.warning,
|
||||
)
|
||||
# Rest-of-week/next-week/explanation are speculative annotations, not
|
||||
# the section's primary content -- a deliberate caption-sized
|
||||
# exception to the 16px floor, all sharing one muted tone instead of
|
||||
# three unrelated ad hoc grays.
|
||||
rest_line = ", ".join(
|
||||
f"{d.label} {d.hour:02d}:00" for d in shutdown.rest_of_week
|
||||
)
|
||||
self._text(
|
||||
f"Rest of week: {rest_line}", role="caption", color=self._colors.muted
|
||||
)
|
||||
next_line = ", ".join(
|
||||
f"{d.label} {d.hour:02d}:00" for d in shutdown.next_week_preview
|
||||
)
|
||||
self._text(
|
||||
f"Next week (speculative): {next_line}",
|
||||
role="caption",
|
||||
color=self._colors.muted,
|
||||
)
|
||||
self._text(shutdown.explanation, role="caption", color=self._colors.muted)
|
||||
101
screen_locker/_status_types.py
Normal file
101
screen_locker/_status_types.py
Normal file
@ -0,0 +1,101 @@
|
||||
"""The frozen dataclasses describing a status snapshot.
|
||||
|
||||
Split out of :mod:`screen_locker._status_data` to keep every file under the
|
||||
250-line cap. Re-exported from there, so ``status_view`` and every other
|
||||
importer is unaffected.
|
||||
|
||||
These are plain value objects: building them from disk is ``_status_data``'s
|
||||
job, rendering them is ``_status_sections``'.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from screen_locker._compliance_state import LockExplanation
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DayStatus:
|
||||
"""One day's workout outcome (a day may hold several workouts)."""
|
||||
|
||||
date: str
|
||||
label: str
|
||||
entry_types: tuple[str, ...]
|
||||
source: str
|
||||
counted: bool
|
||||
day_count: int
|
||||
is_sick_day: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WeeklySummary:
|
||||
"""This ISO week's workout compliance so far."""
|
||||
|
||||
days: tuple[DayStatus, ...]
|
||||
counted_count: int
|
||||
minimum: int
|
||||
remaining: int
|
||||
extra: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SickBudgetStatus:
|
||||
"""Rolling sick-day budget usage."""
|
||||
|
||||
used_7d: int
|
||||
budget_7d: int
|
||||
used_30d: int
|
||||
budget_30d: int
|
||||
used_90d: int
|
||||
budget_90d: int
|
||||
debt: int
|
||||
exhausted: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ManualWorkoutBudgetStatus:
|
||||
"""Rolling manual-workout budget usage."""
|
||||
|
||||
used_7d: int
|
||||
budget_7d: int
|
||||
used_30d: int
|
||||
budget_30d: int
|
||||
exhausted: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ShutdownProjectionDay:
|
||||
"""One labeled row in a shutdown-time projection."""
|
||||
|
||||
label: str
|
||||
hour: int
|
||||
speculative: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ShutdownProjection:
|
||||
"""Tonight's live config plus deterministic/speculative week projections."""
|
||||
|
||||
tonight: tuple[int, int, int] | None
|
||||
rest_of_week: tuple[ShutdownProjectionDay, ...]
|
||||
next_week_preview: tuple[ShutdownProjectionDay, ...]
|
||||
explanation: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StatusSnapshot:
|
||||
"""Everything the status view needs, gathered in one read-only pass."""
|
||||
|
||||
today: DayStatus
|
||||
week: WeeklySummary
|
||||
bonus_hours_this_week: int
|
||||
streak: int
|
||||
early_bird_extended: bool
|
||||
shutdown: ShutdownProjection
|
||||
lock_explanation: LockExplanation
|
||||
sick_budget: SickBudgetStatus
|
||||
manual_workout_budget: ManualWorkoutBudgetStatus
|
||||
generated_at: str
|
||||
120
screen_locker/_sync_client.py
Normal file
120
screen_locker/_sync_client.py
Normal file
@ -0,0 +1,120 @@
|
||||
"""Building the sync client: read the token, pick Firebase or the GitHub mirror.
|
||||
|
||||
Split out of :mod:`screen_locker._workout_sync` to keep every file under the
|
||||
250-line cap. Re-exported from there, so callers and their patch targets are
|
||||
unchanged.
|
||||
|
||||
``sync_client`` returning None means sync is OFF -- and says why in the log,
|
||||
because a silent None here is exactly how the PC stopped syncing for weeks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from crdt_sync import (
|
||||
CONFIG_FILE,
|
||||
ConfigError,
|
||||
FirebaseAuthError,
|
||||
GitHubSyncClient,
|
||||
RemoteStore,
|
||||
RemoteSyncError,
|
||||
firebase_client_for,
|
||||
mirror_client_for,
|
||||
)
|
||||
|
||||
from screen_locker._constants import (
|
||||
SYNC_REPO_NAME,
|
||||
SYNC_REPO_OWNER,
|
||||
SYNC_TIMEOUT_SECONDS,
|
||||
SYNC_TOKEN_FILE,
|
||||
)
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def read_sync_token() -> str | None:
|
||||
"""Return the saved sync PAT, or None if sync isn't configured.
|
||||
|
||||
Unlike diet_guard's equivalent, an absent or empty token file is a
|
||||
normal state here -- sync is an optional primary channel, not something
|
||||
the app requires to function.
|
||||
"""
|
||||
if not SYNC_TOKEN_FILE.exists():
|
||||
return None
|
||||
token = SYNC_TOKEN_FILE.read_text().strip()
|
||||
return token or None
|
||||
|
||||
|
||||
def remote_client(github: RemoteStore) -> RemoteStore:
|
||||
"""Return the backend to read the phone's workout log from.
|
||||
|
||||
Firebase when ``~/.config/crdt-sync/`` is set up, with GitHub kept as a
|
||||
mirror so a phone that has not moved yet is still seen; GitHub alone
|
||||
otherwise. Both callers here are read-only pulls -- this side never pushes
|
||||
-- and :class:`MirrorSyncClient` reads the union of both, so a workout
|
||||
logged against either backend still counts.
|
||||
|
||||
The config file is checked before constructing anything, so an
|
||||
unconfigured machine never reaches the network.
|
||||
|
||||
Rolling back is deleting this function and passing ``github`` straight
|
||||
through: no data moves either way.
|
||||
"""
|
||||
if not CONFIG_FILE.is_file():
|
||||
return github
|
||||
try:
|
||||
return mirror_client_for("screen_locker", github)
|
||||
except (ConfigError, FirebaseAuthError, RemoteSyncError) as exc:
|
||||
_logger.warning(
|
||||
"Firebase unavailable, reading workouts via GitHub only: %s", exc
|
||||
)
|
||||
return github
|
||||
|
||||
|
||||
def sync_client() -> RemoteStore | None:
|
||||
"""Return the configured read client, or None if sync is set up nowhere.
|
||||
|
||||
A GitHub token is no longer required: Firebase has been the primary backend
|
||||
since eb4ff01, so a Firebase-only machine must still sync. Previously this
|
||||
module returned early whenever the PAT was missing, reporting "sync is OFF"
|
||||
on a machine whose sync was working perfectly -- a false negative that hid
|
||||
a live backend behind a legacy credential check.
|
||||
|
||||
GitHub is used alone when only the PAT exists, Firebase alone when only
|
||||
``~/.config/crdt-sync/`` exists, and the mirrored union when both do.
|
||||
``None`` means neither is configured, which stays a benign, expected state.
|
||||
"""
|
||||
token = read_sync_token()
|
||||
github = (
|
||||
GitHubSyncClient(
|
||||
SYNC_REPO_OWNER,
|
||||
SYNC_REPO_NAME,
|
||||
token,
|
||||
timeout_seconds=SYNC_TIMEOUT_SECONDS,
|
||||
)
|
||||
if token is not None
|
||||
else None
|
||||
)
|
||||
if github is not None:
|
||||
return remote_client(github)
|
||||
if not CONFIG_FILE.is_file():
|
||||
_logger.warning(
|
||||
"Cannot pull synced workouts: no sync token at %s and no Firebase "
|
||||
"config at %s — sync is OFF, so only ADB/HTTP can verify a phone "
|
||||
"workout and phone-logged workouts will NOT count here",
|
||||
SYNC_TOKEN_FILE,
|
||||
CONFIG_FILE,
|
||||
)
|
||||
return None
|
||||
try:
|
||||
return firebase_client_for("screen_locker")
|
||||
except (ConfigError, FirebaseAuthError, RemoteSyncError) as exc:
|
||||
_logger.warning(
|
||||
"Firebase is configured at %s but unusable, and there is no GitHub "
|
||||
"token at %s to fall back to: %s — pulling NO synced workouts",
|
||||
CONFIG_FILE,
|
||||
SYNC_TOKEN_FILE,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
91
screen_locker/_sync_records.py
Normal file
91
screen_locker/_sync_records.py
Normal file
@ -0,0 +1,91 @@
|
||||
"""Decoding sync-log blobs into records, and telling record kinds apart.
|
||||
|
||||
Split out of :mod:`screen_locker._workout_sync` to keep every file under the
|
||||
250-line cap. Re-exported from there, so callers are unchanged.
|
||||
|
||||
Everything here is pure: it parses JSON that a caller already fetched. Talking
|
||||
to GitHub or Firebase stays in ``_workout_sync``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync import Hlc, Record
|
||||
|
||||
from screen_locker._manual_workout import MANUAL_WORKOUT_SYNC_KIND
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_PAYLOAD_FIELD = "payload"
|
||||
|
||||
|
||||
def _is_manual_payload(payload: object) -> bool:
|
||||
"""True if a decoded sync payload is a manual-workout record."""
|
||||
return isinstance(payload, dict) and payload.get("kind") == MANUAL_WORKOUT_SYNC_KIND
|
||||
|
||||
|
||||
def _is_session_payload(payload: object) -> bool:
|
||||
"""True if a decoded sync payload is a completed StrongLifts session.
|
||||
|
||||
Identified by SHAPE -- the presence of ``exercises`` -- not by a ``kind``
|
||||
field, because the phone app's ``WorkoutSession.toJson()`` emits no ``kind``
|
||||
at all. Keying session detection on ``kind`` is what made real sessions
|
||||
invisible to the only reader that walks every device directory.
|
||||
|
||||
Shape-matching also excludes the PC-origin ``runnerup_verified`` /
|
||||
``phone_verified`` records that share these device logs: they are non-manual
|
||||
too, so "not manual" alone would hand a caller expecting ``exercises`` and
|
||||
``duration_seconds`` a record that has neither.
|
||||
"""
|
||||
return isinstance(payload, dict) and isinstance(payload.get("exercises"), list)
|
||||
|
||||
|
||||
def _session_records(log_json: str) -> dict[str, tuple[dict, Hlc]]:
|
||||
"""Return ``{record_id: (payload, hlc)}`` for session records in a log blob.
|
||||
|
||||
Raises the same decode errors as :func:`_manual_records`; callers treat a
|
||||
corrupt device log as "no sessions from that device".
|
||||
"""
|
||||
return _records_matching(log_json, _is_session_payload)
|
||||
|
||||
|
||||
def _records_matching(
|
||||
log_json: str, predicate: Callable[[object], bool]
|
||||
) -> dict[str, tuple[dict, Hlc]]:
|
||||
"""Return ``{record_id: (payload, hlc)}`` for payloads passing ``predicate``.
|
||||
|
||||
Raises:
|
||||
TypeError: If the top-level JSON isn't an object or a record's shape
|
||||
doesn't match what :meth:`Record.from_dict` expects.
|
||||
KeyError: If a record is missing an expected key.
|
||||
ValueError: Via ``json.loads`` or :meth:`crdt_sync.Hlc.from_str`.
|
||||
"""
|
||||
raw = json.loads(log_json)
|
||||
if not isinstance(raw, dict):
|
||||
msg = f"top-level sync payload is not a JSON object: {raw!r}"
|
||||
raise TypeError(msg)
|
||||
result: dict[str, tuple[dict, Hlc]] = {}
|
||||
for data in raw.values():
|
||||
record = Record.from_dict(data)
|
||||
field = record.fields.get(_PAYLOAD_FIELD)
|
||||
if field is None:
|
||||
continue
|
||||
payload, hlc = field
|
||||
if predicate(payload):
|
||||
result[record.id] = (payload, hlc)
|
||||
return result
|
||||
|
||||
|
||||
def _manual_records(log_json: str) -> dict[str, tuple[dict, Hlc]]:
|
||||
"""Return ``{record_id: (payload, hlc)}`` for manual records in a log blob.
|
||||
|
||||
Raises the same decode errors as :func:`_records_matching`; callers treat a
|
||||
corrupt device log as "no manual records from that device".
|
||||
"""
|
||||
return _records_matching(log_json, _is_manual_payload)
|
||||
@ -6,18 +6,19 @@ from concurrent.futures import ThreadPoolExecutor # pylint: disable=no-name-in-
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker import _manual_workout, _sick_tracker
|
||||
from screen_locker._constants import (
|
||||
NO_PHONE_EXTRA_LOCKOUT_SECONDS,
|
||||
PHONE_PENALTY_DELAY_DEMO,
|
||||
PHONE_PENALTY_DELAY_PRODUCTION,
|
||||
)
|
||||
from screen_locker._ui_flows_lockout import LockoutFlowMixin
|
||||
from screen_locker._ui_flows_sick import SickDayFlowMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
|
||||
class UIFlowsMixin:
|
||||
"""Mixin providing UI flow logic for the screen locker."""
|
||||
class UIFlowsMixin(SickDayFlowMixin, LockoutFlowMixin):
|
||||
"""Mixin providing UI flow logic for the screen locker.
|
||||
|
||||
The sick-day and lockout/penalty flows live in sibling modules and are
|
||||
composed in here, so ``ScreenLocker``'s own mixin list stays as it was.
|
||||
"""
|
||||
|
||||
def paint_phone_check(self) -> None:
|
||||
"""Paint the "checking phone" screen, without starting the check.
|
||||
@ -198,173 +199,3 @@ class UIFlowsMixin:
|
||||
self._runnerup_on_failure()
|
||||
else:
|
||||
self.root.after(500, self._poll_runnerup_fallback)
|
||||
|
||||
def ask_if_sick(self) -> None:
|
||||
"""Display the structured sick-day justification dialog."""
|
||||
self._show_sick_justification()
|
||||
|
||||
def _get_sick_day_status(self) -> tuple[str, str]:
|
||||
"""Determine sick day status text and color."""
|
||||
if self._sick_mode_used_today():
|
||||
return "Shutdown time already adjusted today", self._colors.warning
|
||||
if self._adjust_shutdown_time_earlier():
|
||||
return (
|
||||
"Shutdown time moved 1.5 hours earlier ✓\n(Will revert tomorrow)"
|
||||
), self._colors.success
|
||||
return (
|
||||
"Could not adjust shutdown time (check permissions)",
|
||||
self._colors.danger,
|
||||
)
|
||||
|
||||
def _proceed_to_sick_countdown(self) -> None:
|
||||
"""Start the (escalated) sick day countdown after justification."""
|
||||
history = getattr(
|
||||
self,
|
||||
"_sick_history_cache",
|
||||
None,
|
||||
)
|
||||
if history is None:
|
||||
history = _sick_tracker.load_history()
|
||||
self._sick_history_cache = history
|
||||
countdown = _sick_tracker.compute_lockout_seconds(history)
|
||||
self.clear_container()
|
||||
status_text, status_color = self._get_sick_day_status()
|
||||
self._show_sick_day_ui(status_text, status_color, countdown)
|
||||
self.sick_remaining_time = countdown
|
||||
self._update_sick_countdown()
|
||||
|
||||
def _show_sick_day_ui(
|
||||
self,
|
||||
status_text: str,
|
||||
status_color: str,
|
||||
countdown: int,
|
||||
) -> None:
|
||||
"""Display sick day UI labels and countdown."""
|
||||
self._label("Sick Day Mode", color=self._colors.warning, pad="md")
|
||||
self._text(status_text, color=status_color)
|
||||
minutes = countdown // 60
|
||||
self._text(
|
||||
f"Please wait ~{minutes} min before unlocking...",
|
||||
role="title",
|
||||
pad="md",
|
||||
)
|
||||
self.sick_countdown_label = self._label(
|
||||
str(countdown),
|
||||
role="display",
|
||||
scale=2.5,
|
||||
pad="lg",
|
||||
)
|
||||
|
||||
def _update_sick_countdown(self) -> None:
|
||||
"""Update the sick day countdown timer."""
|
||||
if self.sick_remaining_time > 0:
|
||||
self.sick_countdown_label.config(text=str(self.sick_remaining_time))
|
||||
self.sick_remaining_time -= 1
|
||||
self.root.after(1000, self._update_sick_countdown)
|
||||
else:
|
||||
self._finalize_sick_day()
|
||||
|
||||
def _finalize_sick_day(self) -> None:
|
||||
"""Persist sick-day history and unlock the screen."""
|
||||
history = getattr(self, "_sick_history_cache", None)
|
||||
if history is None:
|
||||
history = _sick_tracker.load_history()
|
||||
if _sick_tracker.had_commitment_for_today(history):
|
||||
_sick_tracker.mark_commitment_broken(history)
|
||||
self.workout_data["broke_commitment"] = "true"
|
||||
new_debt = _sick_tracker.add_sick_day(history)
|
||||
_sick_tracker.save_history(history)
|
||||
self.workout_data["type"] = "sick_day"
|
||||
self.workout_data["note"] = "Sick day - shutdown moved earlier"
|
||||
self.workout_data["debt"] = str(new_debt)
|
||||
self.unlock_screen()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Lockout flow
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def lockout(self) -> None:
|
||||
"""Display lockout screen with countdown timer."""
|
||||
self.clear_container()
|
||||
self.lockout_label = self._label(
|
||||
f"Go work out!\nLocked for {self.lockout_time} seconds",
|
||||
role="display",
|
||||
scale=1.5,
|
||||
color=self._colors.danger,
|
||||
pad="lg",
|
||||
)
|
||||
self.countdown_label = self._label(
|
||||
str(self.lockout_time),
|
||||
role="display",
|
||||
scale=3.75,
|
||||
pad="lg",
|
||||
)
|
||||
self.remaining_time = self.lockout_time
|
||||
self.update_lockout_countdown()
|
||||
|
||||
def update_lockout_countdown(self) -> None:
|
||||
"""Update the lockout countdown timer display."""
|
||||
if self.remaining_time > 0:
|
||||
self.countdown_label.config(text=str(self.remaining_time))
|
||||
self.remaining_time -= 1
|
||||
self.root.after(1000, self.update_lockout_countdown)
|
||||
else:
|
||||
self._start_phone_check()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Phone penalty
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _show_phone_penalty(
|
||||
self, message: str, *, on_done: Callable[[], None] | None = None
|
||||
) -> None:
|
||||
"""Show penalty countdown when phone verification is unavailable."""
|
||||
self.clear_container()
|
||||
self._phone_penalty_done_fn: Callable[[], None] = (
|
||||
on_done
|
||||
if on_done is not None
|
||||
else lambda: self._show_retry_and_sick(message)
|
||||
)
|
||||
base_delay = (
|
||||
PHONE_PENALTY_DELAY_DEMO
|
||||
if self.demo_mode
|
||||
else PHONE_PENALTY_DELAY_PRODUCTION
|
||||
)
|
||||
# Disconnecting the phone shouldn't be a fast path into sick mode.
|
||||
delay = (
|
||||
base_delay
|
||||
if self.demo_mode
|
||||
else base_delay + NO_PHONE_EXTRA_LOCKOUT_SECONDS
|
||||
)
|
||||
self._label(
|
||||
"Cannot Verify Workout",
|
||||
role="display",
|
||||
color=self._colors.warning,
|
||||
pad="md",
|
||||
)
|
||||
self._text(message, color=self._colors.warning)
|
||||
self._text(
|
||||
"Connect phone via ADB to skip this wait,\n"
|
||||
"or wait for the penalty timer.\n\n"
|
||||
"Note: Phone must be rooted and StrongLifts installed.",
|
||||
role="body",
|
||||
)
|
||||
self.phone_penalty_remaining = delay
|
||||
self.phone_penalty_label = self._label(
|
||||
str(delay),
|
||||
role="display",
|
||||
scale=2.5,
|
||||
pad="md",
|
||||
)
|
||||
self._update_phone_penalty()
|
||||
|
||||
def _update_phone_penalty(self) -> None:
|
||||
"""Update phone penalty countdown."""
|
||||
if self.phone_penalty_remaining > 0:
|
||||
self.phone_penalty_label.config(
|
||||
text=str(self.phone_penalty_remaining),
|
||||
)
|
||||
self.phone_penalty_remaining -= 1
|
||||
self.root.after(1000, self._update_phone_penalty)
|
||||
else:
|
||||
self._phone_penalty_done_fn()
|
||||
|
||||
113
screen_locker/_ui_flows_lockout.py
Normal file
113
screen_locker/_ui_flows_lockout.py
Normal file
@ -0,0 +1,113 @@
|
||||
"""Lockout countdown and phone-penalty flows for the locked screen.
|
||||
|
||||
Split out of :mod:`screen_locker._ui_flows` to keep every file under the
|
||||
250-line cap. Composed back into ``UIFlowsMixin`` there, so the set of mixins
|
||||
``ScreenLocker`` inherits is unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._constants import (
|
||||
NO_PHONE_EXTRA_LOCKOUT_SECONDS,
|
||||
PHONE_PENALTY_DELAY_DEMO,
|
||||
PHONE_PENALTY_DELAY_PRODUCTION,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
|
||||
class LockoutFlowMixin:
|
||||
"""Lockout countdown and the no-phone penalty timer."""
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Lockout flow
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def lockout(self) -> None:
|
||||
"""Display lockout screen with countdown timer."""
|
||||
self.clear_container()
|
||||
self.lockout_label = self._label(
|
||||
f"Go work out!\nLocked for {self.lockout_time} seconds",
|
||||
role="display",
|
||||
scale=1.5,
|
||||
color=self._colors.danger,
|
||||
pad="lg",
|
||||
)
|
||||
self.countdown_label = self._label(
|
||||
str(self.lockout_time),
|
||||
role="display",
|
||||
scale=3.75,
|
||||
pad="lg",
|
||||
)
|
||||
self.remaining_time = self.lockout_time
|
||||
self.update_lockout_countdown()
|
||||
|
||||
def update_lockout_countdown(self) -> None:
|
||||
"""Update the lockout countdown timer display."""
|
||||
if self.remaining_time > 0:
|
||||
self.countdown_label.config(text=str(self.remaining_time))
|
||||
self.remaining_time -= 1
|
||||
self.root.after(1000, self.update_lockout_countdown)
|
||||
else:
|
||||
self._start_phone_check()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Phone penalty
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _show_phone_penalty(
|
||||
self, message: str, *, on_done: Callable[[], None] | None = None
|
||||
) -> None:
|
||||
"""Show penalty countdown when phone verification is unavailable."""
|
||||
self.clear_container()
|
||||
self._phone_penalty_done_fn: Callable[[], None] = (
|
||||
on_done
|
||||
if on_done is not None
|
||||
else lambda: self._show_retry_and_sick(message)
|
||||
)
|
||||
base_delay = (
|
||||
PHONE_PENALTY_DELAY_DEMO
|
||||
if self.demo_mode
|
||||
else PHONE_PENALTY_DELAY_PRODUCTION
|
||||
)
|
||||
# Disconnecting the phone shouldn't be a fast path into sick mode.
|
||||
delay = (
|
||||
base_delay
|
||||
if self.demo_mode
|
||||
else base_delay + NO_PHONE_EXTRA_LOCKOUT_SECONDS
|
||||
)
|
||||
self._label(
|
||||
"Cannot Verify Workout",
|
||||
role="display",
|
||||
color=self._colors.warning,
|
||||
pad="md",
|
||||
)
|
||||
self._text(message, color=self._colors.warning)
|
||||
self._text(
|
||||
"Connect phone via ADB to skip this wait,\n"
|
||||
"or wait for the penalty timer.\n\n"
|
||||
"Note: Phone must be rooted and StrongLifts installed.",
|
||||
role="body",
|
||||
)
|
||||
self.phone_penalty_remaining = delay
|
||||
self.phone_penalty_label = self._label(
|
||||
str(delay),
|
||||
role="display",
|
||||
scale=2.5,
|
||||
pad="md",
|
||||
)
|
||||
self._update_phone_penalty()
|
||||
|
||||
def _update_phone_penalty(self) -> None:
|
||||
"""Update phone penalty countdown."""
|
||||
if self.phone_penalty_remaining > 0:
|
||||
self.phone_penalty_label.config(
|
||||
text=str(self.phone_penalty_remaining),
|
||||
)
|
||||
self.phone_penalty_remaining -= 1
|
||||
self.root.after(1000, self._update_phone_penalty)
|
||||
else:
|
||||
self._phone_penalty_done_fn()
|
||||
94
screen_locker/_ui_flows_sick.py
Normal file
94
screen_locker/_ui_flows_sick.py
Normal file
@ -0,0 +1,94 @@
|
||||
"""Sick-day flow for the screen locker's locked screen.
|
||||
|
||||
Split out of :mod:`screen_locker._ui_flows` to keep every file under the
|
||||
250-line cap. Composed back into ``UIFlowsMixin`` there, so the set of mixins
|
||||
``ScreenLocker`` inherits is unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from screen_locker import _sick_tracker
|
||||
|
||||
|
||||
class SickDayFlowMixin:
|
||||
"""Sick-day justification, countdown and debt bookkeeping."""
|
||||
|
||||
def ask_if_sick(self) -> None:
|
||||
"""Display the structured sick-day justification dialog."""
|
||||
self._show_sick_justification()
|
||||
|
||||
def _get_sick_day_status(self) -> tuple[str, str]:
|
||||
"""Determine sick day status text and color."""
|
||||
if self._sick_mode_used_today():
|
||||
return "Shutdown time already adjusted today", self._colors.warning
|
||||
if self._adjust_shutdown_time_earlier():
|
||||
return (
|
||||
"Shutdown time moved 1.5 hours earlier ✓\n(Will revert tomorrow)"
|
||||
), self._colors.success
|
||||
return (
|
||||
"Could not adjust shutdown time (check permissions)",
|
||||
self._colors.danger,
|
||||
)
|
||||
|
||||
def _proceed_to_sick_countdown(self) -> None:
|
||||
"""Start the (escalated) sick day countdown after justification."""
|
||||
history = getattr(
|
||||
self,
|
||||
"_sick_history_cache",
|
||||
None,
|
||||
)
|
||||
if history is None:
|
||||
history = _sick_tracker.load_history()
|
||||
self._sick_history_cache = history
|
||||
countdown = _sick_tracker.compute_lockout_seconds(history)
|
||||
self.clear_container()
|
||||
status_text, status_color = self._get_sick_day_status()
|
||||
self._show_sick_day_ui(status_text, status_color, countdown)
|
||||
self.sick_remaining_time = countdown
|
||||
self._update_sick_countdown()
|
||||
|
||||
def _show_sick_day_ui(
|
||||
self,
|
||||
status_text: str,
|
||||
status_color: str,
|
||||
countdown: int,
|
||||
) -> None:
|
||||
"""Display sick day UI labels and countdown."""
|
||||
self._label("Sick Day Mode", color=self._colors.warning, pad="md")
|
||||
self._text(status_text, color=status_color)
|
||||
minutes = countdown // 60
|
||||
self._text(
|
||||
f"Please wait ~{minutes} min before unlocking...",
|
||||
role="title",
|
||||
pad="md",
|
||||
)
|
||||
self.sick_countdown_label = self._label(
|
||||
str(countdown),
|
||||
role="display",
|
||||
scale=2.5,
|
||||
pad="lg",
|
||||
)
|
||||
|
||||
def _update_sick_countdown(self) -> None:
|
||||
"""Update the sick day countdown timer."""
|
||||
if self.sick_remaining_time > 0:
|
||||
self.sick_countdown_label.config(text=str(self.sick_remaining_time))
|
||||
self.sick_remaining_time -= 1
|
||||
self.root.after(1000, self._update_sick_countdown)
|
||||
else:
|
||||
self._finalize_sick_day()
|
||||
|
||||
def _finalize_sick_day(self) -> None:
|
||||
"""Persist sick-day history and unlock the screen."""
|
||||
history = getattr(self, "_sick_history_cache", None)
|
||||
if history is None:
|
||||
history = _sick_tracker.load_history()
|
||||
if _sick_tracker.had_commitment_for_today(history):
|
||||
_sick_tracker.mark_commitment_broken(history)
|
||||
self.workout_data["broke_commitment"] = "true"
|
||||
new_debt = _sick_tracker.add_sick_day(history)
|
||||
_sick_tracker.save_history(history)
|
||||
self.workout_data["type"] = "sick_day"
|
||||
self.workout_data["note"] = "Sick day - shutdown moved earlier"
|
||||
self.workout_data["debt"] = str(new_debt)
|
||||
self.unlock_screen()
|
||||
138
screen_locker/_ui_form_fields.py
Normal file
138
screen_locker/_ui_form_fields.py
Normal file
@ -0,0 +1,138 @@
|
||||
"""Labelled form fields and initial focus, shared by every lock surface.
|
||||
|
||||
Split out of :mod:`screen_locker._ui_widgets` to keep every file under the
|
||||
250-line cap. Composed back into ``UIWidgetsMixin`` there, so every host
|
||||
class keeps the same surface.
|
||||
|
||||
Each helper builds its widget on *every* monitor (the lock spans them all),
|
||||
which is why they return groups rather than single widgets.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock import escape_text_tab_trap
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from screen_locker._surface_group import FrameGroup, WidgetGroup
|
||||
|
||||
|
||||
def disable_paste(widget: tk.Widget) -> None:
|
||||
"""Disable paste in a Tk Entry/Text widget.
|
||||
|
||||
Friction-only: a determined user can still bypass via xdotool, but the
|
||||
point is removing the trivial Ctrl+V shortcut so the user must
|
||||
actually type their input.
|
||||
"""
|
||||
for sequence in ("<<Paste>>", "<Control-v>", "<Control-V>", "<Button-2>"):
|
||||
with contextlib.suppress(tk.TclError, AttributeError):
|
||||
widget.bind(sequence, lambda _e: "break")
|
||||
|
||||
|
||||
class UIFormFieldsMixin:
|
||||
"""Labelled entry/text fields and initial focus for the lock surfaces."""
|
||||
|
||||
def _add_label_entry(
|
||||
self,
|
||||
parent: FrameGroup,
|
||||
*,
|
||||
label: str,
|
||||
variable: tk.StringVar,
|
||||
focus: bool = False,
|
||||
) -> None:
|
||||
"""Add a label + single-line entry pair on every monitor.
|
||||
|
||||
All copies share one ``variable``, so typing on any screen is the
|
||||
same text everywhere and reading it back needs no idea which monitor
|
||||
the user actually used.
|
||||
|
||||
``focus`` gives the primary surface's copy the keyboard focus. Exactly
|
||||
one field per screen should ask: the lock takes a global grab, so with
|
||||
nothing focused the user's typing goes nowhere and there is no other
|
||||
window on screen to make that obvious.
|
||||
"""
|
||||
row = parent.child_frame(bg=self._colors.bg)
|
||||
row.pack(pady=self._colors.space("sm"), fill="x")
|
||||
row.child_widgets(
|
||||
tk.Label,
|
||||
text=label,
|
||||
font=self._colors.font("label"),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
anchor="w",
|
||||
).pack(side="top", anchor="w")
|
||||
entries = row.child_widgets(
|
||||
tk.Entry,
|
||||
textvariable=variable,
|
||||
width=50,
|
||||
font=self._colors.font("label"),
|
||||
bg=self._colors.field_bg,
|
||||
fg=self._colors.fg,
|
||||
insertbackground=self._colors.fg,
|
||||
**self._colors.focus_kwargs(),
|
||||
)
|
||||
entries.pack(side="top", anchor="w", pady=self._colors.space("xs"))
|
||||
for entry in entries:
|
||||
disable_paste(entry)
|
||||
if focus:
|
||||
entries.first.focus_set()
|
||||
|
||||
def _add_label_text(
|
||||
self,
|
||||
parent: FrameGroup,
|
||||
*,
|
||||
label: str,
|
||||
height: int = 4,
|
||||
) -> WidgetGroup:
|
||||
"""Add a label + multi-line ``Text`` pair on every monitor.
|
||||
|
||||
Use this instead of building a bare ``tk.Text``: it un-traps Tab.
|
||||
Tk makes ``<Tab>`` insert a literal tab and refocus the widget, and
|
||||
binds ``<Shift-Tab>`` to nothing, so an untreated multi-line field is a
|
||||
keyboard dead end whose only exits (``Ctrl+Tab``/``Ctrl+Shift+Tab``) are
|
||||
not advertised anywhere. On a lock surface that means a user who tabs
|
||||
into it can never reach the submit button.
|
||||
"""
|
||||
row = parent.child_frame(bg=self._colors.bg)
|
||||
row.pack(pady=self._colors.space("sm"), fill="x")
|
||||
row.child_widgets(
|
||||
tk.Label,
|
||||
text=label,
|
||||
font=self._colors.font("label"),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
anchor="w",
|
||||
).pack(side="top", anchor="w")
|
||||
boxes = row.child_widgets(
|
||||
tk.Text,
|
||||
width=60,
|
||||
height=height,
|
||||
wrap="word",
|
||||
font=self._colors.font("label"),
|
||||
bg=self._colors.field_bg,
|
||||
fg=self._colors.fg,
|
||||
insertbackground=self._colors.fg,
|
||||
**self._colors.focus_kwargs(),
|
||||
)
|
||||
boxes.pack(side="top", anchor="w", pady=self._colors.space("xs"))
|
||||
for box in boxes:
|
||||
disable_paste(box)
|
||||
escape_text_tab_trap(box)
|
||||
return boxes
|
||||
|
||||
def _focus_first_button(self, row: FrameGroup) -> None:
|
||||
"""Give the primary surface's first button keyboard focus.
|
||||
|
||||
The lock takes a global grab and there is no other window on screen, so
|
||||
a surface that starts with *nothing* focused leaves the user pressing
|
||||
keys into the void with no visible ring to hint where focus went. The
|
||||
retry screen (TRY AGAIN / I'm sick / Log Manual Workout) had exactly
|
||||
that problem, because ``on_focus_ready`` is a documented no-op.
|
||||
"""
|
||||
for child in row.first.winfo_children():
|
||||
if child.winfo_class() == "Button":
|
||||
child.focus_set()
|
||||
return
|
||||
@ -2,11 +2,12 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock import bind_activate, escape_text_tab_trap
|
||||
from gatelock import bind_activate
|
||||
|
||||
from screen_locker._ui_form_fields import UIFormFieldsMixin, disable_paste
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
@ -15,20 +16,13 @@ if TYPE_CHECKING:
|
||||
|
||||
from screen_locker._surface_group import FrameGroup, WidgetGroup
|
||||
|
||||
|
||||
def disable_paste(widget: tk.Widget) -> None:
|
||||
"""Disable paste in a Tk Entry/Text widget.
|
||||
|
||||
Friction-only: a determined user can still bypass via xdotool, but the
|
||||
point is removing the trivial Ctrl+V shortcut so the user must
|
||||
actually type their input.
|
||||
"""
|
||||
for sequence in ("<<Paste>>", "<Control-v>", "<Control-V>", "<Button-2>"):
|
||||
with contextlib.suppress(tk.TclError, AttributeError):
|
||||
widget.bind(sequence, lambda _e: "break")
|
||||
# disable_paste moved to _ui_form_fields with the fields that use it; it is
|
||||
# re-exported here because _manual_workout_widgets and _sick_dialog import it
|
||||
# from this module.
|
||||
__all__ = ["UIWidgetsMixin", "disable_paste"]
|
||||
|
||||
|
||||
class UIWidgetsMixin:
|
||||
class UIWidgetsMixin(UIFormFieldsMixin):
|
||||
"""Mixin providing low-level widget creation helpers."""
|
||||
|
||||
def clear_container(self) -> None:
|
||||
@ -183,105 +177,3 @@ class UIWidgetsMixin:
|
||||
frame = self.container.child_frame(bg=self._colors.bg)
|
||||
frame.pack(pady=self._colors.space("sm"))
|
||||
return frame
|
||||
|
||||
def _add_label_entry(
|
||||
self,
|
||||
parent: FrameGroup,
|
||||
*,
|
||||
label: str,
|
||||
variable: tk.StringVar,
|
||||
focus: bool = False,
|
||||
) -> None:
|
||||
"""Add a label + single-line entry pair on every monitor.
|
||||
|
||||
All copies share one ``variable``, so typing on any screen is the
|
||||
same text everywhere and reading it back needs no idea which monitor
|
||||
the user actually used.
|
||||
|
||||
``focus`` gives the primary surface's copy the keyboard focus. Exactly
|
||||
one field per screen should ask: the lock takes a global grab, so with
|
||||
nothing focused the user's typing goes nowhere and there is no other
|
||||
window on screen to make that obvious.
|
||||
"""
|
||||
row = parent.child_frame(bg=self._colors.bg)
|
||||
row.pack(pady=self._colors.space("sm"), fill="x")
|
||||
row.child_widgets(
|
||||
tk.Label,
|
||||
text=label,
|
||||
font=self._colors.font("label"),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
anchor="w",
|
||||
).pack(side="top", anchor="w")
|
||||
entries = row.child_widgets(
|
||||
tk.Entry,
|
||||
textvariable=variable,
|
||||
width=50,
|
||||
font=self._colors.font("label"),
|
||||
bg=self._colors.field_bg,
|
||||
fg=self._colors.fg,
|
||||
insertbackground=self._colors.fg,
|
||||
**self._colors.focus_kwargs(),
|
||||
)
|
||||
entries.pack(side="top", anchor="w", pady=self._colors.space("xs"))
|
||||
for entry in entries:
|
||||
disable_paste(entry)
|
||||
if focus:
|
||||
entries.first.focus_set()
|
||||
|
||||
def _add_label_text(
|
||||
self,
|
||||
parent: FrameGroup,
|
||||
*,
|
||||
label: str,
|
||||
height: int = 4,
|
||||
) -> WidgetGroup:
|
||||
"""Add a label + multi-line ``Text`` pair on every monitor.
|
||||
|
||||
Use this instead of building a bare ``tk.Text``: it un-traps Tab.
|
||||
Tk makes ``<Tab>`` insert a literal tab and refocus the widget, and
|
||||
binds ``<Shift-Tab>`` to nothing, so an untreated multi-line field is a
|
||||
keyboard dead end whose only exits (``Ctrl+Tab``/``Ctrl+Shift+Tab``) are
|
||||
not advertised anywhere. On a lock surface that means a user who tabs
|
||||
into it can never reach the submit button.
|
||||
"""
|
||||
row = parent.child_frame(bg=self._colors.bg)
|
||||
row.pack(pady=self._colors.space("sm"), fill="x")
|
||||
row.child_widgets(
|
||||
tk.Label,
|
||||
text=label,
|
||||
font=self._colors.font("label"),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
anchor="w",
|
||||
).pack(side="top", anchor="w")
|
||||
boxes = row.child_widgets(
|
||||
tk.Text,
|
||||
width=60,
|
||||
height=height,
|
||||
wrap="word",
|
||||
font=self._colors.font("label"),
|
||||
bg=self._colors.field_bg,
|
||||
fg=self._colors.fg,
|
||||
insertbackground=self._colors.fg,
|
||||
**self._colors.focus_kwargs(),
|
||||
)
|
||||
boxes.pack(side="top", anchor="w", pady=self._colors.space("xs"))
|
||||
for box in boxes:
|
||||
disable_paste(box)
|
||||
escape_text_tab_trap(box)
|
||||
return boxes
|
||||
|
||||
def _focus_first_button(self, row: FrameGroup) -> None:
|
||||
"""Give the primary surface's first button keyboard focus.
|
||||
|
||||
The lock takes a global grab and there is no other window on screen, so
|
||||
a surface that starts with *nothing* focused leaves the user pressing
|
||||
keys into the void with no visible ring to hint where focus went. The
|
||||
retry screen (TRY AGAIN / I'm sick / Log Manual Workout) had exactly
|
||||
that problem, because ``on_focus_ready`` is a documented no-op.
|
||||
"""
|
||||
for child in row.first.winfo_children():
|
||||
if child.winfo_class() == "Button":
|
||||
child.focus_set()
|
||||
return
|
||||
|
||||
93
screen_locker/_wake_alarm.py
Normal file
93
screen_locker/_wake_alarm.py
Normal file
@ -0,0 +1,93 @@
|
||||
"""rtcwake wake-alarm scheduling, split out of the shutdown mixin.
|
||||
|
||||
Split out of :mod:`screen_locker._shutdown` to keep every file under the
|
||||
250-line cap. Composed back into ``ShutdownMixin`` there, so callers see no
|
||||
change.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import logging
|
||||
import subprocess
|
||||
|
||||
from screen_locker._constants import ALARM_DAYS, RTCWAKE_BIN, WAKE_AFTER_HOURS
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class WakeAlarmMixin:
|
||||
"""Schedules an RTC wake alarm for the next alarm day."""
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# rtcwake integration for weekend wake alarm
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _is_tomorrow_alarm_day() -> bool:
|
||||
"""Check if tomorrow is an alarm day."""
|
||||
tomorrow = datetime.now(tz=timezone.utc) + timedelta(days=1)
|
||||
return tomorrow.weekday() in ALARM_DAYS
|
||||
|
||||
@staticmethod
|
||||
def _compute_wake_timestamp() -> int:
|
||||
"""Compute the UTC epoch timestamp for the next wake alarm.
|
||||
|
||||
Returns:
|
||||
Epoch seconds WAKE_AFTER_HOURS from now.
|
||||
"""
|
||||
wake_time = datetime.now(tz=timezone.utc) + timedelta(
|
||||
hours=WAKE_AFTER_HOURS,
|
||||
)
|
||||
return calendar.timegm(wake_time.utctimetuple())
|
||||
|
||||
@staticmethod
|
||||
def _schedule_rtcwake() -> bool:
|
||||
"""Set rtcwake to power on the PC after WAKE_AFTER_HOURS.
|
||||
|
||||
Uses ``rtcwake -m disk`` to hibernate immediately while programming
|
||||
the RTC to restore power at wake_epoch. Hibernate is completely
|
||||
silent and dark (state written to swap file), making it suitable
|
||||
when the PC is in a bedroom.
|
||||
|
||||
Returns:
|
||||
True if rtcwake was set successfully, False otherwise.
|
||||
"""
|
||||
wake_epoch = WakeAlarmMixin._compute_wake_timestamp()
|
||||
cmd = [
|
||||
"/usr/bin/sudo",
|
||||
RTCWAKE_BIN,
|
||||
"-m",
|
||||
"disk",
|
||||
"-t",
|
||||
str(wake_epoch),
|
||||
]
|
||||
try:
|
||||
subprocess.run(
|
||||
cmd,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
except subprocess.SubprocessError as exc:
|
||||
_logger.warning("Failed to set rtcwake: %s", exc)
|
||||
return False
|
||||
_logger.info(
|
||||
"rtcwake set: PC will wake at epoch %d",
|
||||
wake_epoch,
|
||||
)
|
||||
return True
|
||||
|
||||
def schedule_wake_if_needed(self) -> bool:
|
||||
"""Schedule rtcwake if tomorrow is an alarm day.
|
||||
|
||||
Call this at shutdown time.
|
||||
|
||||
Returns:
|
||||
True if wake was scheduled, False if not needed or failed.
|
||||
"""
|
||||
if not self._is_tomorrow_alarm_day():
|
||||
_logger.info("Tomorrow is not an alarm day — skipping rtcwake")
|
||||
return False
|
||||
return self._schedule_rtcwake()
|
||||
@ -10,32 +10,53 @@ not an error -- unlike diet_guard, where sync is core to the app.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync import (
|
||||
CONFIG_FILE,
|
||||
ConfigError,
|
||||
FirebaseAuthError,
|
||||
GitHubSyncClient,
|
||||
Hlc,
|
||||
Record,
|
||||
RemoteStore,
|
||||
RemoteSyncError,
|
||||
firebase_client_for,
|
||||
mirror_client_for,
|
||||
)
|
||||
|
||||
from screen_locker._constants import (
|
||||
SYNC_REPO_NAME,
|
||||
SYNC_REPO_OWNER,
|
||||
SYNC_TIMEOUT_SECONDS,
|
||||
SYNC_TOKEN_FILE,
|
||||
)
|
||||
from screen_locker._manual_workout import MANUAL_WORKOUT_SYNC_KIND
|
||||
from screen_locker._sync_client import (
|
||||
read_sync_token,
|
||||
remote_client,
|
||||
sync_client,
|
||||
)
|
||||
from screen_locker._sync_records import (
|
||||
_is_manual_payload,
|
||||
_is_session_payload,
|
||||
_manual_records,
|
||||
_records_matching,
|
||||
_session_records,
|
||||
)
|
||||
from screen_locker._sync_retry import with_sync_retry
|
||||
|
||||
# Re-exported for callers (_manual_push) and for the autouse isolate_sync_token
|
||||
# fixture, which redirects SYNC_TOKEN_FILE on this module as well as on
|
||||
# _sync_client -- without both, a real token on the host leaks into the tests.
|
||||
__all__ = [
|
||||
"CONFIG_FILE",
|
||||
"SYNC_TOKEN_FILE",
|
||||
"_is_manual_payload",
|
||||
"_is_session_payload",
|
||||
"_manual_records",
|
||||
"_records_matching",
|
||||
"_session_records",
|
||||
"pull_all_manual_records",
|
||||
"pull_synced_workout",
|
||||
"read_sync_token",
|
||||
"remote_client",
|
||||
"sync_client",
|
||||
]
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
@ -45,40 +66,6 @@ _DEVICES_PREFIX = "screen-locker-sync/devices"
|
||||
_PAYLOAD_FIELD = "payload"
|
||||
|
||||
|
||||
def _is_manual_payload(payload: object) -> bool:
|
||||
"""True if a decoded sync payload is a manual-workout record."""
|
||||
return isinstance(payload, dict) and payload.get("kind") == MANUAL_WORKOUT_SYNC_KIND
|
||||
|
||||
|
||||
def _is_session_payload(payload: object) -> bool:
|
||||
"""True if a decoded sync payload is a completed StrongLifts session.
|
||||
|
||||
Identified by SHAPE -- the presence of ``exercises`` -- not by a ``kind``
|
||||
field, because the phone app's ``WorkoutSession.toJson()`` emits no ``kind``
|
||||
at all. Keying session detection on ``kind`` is what made real sessions
|
||||
invisible to the only reader that walks every device directory.
|
||||
|
||||
Shape-matching also excludes the PC-origin ``runnerup_verified`` /
|
||||
``phone_verified`` records that share these device logs: they are non-manual
|
||||
too, so "not manual" alone would hand a caller expecting ``exercises`` and
|
||||
``duration_seconds`` a record that has neither.
|
||||
"""
|
||||
return isinstance(payload, dict) and isinstance(payload.get("exercises"), list)
|
||||
|
||||
|
||||
def read_sync_token() -> str | None:
|
||||
"""Return the saved sync PAT, or None if sync isn't configured.
|
||||
|
||||
Unlike diet_guard's equivalent, an absent or empty token file is a
|
||||
normal state here -- sync is an optional primary channel, not something
|
||||
the app requires to function.
|
||||
"""
|
||||
if not SYNC_TOKEN_FILE.exists():
|
||||
return None
|
||||
token = SYNC_TOKEN_FILE.read_text().strip()
|
||||
return token or None
|
||||
|
||||
|
||||
def _merge_device_records(
|
||||
client: RemoteStore,
|
||||
extract: Callable[[str], dict[str, tuple[dict, Hlc]]],
|
||||
@ -156,80 +143,6 @@ def _merge_device_records(
|
||||
return merged
|
||||
|
||||
|
||||
def remote_client(github: RemoteStore) -> RemoteStore:
|
||||
"""Return the backend to read the phone's workout log from.
|
||||
|
||||
Firebase when ``~/.config/crdt-sync/`` is set up, with GitHub kept as a
|
||||
mirror so a phone that has not moved yet is still seen; GitHub alone
|
||||
otherwise. Both callers here are read-only pulls -- this side never pushes
|
||||
-- and :class:`MirrorSyncClient` reads the union of both, so a workout
|
||||
logged against either backend still counts.
|
||||
|
||||
The config file is checked before constructing anything, so an
|
||||
unconfigured machine never reaches the network.
|
||||
|
||||
Rolling back is deleting this function and passing ``github`` straight
|
||||
through: no data moves either way.
|
||||
"""
|
||||
if not CONFIG_FILE.is_file():
|
||||
return github
|
||||
try:
|
||||
return mirror_client_for("screen_locker", github)
|
||||
except (ConfigError, FirebaseAuthError, RemoteSyncError) as exc:
|
||||
_logger.warning(
|
||||
"Firebase unavailable, reading workouts via GitHub only: %s", exc
|
||||
)
|
||||
return github
|
||||
|
||||
|
||||
def sync_client() -> RemoteStore | None:
|
||||
"""Return the configured read client, or None if sync is set up nowhere.
|
||||
|
||||
A GitHub token is no longer required: Firebase has been the primary backend
|
||||
since eb4ff01, so a Firebase-only machine must still sync. Previously this
|
||||
module returned early whenever the PAT was missing, reporting "sync is OFF"
|
||||
on a machine whose sync was working perfectly -- a false negative that hid
|
||||
a live backend behind a legacy credential check.
|
||||
|
||||
GitHub is used alone when only the PAT exists, Firebase alone when only
|
||||
``~/.config/crdt-sync/`` exists, and the mirrored union when both do.
|
||||
``None`` means neither is configured, which stays a benign, expected state.
|
||||
"""
|
||||
token = read_sync_token()
|
||||
github = (
|
||||
GitHubSyncClient(
|
||||
SYNC_REPO_OWNER,
|
||||
SYNC_REPO_NAME,
|
||||
token,
|
||||
timeout_seconds=SYNC_TIMEOUT_SECONDS,
|
||||
)
|
||||
if token is not None
|
||||
else None
|
||||
)
|
||||
if github is not None:
|
||||
return remote_client(github)
|
||||
if not CONFIG_FILE.is_file():
|
||||
_logger.warning(
|
||||
"Cannot pull synced workouts: no sync token at %s and no Firebase "
|
||||
"config at %s — sync is OFF, so only ADB/HTTP can verify a phone "
|
||||
"workout and phone-logged workouts will NOT count here",
|
||||
SYNC_TOKEN_FILE,
|
||||
CONFIG_FILE,
|
||||
)
|
||||
return None
|
||||
try:
|
||||
return firebase_client_for("screen_locker")
|
||||
except (ConfigError, FirebaseAuthError, RemoteSyncError) as exc:
|
||||
_logger.warning(
|
||||
"Firebase is configured at %s but unusable, and there is no GitHub "
|
||||
"token at %s to fall back to: %s — pulling NO synced workouts",
|
||||
CONFIG_FILE,
|
||||
SYNC_TOKEN_FILE,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def pull_synced_workout() -> tuple[dict | None, str | None]:
|
||||
"""Return ``(data, error)``: the last-synced StrongLifts session, if any.
|
||||
|
||||
@ -269,51 +182,6 @@ def pull_synced_workout() -> tuple[dict | None, str | None]:
|
||||
return payload, None
|
||||
|
||||
|
||||
def _session_records(log_json: str) -> dict[str, tuple[dict, Hlc]]:
|
||||
"""Return ``{record_id: (payload, hlc)}`` for session records in a log blob.
|
||||
|
||||
Raises the same decode errors as :func:`_manual_records`; callers treat a
|
||||
corrupt device log as "no sessions from that device".
|
||||
"""
|
||||
return _records_matching(log_json, _is_session_payload)
|
||||
|
||||
|
||||
def _records_matching(
|
||||
log_json: str, predicate: Callable[[object], bool]
|
||||
) -> dict[str, tuple[dict, Hlc]]:
|
||||
"""Return ``{record_id: (payload, hlc)}`` for payloads passing ``predicate``.
|
||||
|
||||
Raises:
|
||||
TypeError: If the top-level JSON isn't an object or a record's shape
|
||||
doesn't match what :meth:`Record.from_dict` expects.
|
||||
KeyError: If a record is missing an expected key.
|
||||
ValueError: Via ``json.loads`` or :meth:`crdt_sync.Hlc.from_str`.
|
||||
"""
|
||||
raw = json.loads(log_json)
|
||||
if not isinstance(raw, dict):
|
||||
msg = f"top-level sync payload is not a JSON object: {raw!r}"
|
||||
raise TypeError(msg)
|
||||
result: dict[str, tuple[dict, Hlc]] = {}
|
||||
for data in raw.values():
|
||||
record = Record.from_dict(data)
|
||||
field = record.fields.get(_PAYLOAD_FIELD)
|
||||
if field is None:
|
||||
continue
|
||||
payload, hlc = field
|
||||
if predicate(payload):
|
||||
result[record.id] = (payload, hlc)
|
||||
return result
|
||||
|
||||
|
||||
def _manual_records(log_json: str) -> dict[str, tuple[dict, Hlc]]:
|
||||
"""Return ``{record_id: (payload, hlc)}`` for manual records in a log blob.
|
||||
|
||||
Raises the same decode errors as :func:`_records_matching`; callers treat a
|
||||
corrupt device log as "no manual records from that device".
|
||||
"""
|
||||
return _records_matching(log_json, _is_manual_payload)
|
||||
|
||||
|
||||
def pull_all_manual_records() -> list[tuple[str, dict]]:
|
||||
"""Return all synced manual-workout records across every device log.
|
||||
|
||||
|
||||
@ -33,15 +33,11 @@ from gatelock import LockConfig
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
|
||||
from screen_locker._status_data import (
|
||||
DayStatus,
|
||||
ManualWorkoutBudgetStatus,
|
||||
ShutdownProjection,
|
||||
SickBudgetStatus,
|
||||
StatusSnapshot,
|
||||
WeeklySummary,
|
||||
format_summary_line,
|
||||
gather_status,
|
||||
)
|
||||
from screen_locker._status_sections import StatusSectionsMixin
|
||||
from screen_locker._status_view_verify import PhoneCheckMixin, _make_bare_verifier
|
||||
from screen_locker._surface_group import FrameGroup
|
||||
from screen_locker._sync_status import format_sync_line, gather_sync_status
|
||||
@ -55,7 +51,6 @@ if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import Future
|
||||
|
||||
from screen_locker._compliance_state import LockExplanation
|
||||
from screen_locker._temperature import TemperatureCheck
|
||||
from screen_locker.screen_lock import ScreenLocker
|
||||
|
||||
@ -68,6 +63,7 @@ class StatusWindow(
|
||||
ManualWorkoutDialogMixin,
|
||||
TemperatureStatusMixin,
|
||||
PhoneCheckMixin,
|
||||
StatusSectionsMixin,
|
||||
):
|
||||
"""Thin Tk view over a :class:`StatusSnapshot`.
|
||||
|
||||
@ -169,152 +165,6 @@ class StatusWindow(
|
||||
width=8,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
|
||||
def _section_today(self, parent: tk.Widget, day: DayStatus) -> None:
|
||||
"""Render today's outcome."""
|
||||
del parent
|
||||
mark = "✓" if day.counted else ("😷" if day.is_sick_day else "—")
|
||||
entry_str = ", ".join(day.entry_types) or (
|
||||
"sick day" if day.is_sick_day else "no entry yet"
|
||||
)
|
||||
self._text(
|
||||
f"{mark} Today ({day.label}): {entry_str}",
|
||||
role="body",
|
||||
color=self._colors.success if day.counted else self._colors.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.muted, pad="xs")
|
||||
|
||||
def _section_week(self, parent: tk.Widget, week: WeeklySummary) -> None:
|
||||
"""Render this ISO week's per-day breakdown and totals."""
|
||||
del parent
|
||||
self._label(
|
||||
f"This Week: {week.counted_count}/{week.minimum}", role="body", pad="sm"
|
||||
)
|
||||
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.muted,
|
||||
pad="xs",
|
||||
)
|
||||
if week.remaining > 0:
|
||||
self._text(
|
||||
f"Need {week.remaining} more this week.",
|
||||
role="body",
|
||||
color=self._colors.warning,
|
||||
)
|
||||
elif week.extra > 0:
|
||||
self._text(
|
||||
f"{week.extra} above the weekly minimum!",
|
||||
role="body",
|
||||
color=self._colors.success,
|
||||
)
|
||||
|
||||
def _section_lock_explanation(
|
||||
self, parent: tk.Widget, expl: LockExplanation
|
||||
) -> None:
|
||||
"""Render why the lock did/didn't fire today, plus its evaluation trace."""
|
||||
del parent
|
||||
self._label("Why the lock did/didn't fire", role="body", pad="sm")
|
||||
self._text(
|
||||
expl.reason,
|
||||
role="body",
|
||||
color=self._colors.danger if expl.fired else self._colors.success,
|
||||
)
|
||||
if expl.auto_upgrade.would_attempt:
|
||||
self._text(
|
||||
f"Pending auto-upgrade: {expl.auto_upgrade.reason}",
|
||||
role="label",
|
||||
color=self._colors.warning,
|
||||
)
|
||||
|
||||
def _section_sick_budget(self, parent: tk.Widget, sick: SickBudgetStatus) -> None:
|
||||
"""Render rolling sick-day budget usage."""
|
||||
del parent
|
||||
self._label("Sick Budget", role="body", pad="sm")
|
||||
self._text(
|
||||
f"{sick.used_7d}/{sick.budget_7d} week · {sick.used_30d}/{sick.budget_30d} "
|
||||
f"month · {sick.used_90d}/{sick.budget_90d} quarter · debt {sick.debt}",
|
||||
role="body",
|
||||
color=self._colors.danger if sick.exhausted else self._colors.muted,
|
||||
)
|
||||
|
||||
def _section_manual_workout_budget(
|
||||
self, parent: tk.Widget, manual: ManualWorkoutBudgetStatus
|
||||
) -> None:
|
||||
"""Render rolling manual-workout budget usage."""
|
||||
del parent
|
||||
self._label("Manual Workout Budget", role="body", pad="sm")
|
||||
self._text(
|
||||
f"{manual.used_7d}/{manual.budget_7d} week · "
|
||||
f"{manual.used_30d}/{manual.budget_30d} month",
|
||||
role="body",
|
||||
color=self._colors.danger if manual.exhausted else self._colors.muted,
|
||||
)
|
||||
|
||||
def _section_sync_backend(self, parent: tk.Widget) -> None:
|
||||
"""Render which backend this machine syncs through.
|
||||
|
||||
Read from local state only (see :mod:`screen_locker._sync_status`), so
|
||||
opening or refreshing the window never makes a network call. Coloured
|
||||
by ``healthy`` rather than by backend: "configured but never pushed"
|
||||
looks fine everywhere else and produces no data, which is exactly the
|
||||
state worth surfacing here.
|
||||
"""
|
||||
del parent
|
||||
status = gather_sync_status()
|
||||
self._label("Sync backend", role="body", pad="sm")
|
||||
self._text(
|
||||
format_sync_line(status),
|
||||
role="body",
|
||||
color=self._colors.muted if status.healthy else self._colors.danger,
|
||||
)
|
||||
|
||||
def _section_shutdown(
|
||||
self, parent: tk.Widget, shutdown: ShutdownProjection
|
||||
) -> None:
|
||||
"""Render tonight's live config, rest-of-week, and next-week preview."""
|
||||
del parent
|
||||
self._label("Shutdown Time", role="body", pad="sm")
|
||||
if shutdown.tonight is not None:
|
||||
mon_wed_hour, thu_sun_hour, _morning = shutdown.tonight
|
||||
self._text(
|
||||
f"Live config — Mon-Wed {mon_wed_hour:02d}:00, "
|
||||
f"Thu-Sun {thu_sun_hour:02d}:00",
|
||||
role="body",
|
||||
)
|
||||
else:
|
||||
self._text(
|
||||
"Live shutdown config unavailable.",
|
||||
role="body",
|
||||
color=self._colors.warning,
|
||||
)
|
||||
# Rest-of-week/next-week/explanation are speculative annotations, not
|
||||
# the section's primary content -- a deliberate caption-sized
|
||||
# exception to the 16px floor, all sharing one muted tone instead of
|
||||
# three unrelated ad hoc grays.
|
||||
rest_line = ", ".join(
|
||||
f"{d.label} {d.hour:02d}:00" for d in shutdown.rest_of_week
|
||||
)
|
||||
self._text(
|
||||
f"Rest of week: {rest_line}", role="caption", color=self._colors.muted
|
||||
)
|
||||
next_line = ", ".join(
|
||||
f"{d.label} {d.hour:02d}:00" for d in shutdown.next_week_preview
|
||||
)
|
||||
self._text(
|
||||
f"Next week (speculative): {next_line}",
|
||||
role="caption",
|
||||
color=self._colors.muted,
|
||||
)
|
||||
self._text(shutdown.explanation, role="caption", color=self._colors.muted)
|
||||
|
||||
def _on_refresh_clicked(self) -> None:
|
||||
"""Clear any stale phone-check/credit/temperature results, re-check both."""
|
||||
self._phone_check_result = None
|
||||
|
||||
64
screen_locker/tests/_opt_in_fixtures.py
Normal file
64
screen_locker/tests/_opt_in_fixtures.py
Normal file
@ -0,0 +1,64 @@
|
||||
"""Opt-in (non-autouse) fixtures for the screen_locker tests.
|
||||
|
||||
Split out of ``conftest.py`` to keep every file under the 250-line cap. These
|
||||
are re-imported there, which is what keeps pytest discovering them by name --
|
||||
a fixture is only visible to tests if it is reachable from ``conftest.py``.
|
||||
|
||||
Only fixtures a test must *request* live here. Every ``autouse`` fixture stays
|
||||
in ``conftest.py``: pytest applies autouse fixtures from conftest only, so one
|
||||
moved here would silently stop running and take its safety guard with it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import ExitStack
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from screen_locker.tests._tk_mocks import _TK_MODULES, _make_mock_tk
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_tk() -> Generator[MagicMock]:
|
||||
"""Mock the ``tkinter`` module across every UI module for display-free tests.
|
||||
|
||||
Patches the same single mock into all ``_TK_MODULES`` so assertions on
|
||||
``mock_tk.Button`` capture widgets created by any of the split UI mixins
|
||||
(``_ui_widgets``, ``_sick_dialog``, ...), not just ``screen_lock``.
|
||||
"""
|
||||
mock = _make_mock_tk()
|
||||
with ExitStack() as stack:
|
||||
for module in _TK_MODULES:
|
||||
stack.enter_context(patch(f"{module}.tk", mock))
|
||||
stack.enter_context(
|
||||
patch(
|
||||
"screen_locker.screen_lock.GateRoot",
|
||||
return_value=mock.Tk.return_value,
|
||||
)
|
||||
)
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_sys_exit() -> Generator[MagicMock]:
|
||||
"""Mock sys.exit to prevent test termination."""
|
||||
with patch("screen_locker.screen_lock.sys.exit") as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _mock_sys_exit(mock_sys_exit: MagicMock) -> MagicMock:
|
||||
"""Alias for mock_sys_exit when the return value is unused."""
|
||||
return mock_sys_exit
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_log_file(tmp_path: Path) -> Path:
|
||||
"""Create a temporary log file path."""
|
||||
return tmp_path / "workout_log.json"
|
||||
58
screen_locker/tests/_tk_mocks.py
Normal file
58
screen_locker/tests/_tk_mocks.py
Normal file
@ -0,0 +1,58 @@
|
||||
"""The tkinter mock and the list of modules it must be patched into.
|
||||
|
||||
Split out of ``conftest.py`` to keep every file under the 250-line cap.
|
||||
|
||||
Only this scaffolding moved: every ``autouse`` fixture stays in ``conftest.py``,
|
||||
because pytest collects autouse fixtures from conftest only -- one moved here
|
||||
would simply stop running, and the suite would still pass while the guard it
|
||||
provides was gone.
|
||||
|
||||
When a new module imports ``tkinter as tk`` and calls it, add it to
|
||||
``_TK_MODULES`` below or its widgets are built on a real display.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
# Every module that imports ``tkinter as tk`` and calls it directly. The UI is
|
||||
# split across these, so each ``tk`` must be patched — so no test touches a real
|
||||
# display and a ``mock_tk`` holder sees widgets made on that same mock.
|
||||
_TK_MODULES = (
|
||||
"screen_locker.screen_lock",
|
||||
"screen_locker._sick_dialog",
|
||||
"screen_locker._manual_workout_dialog",
|
||||
"screen_locker._manual_workout_sport_fields",
|
||||
"screen_locker._manual_workout_widgets",
|
||||
"screen_locker._ui_form_fields",
|
||||
"screen_locker._ui_widgets",
|
||||
"screen_locker._window_setup",
|
||||
"screen_locker.status_view",
|
||||
"screen_locker._heat_skip",
|
||||
"screen_locker._surface_group",
|
||||
# The scroll viewport the lock surfaces are built from lives in gatelock
|
||||
# and imports tkinter independently, so it needs the same mock -- otherwise
|
||||
# container.first is a *real* tk.Frame whose winfo_children() cannot be
|
||||
# stubbed, and every surface assertion breaks.
|
||||
"gatelock._scrollable",
|
||||
)
|
||||
_VT_SHUTIL = "gatelock._vt.shutil"
|
||||
_VT_SUBPROCESS = "gatelock._vt.subprocess"
|
||||
|
||||
|
||||
def _make_mock_tk() -> MagicMock:
|
||||
"""Build a MagicMock that stands in for the ``tkinter`` module."""
|
||||
mock = MagicMock()
|
||||
mock_root = MagicMock()
|
||||
mock_root.winfo_screenwidth.return_value = 1920
|
||||
mock_root.winfo_screenheight.return_value = 1080
|
||||
mock.Tk.return_value = mock_root
|
||||
|
||||
mock_frame = MagicMock()
|
||||
mock_frame.winfo_children.return_value = []
|
||||
mock.Frame.return_value = mock_frame
|
||||
|
||||
# Keep real TclError so ``except tk.TclError`` still works.
|
||||
mock.TclError = tk.TclError
|
||||
return mock
|
||||
@ -14,7 +14,6 @@ from contextlib import ExitStack
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@ -32,60 +31,39 @@ from screen_locker.tests._locker_factories import (
|
||||
create_locker_early_bird,
|
||||
create_locker_relaxed_day,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator, Iterator
|
||||
|
||||
|
||||
# Every module that imports ``tkinter as tk`` and calls it directly. The UI is
|
||||
# split across these, so each ``tk`` must be patched — so no test touches a real
|
||||
# display and a ``mock_tk`` holder sees widgets made on that same mock.
|
||||
_TK_MODULES = (
|
||||
"screen_locker.screen_lock",
|
||||
"screen_locker._sick_dialog",
|
||||
"screen_locker._manual_workout_dialog",
|
||||
"screen_locker._manual_workout_widgets",
|
||||
"screen_locker._ui_widgets",
|
||||
"screen_locker._window_setup",
|
||||
"screen_locker.status_view",
|
||||
"screen_locker._heat_skip",
|
||||
"screen_locker._surface_group",
|
||||
# The scroll viewport the lock surfaces are built from lives in gatelock
|
||||
# and imports tkinter independently, so it needs the same mock -- otherwise
|
||||
# container.first is a *real* tk.Frame whose winfo_children() cannot be
|
||||
# stubbed, and every surface assertion breaks.
|
||||
"gatelock._scrollable",
|
||||
from screen_locker.tests._opt_in_fixtures import (
|
||||
_mock_sys_exit,
|
||||
mock_sys_exit,
|
||||
mock_tk,
|
||||
temp_log_file,
|
||||
)
|
||||
from screen_locker.tests._tk_mocks import (
|
||||
_TK_MODULES,
|
||||
_VT_SHUTIL,
|
||||
_VT_SUBPROCESS,
|
||||
_make_mock_tk,
|
||||
)
|
||||
|
||||
# Re-exported so pytest still resolves these by name: a fixture defined in a
|
||||
# sibling module is only visible to tests once conftest imports it. __all__
|
||||
# keeps ruff from pruning them as unused.
|
||||
__all__ = [
|
||||
"FAKE_OUTPUTS",
|
||||
"TWO_OUTPUTS",
|
||||
"_hermetic_gatelock",
|
||||
"_make_locker",
|
||||
"_mock_sys_exit",
|
||||
"create_locker",
|
||||
"create_locker_early_bird",
|
||||
"create_locker_relaxed_day",
|
||||
"dual_output",
|
||||
"mock_sys_exit",
|
||||
"mock_tk",
|
||||
"temp_log_file",
|
||||
]
|
||||
|
||||
_VT_SHUTIL = "gatelock._vt.shutil"
|
||||
_VT_SUBPROCESS = "gatelock._vt.subprocess"
|
||||
|
||||
|
||||
def _make_mock_tk() -> MagicMock:
|
||||
"""Build a MagicMock that stands in for the ``tkinter`` module."""
|
||||
mock = MagicMock()
|
||||
mock_root = MagicMock()
|
||||
mock_root.winfo_screenwidth.return_value = 1920
|
||||
mock_root.winfo_screenheight.return_value = 1080
|
||||
mock.Tk.return_value = mock_root
|
||||
|
||||
mock_frame = MagicMock()
|
||||
mock_frame.winfo_children.return_value = []
|
||||
mock.Frame.return_value = mock_frame
|
||||
|
||||
# Keep real TclError so ``except tk.TclError`` still works.
|
||||
mock.TclError = tk.TclError
|
||||
return mock
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator, Iterator
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@ -138,7 +116,10 @@ def _block_real_network() -> Iterator[None]:
|
||||
reach the real network. Tests needing a real probe patch it locally.
|
||||
"""
|
||||
targets = (
|
||||
"screen_locker._phone_verification.socket.create_connection",
|
||||
# The subnet probes moved out of _phone_verification when it was split;
|
||||
# both new homes must be blocked or a test reaches the real network.
|
||||
"screen_locker._adb_transport.socket.create_connection",
|
||||
"screen_locker._http_workout_fetch.socket.create_connection",
|
||||
"screen_locker._temperature.urllib.request.urlopen",
|
||||
)
|
||||
with ExitStack() as stack:
|
||||
@ -147,55 +128,56 @@ def _block_real_network() -> Iterator[None]:
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_sick_history(tmp_path: Path) -> Iterator[None]:
|
||||
"""Redirect SICK_HISTORY_FILE to tmp_path so tests cannot touch real state."""
|
||||
target = tmp_path / "sick_history.json"
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._sick_tracker.SICK_HISTORY_FILE",
|
||||
target,
|
||||
# Each on-disk state path, and every module that bound it by value at import
|
||||
# time. All of them need patching, not just the _constants source -- a missed
|
||||
# binding lets a test write to the real file.
|
||||
_ISOLATED_STATE: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
(
|
||||
"sick_history.json",
|
||||
("_sick_tracker.SICK_HISTORY_FILE", "_constants.SICK_HISTORY_FILE"),
|
||||
),
|
||||
(
|
||||
"early_bird_pending.json",
|
||||
(
|
||||
"_early_bird.EARLY_BIRD_PENDING_FILE",
|
||||
"_constants.EARLY_BIRD_PENDING_FILE",
|
||||
),
|
||||
patch(
|
||||
"screen_locker._constants.SICK_HISTORY_FILE",
|
||||
target,
|
||||
),
|
||||
(
|
||||
"extra_benefits_state.json",
|
||||
(
|
||||
"_constants.EXTRA_BENEFITS_FILE",
|
||||
"_startup_checks.EXTRA_BENEFITS_FILE",
|
||||
"_sync_mixin.EXTRA_BENEFITS_FILE",
|
||||
"_early_bird.EXTRA_BENEFITS_FILE",
|
||||
"_status.EXTRA_BENEFITS_FILE",
|
||||
),
|
||||
):
|
||||
yield
|
||||
),
|
||||
(
|
||||
"sick_day_state.json",
|
||||
(
|
||||
"_constants.SICK_DAY_STATE_FILE",
|
||||
"_startup_checks.SICK_DAY_STATE_FILE",
|
||||
"_shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
),
|
||||
),
|
||||
("scheduled_skips.json", ("_log_mixin.SCHEDULED_SKIPS_FILE",)),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_early_bird_pending(tmp_path: Path) -> Iterator[None]:
|
||||
"""Redirect EARLY_BIRD_PENDING_FILE to tmp_path so tests use a clean file."""
|
||||
target = tmp_path / "early_bird_pending.json"
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._early_bird.EARLY_BIRD_PENDING_FILE",
|
||||
target,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._constants.EARLY_BIRD_PENDING_FILE",
|
||||
target,
|
||||
),
|
||||
):
|
||||
yield
|
||||
def _isolate_state_files(tmp_path: Path) -> Iterator[None]:
|
||||
"""Redirect every on-disk state path to tmp_path for every test.
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_extra_benefits(tmp_path: Path) -> Iterator[None]:
|
||||
"""Redirect EXTRA_BENEFITS_FILE to tmp_path so tests cannot touch real state.
|
||||
|
||||
Bound by value into several modules at import time, so every bound name
|
||||
needs patching individually — not just the ``_constants`` source.
|
||||
Stays in conftest.py and stays autouse: pytest only applies autouse
|
||||
fixtures declared here, so moving this to a sibling module would leave
|
||||
tests writing to the user's real state files while still passing.
|
||||
"""
|
||||
target = tmp_path / "extra_benefits_state.json"
|
||||
with (
|
||||
patch("screen_locker._constants.EXTRA_BENEFITS_FILE", target),
|
||||
patch("screen_locker._startup_checks.EXTRA_BENEFITS_FILE", target),
|
||||
patch("screen_locker._sync_mixin.EXTRA_BENEFITS_FILE", target),
|
||||
patch("screen_locker._early_bird.EXTRA_BENEFITS_FILE", target),
|
||||
patch("screen_locker._status.EXTRA_BENEFITS_FILE", target),
|
||||
):
|
||||
with ExitStack() as stack:
|
||||
for filename, bindings in _ISOLATED_STATE:
|
||||
target = tmp_path / filename
|
||||
for binding in bindings:
|
||||
stack.enter_context(patch(f"screen_locker.{binding}", target))
|
||||
yield
|
||||
|
||||
|
||||
@ -222,28 +204,6 @@ def _isolate_shutdown_base(tmp_path: Path) -> Iterator[None]:
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_sick_day_state(tmp_path: Path) -> Iterator[None]:
|
||||
"""Redirect SICK_DAY_STATE_FILE to tmp_path so tests cannot touch real state."""
|
||||
target = tmp_path / "sick_day_state.json"
|
||||
with (
|
||||
patch("screen_locker._constants.SICK_DAY_STATE_FILE", target),
|
||||
patch("screen_locker._startup_checks.SICK_DAY_STATE_FILE", target),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_scheduled_skips(tmp_path: Path) -> Iterator[None]:
|
||||
"""Redirect SCHEDULED_SKIPS_FILE to tmp_path so tests use a clean file."""
|
||||
target = tmp_path / "scheduled_skips.json"
|
||||
with patch(
|
||||
"screen_locker._log_mixin.SCHEDULED_SKIPS_FILE",
|
||||
target,
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _mock_weekly_logic() -> Iterator[None]:
|
||||
"""Default to Fri-Mon enforcement with weekly minimum not yet met.
|
||||
@ -266,46 +226,6 @@ def _mock_weekly_logic() -> Iterator[None]:
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_tk() -> Generator[MagicMock]:
|
||||
"""Mock the ``tkinter`` module across every UI module for display-free tests.
|
||||
|
||||
Patches the same single mock into all ``_TK_MODULES`` so assertions on
|
||||
``mock_tk.Button`` capture widgets created by any of the split UI mixins
|
||||
(``_ui_widgets``, ``_sick_dialog``, ...), not just ``screen_lock``.
|
||||
"""
|
||||
mock = _make_mock_tk()
|
||||
with ExitStack() as stack:
|
||||
for module in _TK_MODULES:
|
||||
stack.enter_context(patch(f"{module}.tk", mock))
|
||||
stack.enter_context(
|
||||
patch(
|
||||
"screen_locker.screen_lock.GateRoot",
|
||||
return_value=mock.Tk.return_value,
|
||||
)
|
||||
)
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_sys_exit() -> Generator[MagicMock]:
|
||||
"""Mock sys.exit to prevent test termination."""
|
||||
with patch("screen_locker.screen_lock.sys.exit") as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _mock_sys_exit(mock_sys_exit: MagicMock) -> MagicMock:
|
||||
"""Alias for mock_sys_exit when the return value is unused."""
|
||||
return mock_sys_exit
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_log_file(tmp_path: Path) -> Path:
|
||||
"""Create a temporary log file path."""
|
||||
return tmp_path / "workout_log.json"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_real_firebase_config(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Point the Firebase config at a path that does not exist.
|
||||
@ -316,8 +236,9 @@ def _no_real_firebase_config(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
assert against live data instead of their own fakes. Tests that want the
|
||||
Firebase path point it back at a file they control.
|
||||
"""
|
||||
from screen_locker import _workout_sync
|
||||
# CONFIG_FILE is read by remote_client, which lives in _sync_client since
|
||||
# _workout_sync was split. Patching the old module would leave the real
|
||||
# config in play and the sync tests would assert against live data.
|
||||
from screen_locker import _sync_client
|
||||
|
||||
monkeypatch.setattr(
|
||||
_workout_sync, "CONFIG_FILE", Path("/nonexistent/firebase.json")
|
||||
)
|
||||
monkeypatch.setattr(_sync_client, "CONFIG_FILE", Path("/nonexistent/firebase.json"))
|
||||
|
||||
@ -26,7 +26,7 @@ class TestRunAdb:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
mock_result = MagicMock(returncode=0, stdout="ok\n")
|
||||
with patch(
|
||||
"screen_locker._phone_verification.subprocess.run",
|
||||
"screen_locker._adb_transport.subprocess.run",
|
||||
return_value=mock_result,
|
||||
) as mock_run:
|
||||
success, output = locker._run_adb(["devices"])
|
||||
@ -45,7 +45,7 @@ class TestRunAdb:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
mock_result = MagicMock(returncode=1, stdout="")
|
||||
with patch(
|
||||
"screen_locker._phone_verification.subprocess.run",
|
||||
"screen_locker._adb_transport.subprocess.run",
|
||||
return_value=mock_result,
|
||||
):
|
||||
success, _output = locker._run_adb(["devices"])
|
||||
@ -61,7 +61,7 @@ class TestRunAdb:
|
||||
"""Test ADB binary not found."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with patch(
|
||||
"screen_locker._phone_verification.subprocess.run",
|
||||
"screen_locker._adb_transport.subprocess.run",
|
||||
side_effect=FileNotFoundError("adb not found"),
|
||||
):
|
||||
success, output = locker._run_adb(["devices"])
|
||||
@ -78,7 +78,7 @@ class TestRunAdb:
|
||||
"""Test ADB OSError."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with patch(
|
||||
"screen_locker._phone_verification.subprocess.run",
|
||||
"screen_locker._adb_transport.subprocess.run",
|
||||
side_effect=OSError("permission denied"),
|
||||
):
|
||||
success, output = locker._run_adb(["devices"])
|
||||
@ -95,7 +95,7 @@ class TestRunAdb:
|
||||
"""Test ADB command timeout."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with patch(
|
||||
"screen_locker._phone_verification.subprocess.run",
|
||||
"screen_locker._adb_transport.subprocess.run",
|
||||
side_effect=subprocess.TimeoutExpired("adb", 15),
|
||||
):
|
||||
success, output = locker._run_adb(["devices"])
|
||||
|
||||
@ -79,7 +79,7 @@ class TestHasLoggedToday:
|
||||
log_file = tmp_path / "log.json"
|
||||
log_file.write_text(json.dumps({_today(): {"hmac": "sig"}}))
|
||||
with patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=True
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac", return_value=True
|
||||
):
|
||||
assert has_logged_today(log_file) is True
|
||||
|
||||
@ -89,10 +89,12 @@ class TestHasLoggedToday:
|
||||
log_file.write_text(json.dumps({_today(): {}}))
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.compute_entry_hmac", return_value=None
|
||||
"screen_locker._compliance_predicates.compute_entry_hmac",
|
||||
return_value=None,
|
||||
),
|
||||
):
|
||||
assert has_logged_today(log_file) is True
|
||||
@ -103,10 +105,12 @@ class TestHasLoggedToday:
|
||||
log_file.write_text(json.dumps({_today(): {}}))
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.compute_entry_hmac", return_value="sig"
|
||||
"screen_locker._compliance_predicates.compute_entry_hmac",
|
||||
return_value="sig",
|
||||
),
|
||||
):
|
||||
assert has_logged_today(log_file) is False
|
||||
@ -117,10 +121,12 @@ class TestHasLoggedToday:
|
||||
log_file.write_text(json.dumps({_today(): {"hmac": "tampered"}}))
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.compute_entry_hmac", return_value=None
|
||||
"screen_locker._compliance_predicates.compute_entry_hmac",
|
||||
return_value=None,
|
||||
),
|
||||
):
|
||||
assert has_logged_today(log_file) is False
|
||||
@ -156,7 +162,7 @@ class TestIsEarlyBirdPending:
|
||||
pending_file = tmp_path / "pending.json"
|
||||
pending_file.write_text(json.dumps({"date": _today(), "hmac": "sig"}))
|
||||
with patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=True
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac", return_value=True
|
||||
):
|
||||
assert is_early_bird_pending(pending_file) is True
|
||||
|
||||
@ -166,10 +172,12 @@ class TestIsEarlyBirdPending:
|
||||
pending_file.write_text(json.dumps({"date": _today()}))
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.compute_entry_hmac", return_value=None
|
||||
"screen_locker._compliance_predicates.compute_entry_hmac",
|
||||
return_value=None,
|
||||
),
|
||||
):
|
||||
assert is_early_bird_pending(pending_file) is True
|
||||
@ -180,10 +188,12 @@ class TestIsEarlyBirdPending:
|
||||
pending_file.write_text(json.dumps({"date": _today()}))
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.compute_entry_hmac", return_value="sig"
|
||||
"screen_locker._compliance_predicates.compute_entry_hmac",
|
||||
return_value="sig",
|
||||
),
|
||||
):
|
||||
assert is_early_bird_pending(pending_file) is False
|
||||
@ -194,10 +204,12 @@ class TestIsEarlyBirdPending:
|
||||
pending_file.write_text(json.dumps({"date": _today(), "hmac": "bad"}))
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.compute_entry_hmac", return_value=None
|
||||
"screen_locker._compliance_predicates.compute_entry_hmac",
|
||||
return_value=None,
|
||||
),
|
||||
):
|
||||
assert is_early_bird_pending(pending_file) is False
|
||||
|
||||
@ -49,7 +49,7 @@ class TestExplainLockDecision:
|
||||
)
|
||||
now = datetime.now(tz=timezone.utc).astimezone().replace(hour=6, minute=0)
|
||||
with patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=True
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac", return_value=True
|
||||
):
|
||||
result = explain_lock_decision(
|
||||
**files,
|
||||
@ -71,7 +71,7 @@ class TestExplainLockDecision:
|
||||
)
|
||||
now = datetime.now(tz=timezone.utc).astimezone().replace(hour=10, minute=0)
|
||||
with patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=True
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac", return_value=True
|
||||
):
|
||||
result = explain_lock_decision(
|
||||
**files,
|
||||
@ -106,7 +106,7 @@ class TestExplainLockDecision:
|
||||
files = self._files(tmp_path)
|
||||
files["log_file"].write_text(json.dumps({_today(): {"hmac": "sig"}}))
|
||||
with patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=True
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac", return_value=True
|
||||
):
|
||||
result = explain_lock_decision(
|
||||
**files,
|
||||
|
||||
@ -87,10 +87,12 @@ class TestIsEarlyBirdPending:
|
||||
with (
|
||||
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.compute_entry_hmac", return_value="sig"
|
||||
"screen_locker._compliance_predicates.compute_entry_hmac",
|
||||
return_value="sig",
|
||||
),
|
||||
):
|
||||
assert locker._is_early_bird_pending() is False
|
||||
@ -109,7 +111,8 @@ class TestIsEarlyBirdPending:
|
||||
with (
|
||||
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=True
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
assert locker._is_early_bird_pending() is True
|
||||
@ -128,10 +131,12 @@ class TestIsEarlyBirdPending:
|
||||
with (
|
||||
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.compute_entry_hmac", return_value=None
|
||||
"screen_locker._compliance_predicates.compute_entry_hmac",
|
||||
return_value=None,
|
||||
),
|
||||
):
|
||||
assert locker._is_early_bird_pending() is True
|
||||
|
||||
@ -128,7 +128,7 @@ class TestHasLoggedToday:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.log_file = log_file
|
||||
with patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac",
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=True,
|
||||
):
|
||||
assert locker.has_logged_today() is True
|
||||
@ -149,7 +149,7 @@ class TestHasLoggedToday:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.log_file = log_file
|
||||
with patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac",
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
):
|
||||
assert locker.has_logged_today() is False
|
||||
@ -171,11 +171,11 @@ class TestHasLoggedToday:
|
||||
locker.log_file = log_file
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac",
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.compute_entry_hmac",
|
||||
"screen_locker._compliance_predicates.compute_entry_hmac",
|
||||
return_value=None,
|
||||
),
|
||||
):
|
||||
@ -198,11 +198,11 @@ class TestHasLoggedToday:
|
||||
locker.log_file = log_file
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac",
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=False,
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.compute_entry_hmac",
|
||||
"screen_locker._compliance_predicates.compute_entry_hmac",
|
||||
return_value="some-signature",
|
||||
),
|
||||
):
|
||||
|
||||
@ -171,88 +171,3 @@ class TestApplyWorkoutCredit:
|
||||
assert result.extra_bonus_delta == 1
|
||||
locker._try_adjust_shutdown_for_workout.assert_not_called()
|
||||
locker._adjust_shutdown_time_by.assert_called_once_with(1)
|
||||
|
||||
def test_additional_workout_unreadable_shutdown_config_earns_no_bonus(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""Additional same-day workout, but the shutdown config can't be read
|
||||
(old_cfg is None) → the +1h branch is entered but bails out before
|
||||
ever attempting the adjustment."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.workout_data = {"type": "phone_verified"}
|
||||
prior = [{"workout_data": {"type": "phone_verified"}}]
|
||||
object.__setattr__(
|
||||
locker,
|
||||
"save_workout_log",
|
||||
MagicMock(return_value=RecordResult(appended=True, prior_entries=prior)),
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_try_adjust_shutdown_for_workout", MagicMock(return_value=True)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_read_shutdown_config", MagicMock(return_value=None)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_adjust_shutdown_time_by", MagicMock(return_value=True)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_clear_debt_on_verified_workout", MagicMock(return_value=None)
|
||||
)
|
||||
|
||||
result = locker._apply_workout_credit()
|
||||
|
||||
assert result.shutdown_adjusted is False
|
||||
assert result.extra_bonus_delta == 0
|
||||
locker._try_adjust_shutdown_for_workout.assert_not_called()
|
||||
locker._adjust_shutdown_time_by.assert_not_called()
|
||||
|
||||
def test_additional_workout_of_uncounted_type_earns_nothing(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""A workout whose type isn't in COUNTED_WORKOUT_TYPES (e.g.
|
||||
``early_bird``) and isn't the first counted entry of the day →
|
||||
neither the base push nor the +1h branch fires; the shutdown config
|
||||
is never even consulted."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.workout_data = {"type": "early_bird"}
|
||||
prior = [{"workout_data": {"type": "phone_verified"}}]
|
||||
object.__setattr__(
|
||||
locker, "_try_adjust_shutdown_for_workout", MagicMock(return_value=True)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_read_shutdown_config", MagicMock(return_value=(21, 21, 5))
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_adjust_shutdown_time_by", MagicMock(return_value=True)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_clear_debt_on_verified_workout", MagicMock(return_value=None)
|
||||
)
|
||||
|
||||
result = locker._apply_credit_for_written_entry(prior)
|
||||
|
||||
assert result.shutdown_adjusted is False
|
||||
assert result.extra_bonus_delta == 0
|
||||
locker._try_adjust_shutdown_for_workout.assert_not_called()
|
||||
locker._read_shutdown_config.assert_not_called()
|
||||
locker._adjust_shutdown_time_by.assert_not_called()
|
||||
|
||||
def test_skips_save_for_sick_day_type(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""Skips save for sick day type."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.workout_data = {"type": "sick_day"}
|
||||
object.__setattr__(
|
||||
locker, "_try_adjust_shutdown_for_workout", MagicMock(return_value=False)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_clear_debt_on_verified_workout", MagicMock(return_value=None)
|
||||
)
|
||||
object.__setattr__(locker, "save_workout_log", MagicMock())
|
||||
|
||||
result = locker._apply_workout_credit()
|
||||
|
||||
assert result.already_counted_today is False
|
||||
assert result.shutdown_adjusted is False
|
||||
locker.save_workout_log.assert_not_called()
|
||||
|
||||
117
screen_locker/tests/test_manual_workout_features_part4.py
Normal file
117
screen_locker/tests/test_manual_workout_features_part4.py
Normal file
@ -0,0 +1,117 @@
|
||||
"""More workout-credit cases: bonuses, unreadable config, sick days.
|
||||
|
||||
Split out of test_manual_workout_features_part2.py for the 250-line cap.
|
||||
"""
|
||||
# pylint: disable=protected-access
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from screen_locker._log_mixin import RecordResult
|
||||
from screen_locker.tests.conftest import create_locker
|
||||
|
||||
# The Dart mirror of the budget caps; read at test time so drift on
|
||||
# EITHER side fails, not just a local edit to the Python constants.
|
||||
DART_MANUAL_WORKOUT = (
|
||||
pathlib.Path(__file__).resolve().parents[2]
|
||||
/ "stronglift_replacement"
|
||||
/ "workout_app"
|
||||
/ "lib"
|
||||
/ "models"
|
||||
/ "manual_workout.dart"
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class TestApplyWorkoutCredit:
|
||||
"""More _apply_workout_credit cases under the multi-per-day rule."""
|
||||
|
||||
def test_additional_workout_unreadable_shutdown_config_earns_no_bonus(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""Additional same-day workout, but the shutdown config can't be read
|
||||
(old_cfg is None) → the +1h branch is entered but bails out before
|
||||
ever attempting the adjustment."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.workout_data = {"type": "phone_verified"}
|
||||
prior = [{"workout_data": {"type": "phone_verified"}}]
|
||||
object.__setattr__(
|
||||
locker,
|
||||
"save_workout_log",
|
||||
MagicMock(return_value=RecordResult(appended=True, prior_entries=prior)),
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_try_adjust_shutdown_for_workout", MagicMock(return_value=True)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_read_shutdown_config", MagicMock(return_value=None)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_adjust_shutdown_time_by", MagicMock(return_value=True)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_clear_debt_on_verified_workout", MagicMock(return_value=None)
|
||||
)
|
||||
|
||||
result = locker._apply_workout_credit()
|
||||
|
||||
assert result.shutdown_adjusted is False
|
||||
assert result.extra_bonus_delta == 0
|
||||
locker._try_adjust_shutdown_for_workout.assert_not_called()
|
||||
locker._adjust_shutdown_time_by.assert_not_called()
|
||||
|
||||
def test_additional_workout_of_uncounted_type_earns_nothing(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""A workout whose type isn't in COUNTED_WORKOUT_TYPES (e.g.
|
||||
``early_bird``) and isn't the first counted entry of the day →
|
||||
neither the base push nor the +1h branch fires; the shutdown config
|
||||
is never even consulted."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.workout_data = {"type": "early_bird"}
|
||||
prior = [{"workout_data": {"type": "phone_verified"}}]
|
||||
object.__setattr__(
|
||||
locker, "_try_adjust_shutdown_for_workout", MagicMock(return_value=True)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_read_shutdown_config", MagicMock(return_value=(21, 21, 5))
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_adjust_shutdown_time_by", MagicMock(return_value=True)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_clear_debt_on_verified_workout", MagicMock(return_value=None)
|
||||
)
|
||||
|
||||
result = locker._apply_credit_for_written_entry(prior)
|
||||
|
||||
assert result.shutdown_adjusted is False
|
||||
assert result.extra_bonus_delta == 0
|
||||
locker._try_adjust_shutdown_for_workout.assert_not_called()
|
||||
locker._read_shutdown_config.assert_not_called()
|
||||
locker._adjust_shutdown_time_by.assert_not_called()
|
||||
|
||||
def test_skips_save_for_sick_day_type(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""Skips save for sick day type."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.workout_data = {"type": "sick_day"}
|
||||
object.__setattr__(
|
||||
locker, "_try_adjust_shutdown_for_workout", MagicMock(return_value=False)
|
||||
)
|
||||
object.__setattr__(
|
||||
locker, "_clear_debt_on_verified_workout", MagicMock(return_value=None)
|
||||
)
|
||||
object.__setattr__(locker, "save_workout_log", MagicMock())
|
||||
|
||||
result = locker._apply_workout_credit()
|
||||
|
||||
assert result.already_counted_today is False
|
||||
assert result.shutdown_adjusted is False
|
||||
locker.save_workout_log.assert_not_called()
|
||||
@ -144,7 +144,7 @@ class TestGetLocalSubnetPrefix:
|
||||
mock_sock.__enter__ = MagicMock(return_value=mock_sock)
|
||||
mock_sock.__exit__ = MagicMock(return_value=False)
|
||||
with patch(
|
||||
"screen_locker._phone_verification.socket.socket",
|
||||
"screen_locker._adb_transport.socket.socket",
|
||||
return_value=mock_sock,
|
||||
):
|
||||
result = locker._get_local_subnet_prefix()
|
||||
@ -159,7 +159,7 @@ class TestGetLocalSubnetPrefix:
|
||||
"""Test returns None when socket raises OSError."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with patch(
|
||||
"screen_locker._phone_verification.socket.socket",
|
||||
"screen_locker._adb_transport.socket.socket",
|
||||
side_effect=OSError("no network"),
|
||||
):
|
||||
result = locker._get_local_subnet_prefix()
|
||||
|
||||
@ -128,7 +128,7 @@ class TestScanForHttpServer:
|
||||
with (
|
||||
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
||||
patch(
|
||||
"screen_locker._phone_verification.socket.create_connection",
|
||||
"screen_locker._http_workout_fetch.socket.create_connection",
|
||||
return_value=_mock_cm(MagicMock()),
|
||||
),
|
||||
):
|
||||
@ -145,7 +145,7 @@ class TestScanForHttpServer:
|
||||
with (
|
||||
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
||||
patch(
|
||||
"screen_locker._phone_verification.socket.create_connection",
|
||||
"screen_locker._http_workout_fetch.socket.create_connection",
|
||||
side_effect=OSError("refused"),
|
||||
),
|
||||
):
|
||||
|
||||
@ -39,7 +39,7 @@ class TestTryWirelessReconnect:
|
||||
patch.object(locker, "_try_adb_connect", return_value=True),
|
||||
patch.object(locker, "_has_adb_device", return_value=True),
|
||||
patch(
|
||||
"screen_locker._phone_verification.socket.create_connection",
|
||||
"screen_locker._adb_transport.socket.create_connection",
|
||||
) as mock_conn,
|
||||
):
|
||||
mock_sock = MagicMock()
|
||||
@ -60,7 +60,7 @@ class TestTryWirelessReconnect:
|
||||
with (
|
||||
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
||||
patch(
|
||||
"screen_locker._phone_verification.socket.create_connection",
|
||||
"screen_locker._adb_transport.socket.create_connection",
|
||||
side_effect=OSError("refused"),
|
||||
),
|
||||
):
|
||||
@ -80,7 +80,7 @@ class TestTryWirelessReconnect:
|
||||
patch.object(locker, "_try_adb_connect", return_value=True),
|
||||
patch.object(locker, "_has_adb_device", return_value=False),
|
||||
patch(
|
||||
"screen_locker._phone_verification.socket.create_connection",
|
||||
"screen_locker._adb_transport.socket.create_connection",
|
||||
) as mock_conn,
|
||||
):
|
||||
mock_sock = MagicMock()
|
||||
@ -102,7 +102,7 @@ class TestTryWirelessReconnect:
|
||||
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
||||
patch.object(locker, "_try_adb_connect", return_value=False),
|
||||
patch(
|
||||
"screen_locker._phone_verification.socket.create_connection",
|
||||
"screen_locker._adb_transport.socket.create_connection",
|
||||
) as mock_conn,
|
||||
):
|
||||
mock_sock = MagicMock()
|
||||
|
||||
@ -45,7 +45,7 @@ class TestFetchHttpWorkout:
|
||||
return_value="http://192.168.1.5:8765/workout",
|
||||
),
|
||||
patch(
|
||||
"screen_locker._phone_verification._HTTPConnection",
|
||||
"screen_locker._http_workout_fetch._HTTPConnection",
|
||||
return_value=conn,
|
||||
),
|
||||
):
|
||||
@ -68,7 +68,7 @@ class TestFetchHttpWorkout:
|
||||
return_value="http://192.168.1.5:8765/workout",
|
||||
),
|
||||
patch(
|
||||
"screen_locker._phone_verification._HTTPConnection",
|
||||
"screen_locker._http_workout_fetch._HTTPConnection",
|
||||
return_value=conn,
|
||||
),
|
||||
):
|
||||
@ -86,7 +86,7 @@ class TestFetchHttpWorkout:
|
||||
return_value="http://192.168.1.5:8765/workout",
|
||||
),
|
||||
patch(
|
||||
"screen_locker._phone_verification._HTTPConnection",
|
||||
"screen_locker._http_workout_fetch._HTTPConnection",
|
||||
side_effect=OSError("unreachable"),
|
||||
),
|
||||
):
|
||||
|
||||
@ -5,7 +5,6 @@ Split out of test_runnerup_verification_part7.py for the 250-line cap.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@ -227,69 +226,3 @@ class TestScanAndFillWeekRunnerupSkips:
|
||||
|
||||
# The append still reports success; only the save failure is warned.
|
||||
assert result >= 1
|
||||
|
||||
def test_handles_corrupt_log_file(
|
||||
self,
|
||||
mock_tk: MagicMock,
|
||||
mock_sys_exit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Corrupt log JSON → starts with empty dict, still works."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
log_file = tmp_path / "log.json"
|
||||
log_file.write_text("not-json")
|
||||
object.__setattr__(locker, "_has_adb_device", MagicMock(return_value=True))
|
||||
object.__setattr__(
|
||||
locker,
|
||||
"_find_runnerup_exports_for_date",
|
||||
MagicMock(return_value=[]),
|
||||
)
|
||||
# Should not raise; returns 0 (no exports found).
|
||||
assert locker._scan_and_fill_week_runnerup(log_file) == 0
|
||||
|
||||
def test_hmac_none_still_fills_entry(
|
||||
self,
|
||||
mock_tk: MagicMock,
|
||||
mock_sys_exit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""HMAC key absent (compute_entry_hmac returns None) → entry still written."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
log_file = tmp_path / "log.json"
|
||||
log_file.write_text("{}")
|
||||
object.__setattr__(locker, "_has_adb_device", MagicMock(return_value=True))
|
||||
object.__setattr__(
|
||||
locker,
|
||||
"_find_runnerup_exports_for_date",
|
||||
MagicMock(return_value=["/sdcard/run.tcx"]),
|
||||
)
|
||||
object.__setattr__(
|
||||
locker,
|
||||
"_pull_and_parse_tcx",
|
||||
MagicMock(
|
||||
return_value={"sport": 0, "duration_seconds": 2400, "distance_m": 6000}
|
||||
),
|
||||
)
|
||||
object.__setattr__(
|
||||
locker,
|
||||
"_validate_runnerup_data",
|
||||
MagicMock(return_value=("verified", "Running: 6.0 km in 40 min")),
|
||||
)
|
||||
|
||||
with patch(
|
||||
"screen_locker._log_mixin.compute_entry_hmac",
|
||||
return_value=None,
|
||||
):
|
||||
result = locker._scan_and_fill_week_runnerup(log_file)
|
||||
|
||||
assert result > 0
|
||||
# No "hmac" key when signature is None; each day holds a list of entries.
|
||||
logs = json.loads(log_file.read_text())
|
||||
for entries in logs.values():
|
||||
for entry in entries:
|
||||
assert "hmac" not in entry
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _find_runnerup_package
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
137
screen_locker/tests/test_runnerup_verification_part15.py
Normal file
137
screen_locker/tests/test_runnerup_verification_part15.py
Normal file
@ -0,0 +1,137 @@
|
||||
"""More RunnerUp week-scan backfill edge cases.
|
||||
|
||||
Split out of test_runnerup_verification_part10.py for the 250-line cap.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from screen_locker.tests.conftest import create_locker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
# Minimal valid TCX XML for a 40-minute, 6-km run.
|
||||
_TCX_RUNNING = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2">
|
||||
<Activities>
|
||||
<Activity Sport="Running">
|
||||
<Lap>
|
||||
<TotalTimeSeconds>2400.0</TotalTimeSeconds>
|
||||
<DistanceMeters>6000.0</DistanceMeters>
|
||||
</Lap>
|
||||
</Activity>
|
||||
</Activities>
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2">
|
||||
<Activities>
|
||||
<Activity Sport="Gym">
|
||||
<Lap>
|
||||
<TotalTimeSeconds>3600.0</TotalTimeSeconds>
|
||||
<DistanceMeters>0.0</DistanceMeters>
|
||||
</Lap>
|
||||
</Activity>
|
||||
</Activities>
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# Two laps that together make a valid run.
|
||||
_TCX_MULTI_LAP = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2">
|
||||
<Activities>
|
||||
<Activity Sport="Running">
|
||||
<Lap>
|
||||
<TotalTimeSeconds>1200.0</TotalTimeSeconds>
|
||||
<DistanceMeters>3000.0</DistanceMeters>
|
||||
</Lap>
|
||||
<Lap>
|
||||
<TotalTimeSeconds>1200.0</TotalTimeSeconds>
|
||||
<DistanceMeters>3000.0</DistanceMeters>
|
||||
</Lap>
|
||||
</Activity>
|
||||
</Activities>
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
|
||||
class TestScanAndFillWeekRunnerupSkips:
|
||||
"""Days the scan declines to fill, and failures it survives."""
|
||||
|
||||
def test_handles_corrupt_log_file(
|
||||
self,
|
||||
mock_tk: MagicMock,
|
||||
mock_sys_exit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Corrupt log JSON → starts with empty dict, still works."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
log_file = tmp_path / "log.json"
|
||||
log_file.write_text("not-json")
|
||||
object.__setattr__(locker, "_has_adb_device", MagicMock(return_value=True))
|
||||
object.__setattr__(
|
||||
locker,
|
||||
"_find_runnerup_exports_for_date",
|
||||
MagicMock(return_value=[]),
|
||||
)
|
||||
# Should not raise; returns 0 (no exports found).
|
||||
assert locker._scan_and_fill_week_runnerup(log_file) == 0
|
||||
|
||||
def test_hmac_none_still_fills_entry(
|
||||
self,
|
||||
mock_tk: MagicMock,
|
||||
mock_sys_exit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""HMAC key absent (compute_entry_hmac returns None) → entry still written."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
log_file = tmp_path / "log.json"
|
||||
log_file.write_text("{}")
|
||||
object.__setattr__(locker, "_has_adb_device", MagicMock(return_value=True))
|
||||
object.__setattr__(
|
||||
locker,
|
||||
"_find_runnerup_exports_for_date",
|
||||
MagicMock(return_value=["/sdcard/run.tcx"]),
|
||||
)
|
||||
object.__setattr__(
|
||||
locker,
|
||||
"_pull_and_parse_tcx",
|
||||
MagicMock(
|
||||
return_value={"sport": 0, "duration_seconds": 2400, "distance_m": 6000}
|
||||
),
|
||||
)
|
||||
object.__setattr__(
|
||||
locker,
|
||||
"_validate_runnerup_data",
|
||||
MagicMock(return_value=("verified", "Running: 6.0 km in 40 min")),
|
||||
)
|
||||
|
||||
with patch(
|
||||
"screen_locker._log_mixin.compute_entry_hmac",
|
||||
return_value=None,
|
||||
):
|
||||
result = locker._scan_and_fill_week_runnerup(log_file)
|
||||
|
||||
assert result > 0
|
||||
# No "hmac" key when signature is None; each day holds a list of entries.
|
||||
logs = json.loads(log_file.read_text())
|
||||
for entries in logs.values():
|
||||
for entry in entries:
|
||||
assert "hmac" not in entry
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _find_runnerup_package
|
||||
# ---------------------------------------------------------------------------
|
||||
@ -6,7 +6,6 @@ from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from screen_locker.tests._unlock_helpers import setup_unlock
|
||||
from screen_locker.tests.conftest import create_locker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
@ -131,122 +130,3 @@ class TestUnlockScreenExtras:
|
||||
locker.unlock_screen()
|
||||
|
||||
assert not any("Extra workout" in c for c in text_calls)
|
||||
|
||||
|
||||
class TestIngestSyncedManualWorkouts:
|
||||
"""Tests for _ingest_synced_manual_workouts (manual-sync wiring)."""
|
||||
|
||||
def test_logs_each_ingested_record(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""Logs each ingested record."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._sync_mixin.pull_all_manual_records",
|
||||
return_value=[("manual:x", {})],
|
||||
),
|
||||
patch(
|
||||
"screen_locker._sync_mixin.ingest_manual_records",
|
||||
return_value=["manual:x"],
|
||||
) as ingest,
|
||||
):
|
||||
locker._ingest_synced_manual_workouts()
|
||||
ingest.assert_called_once()
|
||||
|
||||
def test_no_records_ingests_nothing(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""No records ingests nothing."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._sync_mixin.pull_all_manual_records",
|
||||
return_value=[],
|
||||
),
|
||||
patch(
|
||||
"screen_locker._sync_mixin.ingest_manual_records",
|
||||
return_value=[],
|
||||
),
|
||||
):
|
||||
locker._ingest_synced_manual_workouts()
|
||||
|
||||
def test_passes_credit_callback_and_resets_workout_data(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""The callback wired into ingest_manual_records must be
|
||||
``locker._credit_ingested_manual_workout``, so a synced manual
|
||||
workout earns the same reward a live one would; workout_data is reset
|
||||
afterward so it can't leak into a later interactive flow."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.workout_data = {"stale": "state"}
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._sync_mixin.pull_all_manual_records",
|
||||
return_value=[],
|
||||
),
|
||||
patch(
|
||||
"screen_locker._sync_mixin.ingest_manual_records",
|
||||
return_value=[],
|
||||
) as ingest,
|
||||
):
|
||||
locker._ingest_synced_manual_workouts()
|
||||
assert ingest.call_args.kwargs["on_ingested"] == (
|
||||
locker._credit_ingested_manual_workout
|
||||
)
|
||||
assert locker.workout_data == {}
|
||||
|
||||
def test_credit_ingested_manual_workout_applies_reward(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""_credit_ingested_manual_workout sets workout_data to the ingested
|
||||
entry and applies the shared credit logic — proving a synced manual
|
||||
workout (today's or back-dated) earns full shutdown/debt credit,
|
||||
exactly like a live-logged one."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
entry = {"type": "manual_workout", "source": "table tennis at Solec"}
|
||||
prior: list[dict] = []
|
||||
with patch.object(
|
||||
locker,
|
||||
"_apply_credit_for_written_entry",
|
||||
return_value=MagicMock(shutdown_adjusted=True, extra_bonus_delta=0),
|
||||
) as apply_credit:
|
||||
locker._credit_ingested_manual_workout(entry, prior)
|
||||
assert locker.workout_data == entry
|
||||
apply_credit.assert_called_once_with(prior)
|
||||
|
||||
def test_credit_ingested_manual_workout_logs_extra_bonus(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""A second same-day synced manual workout (extra_bonus_delta, not the
|
||||
base push) takes the elif branch — a back-dated sync can still stack
|
||||
the +1h bonus exactly like an additional same-day verified workout."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
entry = {"type": "manual_workout", "source": "gym"}
|
||||
prior = [{"workout_data": {"type": "manual_workout"}}]
|
||||
with patch.object(
|
||||
locker,
|
||||
"_apply_credit_for_written_entry",
|
||||
return_value=MagicMock(shutdown_adjusted=False, extra_bonus_delta=1),
|
||||
) as apply_credit:
|
||||
locker._credit_ingested_manual_workout(entry, prior)
|
||||
assert locker.workout_data == entry
|
||||
apply_credit.assert_called_once_with(prior)
|
||||
|
||||
def test_credit_ingested_manual_workout_no_reward_logs_nothing(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""A duplicate/no-op credit result (neither shutdown_adjusted nor
|
||||
extra_bonus_delta) → neither log line fires; credit is still applied
|
||||
via workout_data being set."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
entry = {"type": "manual_workout", "source": "gym"}
|
||||
prior: list[dict] = []
|
||||
with patch.object(
|
||||
locker,
|
||||
"_apply_credit_for_written_entry",
|
||||
return_value=MagicMock(shutdown_adjusted=False, extra_bonus_delta=0),
|
||||
) as apply_credit:
|
||||
locker._credit_ingested_manual_workout(entry, prior)
|
||||
assert locker.workout_data == entry
|
||||
apply_credit.assert_called_once_with(prior)
|
||||
|
||||
133
screen_locker/tests/test_screen_lock_coverage_part5.py
Normal file
133
screen_locker/tests/test_screen_lock_coverage_part5.py
Normal file
@ -0,0 +1,133 @@
|
||||
"""Tests for ingesting manual workouts synced from the phone.
|
||||
|
||||
Split out of test_screen_lock_coverage_part2.py for the 250-line cap.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from screen_locker.tests.conftest import create_locker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class TestIngestSyncedManualWorkouts:
|
||||
"""Tests for _ingest_synced_manual_workouts (manual-sync wiring)."""
|
||||
|
||||
def test_logs_each_ingested_record(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""Logs each ingested record."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._sync_mixin.pull_all_manual_records",
|
||||
return_value=[("manual:x", {})],
|
||||
),
|
||||
patch(
|
||||
"screen_locker._sync_mixin.ingest_manual_records",
|
||||
return_value=["manual:x"],
|
||||
) as ingest,
|
||||
):
|
||||
locker._ingest_synced_manual_workouts()
|
||||
ingest.assert_called_once()
|
||||
|
||||
def test_no_records_ingests_nothing(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""No records ingests nothing."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._sync_mixin.pull_all_manual_records",
|
||||
return_value=[],
|
||||
),
|
||||
patch(
|
||||
"screen_locker._sync_mixin.ingest_manual_records",
|
||||
return_value=[],
|
||||
),
|
||||
):
|
||||
locker._ingest_synced_manual_workouts()
|
||||
|
||||
def test_passes_credit_callback_and_resets_workout_data(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""The callback wired into ingest_manual_records must be
|
||||
``locker._credit_ingested_manual_workout``, so a synced manual
|
||||
workout earns the same reward a live one would; workout_data is reset
|
||||
afterward so it can't leak into a later interactive flow."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.workout_data = {"stale": "state"}
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._sync_mixin.pull_all_manual_records",
|
||||
return_value=[],
|
||||
),
|
||||
patch(
|
||||
"screen_locker._sync_mixin.ingest_manual_records",
|
||||
return_value=[],
|
||||
) as ingest,
|
||||
):
|
||||
locker._ingest_synced_manual_workouts()
|
||||
assert ingest.call_args.kwargs["on_ingested"] == (
|
||||
locker._credit_ingested_manual_workout
|
||||
)
|
||||
assert locker.workout_data == {}
|
||||
|
||||
def test_credit_ingested_manual_workout_applies_reward(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""_credit_ingested_manual_workout sets workout_data to the ingested
|
||||
entry and applies the shared credit logic — proving a synced manual
|
||||
workout (today's or back-dated) earns full shutdown/debt credit,
|
||||
exactly like a live-logged one."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
entry = {"type": "manual_workout", "source": "table tennis at Solec"}
|
||||
prior: list[dict] = []
|
||||
with patch.object(
|
||||
locker,
|
||||
"_apply_credit_for_written_entry",
|
||||
return_value=MagicMock(shutdown_adjusted=True, extra_bonus_delta=0),
|
||||
) as apply_credit:
|
||||
locker._credit_ingested_manual_workout(entry, prior)
|
||||
assert locker.workout_data == entry
|
||||
apply_credit.assert_called_once_with(prior)
|
||||
|
||||
def test_credit_ingested_manual_workout_logs_extra_bonus(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""A second same-day synced manual workout (extra_bonus_delta, not the
|
||||
base push) takes the elif branch — a back-dated sync can still stack
|
||||
the +1h bonus exactly like an additional same-day verified workout."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
entry = {"type": "manual_workout", "source": "gym"}
|
||||
prior = [{"workout_data": {"type": "manual_workout"}}]
|
||||
with patch.object(
|
||||
locker,
|
||||
"_apply_credit_for_written_entry",
|
||||
return_value=MagicMock(shutdown_adjusted=False, extra_bonus_delta=1),
|
||||
) as apply_credit:
|
||||
locker._credit_ingested_manual_workout(entry, prior)
|
||||
assert locker.workout_data == entry
|
||||
apply_credit.assert_called_once_with(prior)
|
||||
|
||||
def test_credit_ingested_manual_workout_no_reward_logs_nothing(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""A duplicate/no-op credit result (neither shutdown_adjusted nor
|
||||
extra_bonus_delta) → neither log line fires; credit is still applied
|
||||
via workout_data being set."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
entry = {"type": "manual_workout", "source": "gym"}
|
||||
prior: list[dict] = []
|
||||
with patch.object(
|
||||
locker,
|
||||
"_apply_credit_for_written_entry",
|
||||
return_value=MagicMock(shutdown_adjusted=False, extra_bonus_delta=0),
|
||||
) as apply_credit:
|
||||
locker._credit_ingested_manual_workout(entry, prior)
|
||||
assert locker.workout_data == entry
|
||||
apply_credit.assert_called_once_with(prior)
|
||||
@ -27,7 +27,7 @@ class TestRestoreOriginalConfigIfNeeded:
|
||||
mock_file = MagicMock()
|
||||
mock_file.exists.return_value = False
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
mock_file,
|
||||
):
|
||||
locker._restore_original_config_if_needed()
|
||||
@ -52,7 +52,7 @@ class TestRestoreOriginalConfigIfNeeded:
|
||||
)
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
),
|
||||
patch.object(locker, "_write_restored_config") as mock_restore,
|
||||
@ -83,7 +83,7 @@ class TestRestoreOriginalConfigIfNeeded:
|
||||
)
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
),
|
||||
patch.object(locker, "_write_restored_config") as mock_restore,
|
||||
@ -103,7 +103,7 @@ class TestRestoreOriginalConfigIfNeeded:
|
||||
state_file.write_text(json.dumps({"date": "2020-01-01"}))
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
),
|
||||
patch.object(locker, "_write_restored_config") as mock_restore,
|
||||
@ -123,7 +123,7 @@ class TestRestoreOriginalConfigIfNeeded:
|
||||
mock_file.exists.return_value = True
|
||||
mock_file.open.side_effect = OSError("fail")
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
mock_file,
|
||||
):
|
||||
locker._restore_original_config_if_needed()
|
||||
@ -139,7 +139,7 @@ class TestRestoreOriginalConfigIfNeeded:
|
||||
state_file = tmp_path / "state.json"
|
||||
state_file.write_text("not valid json{{{")
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
):
|
||||
locker._restore_original_config_if_needed()
|
||||
|
||||
@ -25,7 +25,7 @@ class TestSaveSickDayState:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
state_file = tmp_path / "state.json"
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
):
|
||||
result = locker._save_sick_day_state("2026-03-21", 21, 20)
|
||||
@ -46,7 +46,7 @@ class TestSaveSickDayState:
|
||||
mock_path = MagicMock()
|
||||
mock_path.open.side_effect = OSError("permission denied")
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
mock_path,
|
||||
):
|
||||
result = locker._save_sick_day_state("2026-03-21", 21, 20)
|
||||
@ -75,7 +75,7 @@ class TestLoadSickDayState:
|
||||
)
|
||||
)
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
):
|
||||
result = locker._load_sick_day_state()
|
||||
@ -92,7 +92,7 @@ class TestLoadSickDayState:
|
||||
state_file = tmp_path / "state.json"
|
||||
state_file.write_text(json.dumps({"date": "2026-03-20"}))
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
):
|
||||
result = locker._load_sick_day_state()
|
||||
@ -118,7 +118,7 @@ class TestWriteRestoredConfig:
|
||||
locker, "_write_shutdown_config", return_value=True
|
||||
) as mock_write,
|
||||
patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
),
|
||||
):
|
||||
@ -139,7 +139,7 @@ class TestWriteRestoredConfig:
|
||||
with (
|
||||
patch.object(locker, "_read_shutdown_config", return_value=None),
|
||||
patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
),
|
||||
):
|
||||
|
||||
@ -26,7 +26,7 @@ class TestSickModeUsedToday:
|
||||
mock_file = MagicMock()
|
||||
mock_file.exists.return_value = False
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
mock_file,
|
||||
):
|
||||
assert locker._sick_mode_used_today() is False
|
||||
@ -41,7 +41,7 @@ class TestSickModeUsedToday:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
state_file = tmp_path / "state.json"
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
):
|
||||
from datetime import datetime, timezone
|
||||
@ -60,7 +60,7 @@ class TestSickModeUsedToday:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
state_file = tmp_path / "state.json"
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
):
|
||||
state_file.write_text(json.dumps({"date": "2020-01-01"}))
|
||||
@ -76,7 +76,7 @@ class TestSickModeUsedToday:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
state_file = tmp_path / "state.json"
|
||||
with patch(
|
||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||
"screen_locker._shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
state_file,
|
||||
):
|
||||
state_file.write_text("not json{{{")
|
||||
|
||||
@ -75,7 +75,8 @@ class TestGatherStatus:
|
||||
"screen_locker._status_data.has_workout_skip_today", return_value=False
|
||||
),
|
||||
patch(
|
||||
"screen_locker._compliance_state.verify_entry_hmac", return_value=True
|
||||
"screen_locker._compliance_predicates.verify_entry_hmac",
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
snap = gather_status(**files, now=_FRIDAY_NOON_UTC)
|
||||
|
||||
@ -28,9 +28,13 @@ def isolate_sync_token(tmp_path: Path) -> Iterator[None]:
|
||||
file makes ``read_sync_token()`` return None, the same benign "sync not
|
||||
configured" state every existing test already assumes.
|
||||
"""
|
||||
with patch(
|
||||
"screen_locker._workout_sync.SYNC_TOKEN_FILE",
|
||||
tmp_path / "sync_token",
|
||||
# read_sync_token moved to _sync_client when _workout_sync was split;
|
||||
# _workout_sync still re-exports the constant, so both names must be
|
||||
# redirected or a real token on the host leaks into the tests.
|
||||
token = tmp_path / "sync_token"
|
||||
with (
|
||||
patch("screen_locker._sync_client.SYNC_TOKEN_FILE", token),
|
||||
patch("screen_locker._workout_sync.SYNC_TOKEN_FILE", token),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@ -26,7 +26,7 @@ class TestIsTomorrowAlarmDay:
|
||||
|
||||
# Sunday 2026-04-12 → tomorrow Monday
|
||||
with patch(
|
||||
"screen_locker._shutdown.datetime",
|
||||
"screen_locker._wake_alarm.datetime",
|
||||
) as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 4, 12, 23, 0, tzinfo=timezone.utc)
|
||||
mock_dt.side_effect = datetime
|
||||
@ -34,7 +34,7 @@ class TestIsTomorrowAlarmDay:
|
||||
|
||||
# Ensure timedelta works
|
||||
with patch(
|
||||
"screen_locker._shutdown.timedelta",
|
||||
"screen_locker._wake_alarm.timedelta",
|
||||
timedelta,
|
||||
):
|
||||
assert locker._is_tomorrow_alarm_day() is True
|
||||
@ -52,10 +52,10 @@ class TestIsTomorrowAlarmDay:
|
||||
# Monday 2026-04-13 → tomorrow Tuesday (weekday=1)
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._shutdown.datetime",
|
||||
"screen_locker._wake_alarm.datetime",
|
||||
) as mock_dt,
|
||||
patch(
|
||||
"screen_locker._shutdown.timedelta",
|
||||
"screen_locker._wake_alarm.timedelta",
|
||||
timedelta,
|
||||
),
|
||||
):
|
||||
@ -76,10 +76,10 @@ class TestIsTomorrowAlarmDay:
|
||||
# Thursday 2026-04-16 → tomorrow Friday (weekday=4)
|
||||
with (
|
||||
patch(
|
||||
"screen_locker._shutdown.datetime",
|
||||
"screen_locker._wake_alarm.datetime",
|
||||
) as mock_dt,
|
||||
patch(
|
||||
"screen_locker._shutdown.timedelta",
|
||||
"screen_locker._wake_alarm.timedelta",
|
||||
timedelta,
|
||||
),
|
||||
):
|
||||
@ -100,7 +100,7 @@ class TestScheduleRtcwake:
|
||||
"""Successful rtcwake call returns True."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with patch(
|
||||
"screen_locker._shutdown.subprocess.run",
|
||||
"screen_locker._wake_alarm.subprocess.run",
|
||||
) as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
assert locker._schedule_rtcwake() is True
|
||||
@ -119,7 +119,7 @@ class TestScheduleRtcwake:
|
||||
import subprocess
|
||||
|
||||
with patch(
|
||||
"screen_locker._shutdown.subprocess.run",
|
||||
"screen_locker._wake_alarm.subprocess.run",
|
||||
side_effect=subprocess.SubprocessError("rtcwake failed"),
|
||||
):
|
||||
assert locker._schedule_rtcwake() is False
|
||||
|
||||
@ -16,7 +16,7 @@ from crdt_sync import (
|
||||
)
|
||||
import pytest
|
||||
|
||||
from screen_locker import _workout_sync
|
||||
from screen_locker import _sync_client, _workout_sync
|
||||
from screen_locker.tests._workout_sync_fixtures import (
|
||||
_firebase_config,
|
||||
)
|
||||
@ -44,7 +44,7 @@ class TestSyncClient:
|
||||
"""Uses github alone when only the token exists."""
|
||||
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
|
||||
github = MagicMock()
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=github):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=github):
|
||||
assert _workout_sync.sync_client() is github
|
||||
|
||||
def test_mirrors_when_both_the_token_and_firebase_exist(
|
||||
@ -52,21 +52,21 @@ class TestSyncClient:
|
||||
) -> None:
|
||||
"""Mirrors when both the token and firebase exist."""
|
||||
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
|
||||
_firebase_config(_workout_sync, tmp_path, monkeypatch)
|
||||
_firebase_config(_sync_client, tmp_path, monkeypatch)
|
||||
github = MagicMock()
|
||||
monkeypatch.setattr(
|
||||
_workout_sync, "mirror_client_for", lambda _app, client: ("mirror", client)
|
||||
_sync_client, "mirror_client_for", lambda _app, client: ("mirror", client)
|
||||
)
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=github):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=github):
|
||||
assert _workout_sync.sync_client() == ("mirror", github)
|
||||
|
||||
def test_uses_firebase_alone_when_only_the_config_exists(
|
||||
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A Firebase-only machine must still sync -- no PAT required."""
|
||||
_firebase_config(_workout_sync, tmp_path, monkeypatch)
|
||||
_firebase_config(_sync_client, tmp_path, monkeypatch)
|
||||
firebase = MagicMock()
|
||||
monkeypatch.setattr(_workout_sync, "firebase_client_for", lambda _app: firebase)
|
||||
monkeypatch.setattr(_sync_client, "firebase_client_for", lambda _app: firebase)
|
||||
assert _workout_sync.sync_client() is firebase
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@ -81,12 +81,12 @@ class TestSyncClient:
|
||||
self, error: Exception, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""No PAT to fall back to: report it loudly, do not raise."""
|
||||
_firebase_config(_workout_sync, tmp_path, monkeypatch)
|
||||
_firebase_config(_sync_client, tmp_path, monkeypatch)
|
||||
|
||||
def _boom(*_args: object, **_kwargs: object) -> None:
|
||||
raise error
|
||||
|
||||
monkeypatch.setattr(_workout_sync, "firebase_client_for", _boom)
|
||||
monkeypatch.setattr(_sync_client, "firebase_client_for", _boom)
|
||||
assert _workout_sync.sync_client() is None
|
||||
|
||||
def test_warns_when_firebase_only_is_unusable(
|
||||
@ -96,13 +96,13 @@ class TestSyncClient:
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Warns when firebase only is unusable."""
|
||||
_firebase_config(_workout_sync, tmp_path, monkeypatch)
|
||||
_firebase_config(_sync_client, tmp_path, monkeypatch)
|
||||
|
||||
def _boom(*_args: object, **_kwargs: object) -> None:
|
||||
message = "backend down"
|
||||
raise FirebaseSyncError(message)
|
||||
|
||||
monkeypatch.setattr(_workout_sync, "firebase_client_for", _boom)
|
||||
monkeypatch.setattr(_sync_client, "firebase_client_for", _boom)
|
||||
with caplog.at_level("WARNING"):
|
||||
_workout_sync.sync_client()
|
||||
assert "backend down" in caplog.text
|
||||
|
||||
@ -11,7 +11,7 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync import ConfigError
|
||||
|
||||
from screen_locker import _workout_sync
|
||||
from screen_locker import _sync_client, _workout_sync
|
||||
from screen_locker.tests._workout_sync_fixtures import _firebase_config
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@ -36,9 +36,9 @@ class TestRemoteClient:
|
||||
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Configured: reads union both, so either backend's workout counts."""
|
||||
_firebase_config(_workout_sync, tmp_path, monkeypatch)
|
||||
_firebase_config(_sync_client, tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
_workout_sync,
|
||||
_sync_client,
|
||||
"mirror_client_for",
|
||||
lambda _app, client: ("mirror", client),
|
||||
)
|
||||
@ -50,13 +50,13 @@ class TestRemoteClient:
|
||||
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A broken Firebase must degrade to GitHub, never fail the pull."""
|
||||
_firebase_config(_workout_sync, tmp_path, monkeypatch)
|
||||
_firebase_config(_sync_client, tmp_path, monkeypatch)
|
||||
|
||||
def _boom(*_args: object, **_kwargs: object) -> None:
|
||||
message = "no password"
|
||||
raise ConfigError(message)
|
||||
|
||||
monkeypatch.setattr(_workout_sync, "mirror_client_for", _boom)
|
||||
monkeypatch.setattr(_sync_client, "mirror_client_for", _boom)
|
||||
github = object()
|
||||
|
||||
assert _workout_sync.remote_client(github) is github
|
||||
|
||||
@ -15,7 +15,7 @@ from crdt_sync import (
|
||||
GitHubSyncError,
|
||||
)
|
||||
|
||||
from screen_locker import _workout_sync
|
||||
from screen_locker import _sync_client, _workout_sync
|
||||
from screen_locker.tests._workout_sync_fixtures import (
|
||||
_firebase_config,
|
||||
_manual_payload,
|
||||
@ -36,7 +36,7 @@ class TestPullSyncedWorkout:
|
||||
|
||||
def test_returns_none_none_when_no_token_is_configured(self) -> None:
|
||||
"""Returns none none when no token is configured."""
|
||||
with patch.object(_workout_sync, "GitHubSyncClient") as client_cls:
|
||||
with patch.object(_sync_client, "GitHubSyncClient") as client_cls:
|
||||
assert _workout_sync.pull_synced_workout() == (None, None)
|
||||
client_cls.assert_not_called()
|
||||
|
||||
@ -45,7 +45,7 @@ class TestPullSyncedWorkout:
|
||||
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
|
||||
client = MagicMock()
|
||||
client.list_directory.side_effect = GitHubSyncError("offline")
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
assert _workout_sync.pull_synced_workout() == (None, "offline")
|
||||
|
||||
def test_does_not_propagate_a_firebase_sync_error(self) -> None:
|
||||
@ -58,7 +58,7 @@ class TestPullSyncedWorkout:
|
||||
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
|
||||
client = MagicMock()
|
||||
client.list_directory.side_effect = FirebaseSyncError("firebase exploded")
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
data, error = _workout_sync.pull_synced_workout()
|
||||
assert data is None
|
||||
assert error == "firebase exploded"
|
||||
@ -71,10 +71,10 @@ class TestPullSyncedWorkout:
|
||||
The configuration the locker actually died in, pinned in its own right
|
||||
so a future GitHub-only narrowing of the handler cannot pass.
|
||||
"""
|
||||
_firebase_config(_workout_sync, tmp_path, monkeypatch)
|
||||
_firebase_config(_sync_client, tmp_path, monkeypatch)
|
||||
client = MagicMock()
|
||||
client.list_directory.side_effect = FirebaseSyncError("firebase exploded")
|
||||
monkeypatch.setattr(_workout_sync, "firebase_client_for", lambda _app: client)
|
||||
monkeypatch.setattr(_sync_client, "firebase_client_for", lambda _app: client)
|
||||
data, error = _workout_sync.pull_synced_workout()
|
||||
assert data is None
|
||||
assert error == "firebase exploded"
|
||||
@ -83,14 +83,14 @@ class TestPullSyncedWorkout:
|
||||
"""Returns none none when nothing has been pushed yet."""
|
||||
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
|
||||
client = _multi_device_client({"phone": None})
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
assert _workout_sync.pull_synced_workout() == (None, None)
|
||||
|
||||
def test_returns_none_none_when_there_are_no_devices_at_all(self) -> None:
|
||||
"""Returns none none when there are no devices at all."""
|
||||
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
|
||||
client = _multi_device_client({})
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
assert _workout_sync.pull_synced_workout() == (None, None)
|
||||
|
||||
def test_returns_the_payload_on_success(self) -> None:
|
||||
@ -100,7 +100,7 @@ class TestPullSyncedWorkout:
|
||||
client = _multi_device_client(
|
||||
{"phone": json.dumps({"a": _session_record_dict("session:a", payload)})}
|
||||
)
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
assert _workout_sync.pull_synced_workout() == (payload, None)
|
||||
|
||||
def test_finds_a_session_in_a_uuid_named_device_directory(self) -> None:
|
||||
@ -131,7 +131,7 @@ class TestPullSyncedWorkout:
|
||||
),
|
||||
}
|
||||
)
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
assert _workout_sync.pull_synced_workout() == (fresh, None)
|
||||
|
||||
def test_returns_the_highest_clock_session_across_devices(self) -> None:
|
||||
@ -163,7 +163,7 @@ class TestPullSyncedWorkout:
|
||||
),
|
||||
}
|
||||
)
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
data, error = _workout_sync.pull_synced_workout()
|
||||
assert error is None
|
||||
assert data == newest
|
||||
@ -201,7 +201,7 @@ class TestPullSyncedWorkout:
|
||||
)
|
||||
}
|
||||
)
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
data, error = _workout_sync.pull_synced_workout()
|
||||
assert error is None
|
||||
assert data == session
|
||||
@ -216,12 +216,12 @@ class TestPullSyncedWorkout:
|
||||
"phone": json.dumps({"a": _session_record_dict("session:a", payload)}),
|
||||
}
|
||||
)
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
assert _workout_sync.pull_synced_workout() == (payload, None)
|
||||
|
||||
def test_returns_none_none_when_every_device_log_is_corrupt(self) -> None:
|
||||
"""Returns none none when every device log is corrupt."""
|
||||
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
|
||||
client = _multi_device_client({"corrupt": "{not valid json"})
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
assert _workout_sync.pull_synced_workout() == (None, None)
|
||||
|
||||
@ -13,7 +13,7 @@ from crdt_sync import (
|
||||
GitHubSyncError,
|
||||
)
|
||||
|
||||
from screen_locker import _workout_sync
|
||||
from screen_locker import _sync_client, _workout_sync
|
||||
from screen_locker.tests._workout_sync_fixtures import (
|
||||
_manual_payload,
|
||||
_manual_record_dict,
|
||||
@ -33,7 +33,7 @@ class TestPullAllManualRecords:
|
||||
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
|
||||
client = MagicMock()
|
||||
client.list_directory.side_effect = GitHubSyncError("offline")
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
assert _workout_sync.pull_all_manual_records() == []
|
||||
|
||||
def test_merges_manual_records_across_devices(self) -> None:
|
||||
@ -49,7 +49,7 @@ class TestPullAllManualRecords:
|
||||
),
|
||||
}
|
||||
)
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
result = _workout_sync.pull_all_manual_records()
|
||||
assert sorted(rid for rid, _ in result) == ["manual:a", "manual:b"]
|
||||
|
||||
@ -66,7 +66,7 @@ class TestPullAllManualRecords:
|
||||
"corrupt": "{not json",
|
||||
}
|
||||
)
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
result = _workout_sync.pull_all_manual_records()
|
||||
assert [rid for rid, _ in result] == ["manual:a"]
|
||||
|
||||
@ -95,7 +95,7 @@ class TestPullAllManualRecords:
|
||||
),
|
||||
}
|
||||
)
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
result = _workout_sync.pull_all_manual_records()
|
||||
assert len(result) == 1
|
||||
assert result[0][1]["cost"] == "NEW"
|
||||
@ -125,7 +125,7 @@ class TestPullAllManualRecords:
|
||||
),
|
||||
}
|
||||
)
|
||||
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
result = _workout_sync.pull_all_manual_records()
|
||||
assert len(result) == 1
|
||||
assert result[0][1]["cost"] == "NEW"
|
||||
|
||||
15
scripts/__init__.py
Normal file
15
scripts/__init__.py
Normal file
@ -0,0 +1,15 @@
|
||||
"""Maintenance and verification scripts for screen-locker.
|
||||
|
||||
A real package rather than a loose directory, so the shared helpers split out
|
||||
of the verification gates (``_xvfb_reexec``, ``_popup_form_check``) are
|
||||
importable as ``scripts.<name>``.
|
||||
|
||||
Both invocation styles still work and both are used:
|
||||
|
||||
* ``python3 -m scripts.verify_screen_fits`` -- pre-commit
|
||||
* ``python3 scripts/verify_lock_popup_safety.py`` -- CI
|
||||
|
||||
The second puts ``scripts/`` itself on ``sys.path`` instead of the repo root,
|
||||
so the gates that import a sibling try the package-qualified name first and
|
||||
fall back to the bare one.
|
||||
"""
|
||||
201
scripts/_popup_form_check.py
Normal file
201
scripts/_popup_form_check.py
Normal file
@ -0,0 +1,201 @@
|
||||
"""The real manual-workout form, checked for popups, plus the tick helpers.
|
||||
|
||||
Split out of ``verify_lock_popup_safety.py`` to keep every file under the
|
||||
250-line cap. That script imports ``check_real_form_survives`` and runs it as
|
||||
one of its two checks.
|
||||
|
||||
The point of the check: the evidence form must build every widget inline on
|
||||
the lock surface. A widget that opens its own toplevel (an OptionMenu, a
|
||||
messagebox) would appear *above* the lock and hand back an escape hatch.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from gatelock import LockConfig, RecoveryLoop
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
|
||||
from screen_locker._surface_group import FrameGroup
|
||||
from screen_locker._ui_widgets import UIWidgetsMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
TICK_MS = 1000
|
||||
TICKS = 5
|
||||
|
||||
|
||||
class HostileLock:
|
||||
"""gatelock's two recovery-tick behaviours over a real Tk root."""
|
||||
|
||||
def __init__(self, root: tk.Tk) -> None:
|
||||
"""Take the global grab and start ticking."""
|
||||
self.root = root
|
||||
self.ticks = 0
|
||||
# A RecoveryLoop built only to borrow gatelock's real grab predicate;
|
||||
# this harness drives the ticks itself, so the collaborators are never
|
||||
# called -- the same MagicMock stand-ins gatelock's own tests use.
|
||||
#
|
||||
# This is the gatelock 0.4.0 signature, which is what requirements.txt
|
||||
# pins. gatelock 0.5.0 regroups these into a RecoveryCollaborators
|
||||
# object, so running against a locally-installed 0.5.0 raises
|
||||
# "takes 3 positional arguments but 6 were given" -- that is an
|
||||
# environment drift, not a bug here. Fix it by matching the pin:
|
||||
# pip install -e . && pip install -r requirements.txt
|
||||
self._loop = RecoveryLoop(
|
||||
root, LockConfig(mode="hard"), MagicMock(), MagicMock(), MagicMock()
|
||||
)
|
||||
root.grab_set_global()
|
||||
root.after(TICK_MS, self._tick)
|
||||
|
||||
def _tick(self) -> None:
|
||||
"""Lift the surface and re-take the grab, exactly as gatelock does."""
|
||||
self.root.lift()
|
||||
if not self._loop.holds_grab():
|
||||
self.root.grab_set_global()
|
||||
# Counted only after the work, so a raising tick does not count. Tk
|
||||
# swallows exceptions from `after` callbacks, and this harness once
|
||||
# reported OK while every tick was dying on an AttributeError.
|
||||
self.ticks += 1
|
||||
self.root.after(TICK_MS, self._tick)
|
||||
|
||||
|
||||
def run_ticks(
|
||||
root: tk.Tk, judge: Callable[[], bool], setup: Callable[[], None] | None = None
|
||||
) -> bool:
|
||||
"""Tick hostilely TICKS times, then let ``judge`` say what survived.
|
||||
|
||||
``setup`` runs AFTER the lock has taken its grab, which is the order the
|
||||
real thing has: the user opens a widget on an already-grabbed lock. Posting
|
||||
a menu first would just let the lock's initial ``grab_set_global()`` take
|
||||
it, proving nothing about the recovery tick.
|
||||
"""
|
||||
verdict = False
|
||||
|
||||
def decide() -> None:
|
||||
nonlocal verdict
|
||||
verdict = judge()
|
||||
|
||||
lock = HostileLock(root)
|
||||
if setup is not None:
|
||||
root.after(200, setup)
|
||||
root.after(TICK_MS * TICKS + 400, decide)
|
||||
root.after(TICK_MS * TICKS + 600, root.quit)
|
||||
root.mainloop()
|
||||
root.destroy()
|
||||
if lock.ticks < TICKS:
|
||||
_logger.error(
|
||||
" only %d of %d hostile ticks completed -- the harness itself is "
|
||||
"broken, so this result proves nothing",
|
||||
lock.ticks,
|
||||
TICKS,
|
||||
)
|
||||
return False
|
||||
return verdict
|
||||
|
||||
|
||||
def leaf(name: object) -> str:
|
||||
"""A Tk window path shortened to its last component, "root" for ``.``."""
|
||||
if not name:
|
||||
return "<nothing>"
|
||||
return str(name).rsplit(".", 1)[-1] or "root"
|
||||
|
||||
|
||||
def grab_holder(root: tk.Tk) -> str:
|
||||
"""The leaf name of whatever currently holds the grab."""
|
||||
return leaf(root.tk.call("grab", "current", root))
|
||||
|
||||
|
||||
class FormHost(UIWidgetsMixin, ManualWorkoutDialogMixin):
|
||||
"""The two hooks the mixin requires, over a real Tk root."""
|
||||
|
||||
def __init__(self, root: tk.Tk) -> None:
|
||||
"""Set only the attributes the form actually reads."""
|
||||
self.root = root
|
||||
self.demo_mode = False
|
||||
self.log_file = (
|
||||
Path(__file__).resolve().parent.parent
|
||||
/ "screen_locker"
|
||||
/ "workout_log.json"
|
||||
)
|
||||
self._colors = LockConfig()
|
||||
self.container = FrameGroup.single(root, bg=self._colors.bg)
|
||||
|
||||
def _on_manual_workout_saved(self, entry: dict[str, object]) -> None:
|
||||
"""Unused here; the form is never submitted."""
|
||||
|
||||
def _on_manual_workout_cancelled(self) -> None:
|
||||
"""Unused here; BACK is never pressed."""
|
||||
|
||||
# Public wrappers so this script never reaches into the mixin's
|
||||
# private surface from outside the class.
|
||||
def render(self) -> None:
|
||||
"""Paint the manual-workout form into the container."""
|
||||
self._show_manual_workout_form()
|
||||
|
||||
def state(self) -> tuple[str, bool, bool]:
|
||||
"""(selected sport code, other fields shown, table-tennis shown)."""
|
||||
return (
|
||||
self._current_mw_sport(),
|
||||
bool(self._mw_other_frame.winfo_ismapped()),
|
||||
bool(self._mw_tt_frame.winfo_ismapped()),
|
||||
)
|
||||
|
||||
|
||||
def radios(widget: tk.Misc) -> list[tk.Radiobutton]:
|
||||
"""Every Radiobutton under ``widget``, depth-first."""
|
||||
found: list[tk.Radiobutton] = []
|
||||
for child in widget.winfo_children():
|
||||
if isinstance(child, tk.Radiobutton):
|
||||
found.append(child)
|
||||
found.extend(radios(child))
|
||||
return found
|
||||
|
||||
|
||||
def check_real_form_survives() -> bool:
|
||||
"""Build the production form, pick "Other", hold it through the ticks."""
|
||||
root = tk.Tk()
|
||||
root.geometry("1600x1200+0+0")
|
||||
host = FormHost(root)
|
||||
host.render()
|
||||
root.update()
|
||||
|
||||
buttons = radios(root)
|
||||
labels = [b.cget("text") for b in buttons]
|
||||
_logger.info(" sport radio buttons rendered: %s", labels)
|
||||
if len(buttons) != len(_manual_workout.SPORT_LABELS):
|
||||
_logger.error(
|
||||
" expected one radio button per sport (%d), got %d",
|
||||
len(_manual_workout.SPORT_LABELS),
|
||||
len(labels),
|
||||
)
|
||||
root.destroy()
|
||||
return False
|
||||
|
||||
def pick_other() -> None:
|
||||
buttons[1].invoke()
|
||||
root.update()
|
||||
|
||||
def judge() -> bool:
|
||||
"""The Other sport must still be selected, with its own fields shown."""
|
||||
sport, other_shown, tt_shown = host.state()
|
||||
_logger.info(
|
||||
" radio buttons after %d ticks: grab=%s sport=%r other_fields=%s "
|
||||
"tt_fields=%s",
|
||||
TICKS,
|
||||
grab_holder(root),
|
||||
sport,
|
||||
other_shown,
|
||||
tt_shown,
|
||||
)
|
||||
return sport == _manual_workout.SPORT_OTHER and other_shown and not tt_shown
|
||||
|
||||
return run_ticks(root, judge, setup=pick_other)
|
||||
72
scripts/_xvfb_reexec.py
Normal file
72
scripts/_xvfb_reexec.py
Normal file
@ -0,0 +1,72 @@
|
||||
"""Re-run a GUI check script on a throwaway X display.
|
||||
|
||||
Split out of ``verify_lock_popup_safety.py`` and ``verify_screen_fits.py``
|
||||
to keep every file under the 250-line cap. Both had their own near-identical
|
||||
copy; they differ only in the sentinel env var and how the inner process is
|
||||
addressed, so both are parameters here.
|
||||
|
||||
Each script runs itself twice: the outer run starts ``xvfb-run`` and re-execs,
|
||||
the inner run (marked by the sentinel) does the real work against that
|
||||
display. Without the sentinel the inner process would start another Xvfb
|
||||
forever.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Comfortably bigger than every size under test, so each surface is sized by
|
||||
# the geometry the harness sets rather than clamped by the display.
|
||||
_SCREEN_ARG = "-screen 0 1600x1200x24"
|
||||
|
||||
|
||||
def reexec_under_xvfb(
|
||||
*,
|
||||
inner_env: str,
|
||||
module: str | None = None,
|
||||
script: Path | None = None,
|
||||
) -> int:
|
||||
"""Re-run this check on a throwaway X display, returning its exit code.
|
||||
|
||||
Exactly one of *module* (run as ``python -m module`` from the repo root)
|
||||
or *script* (run as an absolute path) identifies the inner process; that
|
||||
difference is why the two callers cannot share a single hardcoded form.
|
||||
|
||||
Args:
|
||||
inner_env: Sentinel env var set for the inner run, so it knows not to
|
||||
start another Xvfb.
|
||||
module: Dotted module path to run with ``-m``.
|
||||
script: Absolute path of the script file to run.
|
||||
|
||||
Returns:
|
||||
The inner process's exit code, or 1 if ``xvfb-run`` is unavailable.
|
||||
"""
|
||||
if (module is None) == (script is None):
|
||||
msg = "pass exactly one of module= or script="
|
||||
raise ValueError(msg)
|
||||
|
||||
xvfb_run = shutil.which("xvfb-run")
|
||||
if xvfb_run is None:
|
||||
_logger.error(
|
||||
"xvfb-run not found. Install it with: sudo pacman -S --needed "
|
||||
"xorg-server-xvfb"
|
||||
)
|
||||
return 1
|
||||
|
||||
env = dict(os.environ, **{inner_env: "1"})
|
||||
repo_root = Path(__file__).resolve().parent.parent
|
||||
# Absolute argv, no shell.
|
||||
target = ["-m", module] if module is not None else [str(script)]
|
||||
return subprocess.run(
|
||||
[xvfb_run, "-a", "-s", _SCREEN_ARG, sys.executable, *target],
|
||||
check=False,
|
||||
cwd=repo_root,
|
||||
env=env,
|
||||
).returncode
|
||||
@ -4,13 +4,17 @@
|
||||
import logging
|
||||
import sys
|
||||
|
||||
MAX_LINES = 400
|
||||
MAX_LINES = 250
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Return 1 if any file exceeds the line limit, else 0."""
|
||||
# Without this the module relies on logging's last-resort handler, which
|
||||
# drops anything below WARNING and prints no context — a hook that fails
|
||||
# without saying which file is a silent failure.
|
||||
logging.basicConfig(format="%(levelname)s: %(message)s", stream=sys.stderr)
|
||||
failed = False
|
||||
for filepath in sys.argv[1:]:
|
||||
try:
|
||||
@ -27,6 +31,15 @@ def main() -> int:
|
||||
failed = True
|
||||
continue
|
||||
if count > MAX_LINES:
|
||||
# A bare non-zero exit tells nobody which file blew the cap, so the
|
||||
# violation has to name itself and the size of the split it needs.
|
||||
_logger.error(
|
||||
"%s is %d lines — %d over the %d-line cap. Split it before committing.",
|
||||
filepath,
|
||||
count,
|
||||
count - MAX_LINES,
|
||||
MAX_LINES,
|
||||
)
|
||||
failed = True
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
@ -51,8 +51,12 @@ _LOUD_CALLS = (
|
||||
"ScaffoldMessenger",
|
||||
)
|
||||
|
||||
# `} on Foo catch (e) {`, `} catch (e) {`, `on Foo {`.
|
||||
_CATCH_RE = re.compile(r"\bcatch\s*\(|\bon\s+\w+\s*\{")
|
||||
# `} on Foo catch (e) {`, `} catch (e) {`, `} on Foo {`.
|
||||
#
|
||||
# The bare `on Foo {` form requires the preceding `}` of the try block: without
|
||||
# it this also matched `extension StorageServiceBackup on StorageService {`,
|
||||
# reporting an extension declaration as a swallowed exception.
|
||||
_CATCH_RE = re.compile(r"\bcatch\s*\(|\}\s*on\s+\w+\s*\{")
|
||||
|
||||
# `.catchError((_) {})` and friends -- an empty body is always silent.
|
||||
_EMPTY_CATCH_ERROR_RE = re.compile(r"\.catchError\(\s*\([^)]*\)\s*(?:=>\s*)?\{\s*\}")
|
||||
|
||||
75
scripts/split_dart_test.py
Normal file
75
scripts/split_dart_test.py
Normal file
@ -0,0 +1,75 @@
|
||||
"""Split a Dart test file at top-level `group(` boundaries.
|
||||
|
||||
Each output file reuses the original's imports and its main() setup preamble
|
||||
(everything between `void main() {` and the first top-level group), so every
|
||||
part runs the same fixtures the original did.
|
||||
|
||||
Usage:
|
||||
split_dart_test.py <file> <out1>:<firstGroupIdx> [<out2>:<idx> ...]
|
||||
|
||||
Indices are 0-based positions in the top-level group list; each output takes
|
||||
groups[idx:next_idx]. The source file keeps groups[:first_idx].
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
|
||||
def top_level_groups(lines: list[str]) -> list[int]:
|
||||
"""Return 0-based line indices of every top-level test boundary.
|
||||
|
||||
Screen tests are often a flat list of `testWidgets(` calls with no
|
||||
`group(` at all, so both count as a split point.
|
||||
"""
|
||||
return [
|
||||
i
|
||||
for i, ln in enumerate(lines)
|
||||
if re.match(r"^ (group|testWidgets|test)\(", ln)
|
||||
]
|
||||
|
||||
|
||||
def split(path: Path, specs: list[tuple[Path, int]]) -> None:
|
||||
"""Write each spec's group range to its own file, trimming the source."""
|
||||
lines = path.read_text().splitlines(keepends=True)
|
||||
groups = top_level_groups(lines)
|
||||
main_idx = next(i for i, ln in enumerate(lines) if ln.startswith("void main("))
|
||||
header = "".join(lines[:main_idx])
|
||||
preamble = "".join(lines[main_idx + 1 : groups[0]])
|
||||
|
||||
# Fixtures and fake classes often sit AFTER main(). Every split file needs
|
||||
# them too, or it fails to compile on a helper the original defined once.
|
||||
main_end = next(
|
||||
(i for i in range(len(lines) - 1, main_idx, -1) if lines[i].startswith("}")),
|
||||
len(lines) - 1,
|
||||
)
|
||||
trailer = "".join(lines[main_end + 1 :])
|
||||
|
||||
bounds = [i for _, i in specs] + [len(groups)]
|
||||
for (out, start), end in zip(specs, bounds[1:], strict=False):
|
||||
first = groups[start]
|
||||
last = groups[end] if end < len(groups) else main_end
|
||||
body = "".join(lines[first:last]).rstrip("\n")
|
||||
out.write_text(f"{header}void main() {{\n{preamble}{body}\n}}\n{trailer}")
|
||||
|
||||
keep = groups[specs[0][1]]
|
||||
path.write_text(
|
||||
"".join(lines[:keep]).rstrip("\n") + "\n}\n" + trailer,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Parse argv and run the split."""
|
||||
src = Path(sys.argv[1])
|
||||
specs = []
|
||||
for arg in sys.argv[2:]:
|
||||
name, idx = arg.rsplit(":", 1)
|
||||
specs.append((src.parent / name, int(idx)))
|
||||
split(src, specs)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@ -22,30 +22,25 @@ whole ``tk`` module for every test so the suite can never reach a real
|
||||
display. This script re-executes itself under Xvfb instead, so a global grab
|
||||
can never freeze the developer's own session. Run it directly, or let CI:
|
||||
|
||||
python3 ~/screen-locker/scripts/verify_lock_popup_safety.py
|
||||
python3 -m scripts.verify_lock_popup_safety # from the repo root
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from gatelock import LockConfig, RecoveryLoop
|
||||
from gatelock import RecoveryLoop
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
|
||||
from screen_locker._surface_group import FrameGroup
|
||||
from screen_locker._ui_widgets import UIWidgetsMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from scripts._popup_form_check import (
|
||||
check_real_form_survives,
|
||||
grab_holder,
|
||||
leaf,
|
||||
run_ticks,
|
||||
)
|
||||
from scripts._xvfb_reexec import reexec_under_xvfb
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
@ -54,105 +49,6 @@ TICKS = 5
|
||||
INNER_ENV = "_LOCK_POPUP_CHECK_INNER"
|
||||
|
||||
|
||||
def reexec_under_xvfb() -> int:
|
||||
"""Re-run this script on a throwaway X display, returning its exit code."""
|
||||
xvfb_run = shutil.which("xvfb-run")
|
||||
if xvfb_run is None:
|
||||
_logger.error(
|
||||
"xvfb-run not found. Install it with: sudo pacman -S --needed "
|
||||
"xorg-server-xvfb"
|
||||
)
|
||||
return 1
|
||||
env = dict(os.environ, **{INNER_ENV: "1"})
|
||||
# Absolute argv, no shell.
|
||||
return subprocess.run(
|
||||
[
|
||||
xvfb_run,
|
||||
"-a",
|
||||
"-s",
|
||||
"-screen 0 1600x1200x24",
|
||||
sys.executable,
|
||||
str(Path(__file__).resolve()),
|
||||
],
|
||||
check=False,
|
||||
env=env,
|
||||
).returncode
|
||||
|
||||
|
||||
class HostileLock:
|
||||
"""gatelock's two recovery-tick behaviours over a real Tk root."""
|
||||
|
||||
def __init__(self, root: tk.Tk) -> None:
|
||||
"""Take the global grab and start ticking."""
|
||||
self.root = root
|
||||
self.ticks = 0
|
||||
# A RecoveryLoop built only to borrow gatelock's real grab predicate;
|
||||
# this harness drives the ticks itself, so the collaborators are never
|
||||
# called -- the same MagicMock stand-ins gatelock's own tests use.
|
||||
self._loop = RecoveryLoop(
|
||||
root, LockConfig(mode="hard"), MagicMock(), MagicMock(), MagicMock()
|
||||
)
|
||||
root.grab_set_global()
|
||||
root.after(TICK_MS, self._tick)
|
||||
|
||||
def _tick(self) -> None:
|
||||
"""Lift the surface and re-take the grab, exactly as gatelock does."""
|
||||
self.root.lift()
|
||||
if not self._loop.holds_grab():
|
||||
self.root.grab_set_global()
|
||||
# Counted only after the work, so a raising tick does not count. Tk
|
||||
# swallows exceptions from `after` callbacks, and this harness once
|
||||
# reported OK while every tick was dying on an AttributeError.
|
||||
self.ticks += 1
|
||||
self.root.after(TICK_MS, self._tick)
|
||||
|
||||
|
||||
def run_ticks(
|
||||
root: tk.Tk, judge: Callable[[], bool], setup: Callable[[], None] | None = None
|
||||
) -> bool:
|
||||
"""Tick hostilely TICKS times, then let ``judge`` say what survived.
|
||||
|
||||
``setup`` runs AFTER the lock has taken its grab, which is the order the
|
||||
real thing has: the user opens a widget on an already-grabbed lock. Posting
|
||||
a menu first would just let the lock's initial ``grab_set_global()`` take
|
||||
it, proving nothing about the recovery tick.
|
||||
"""
|
||||
verdict = False
|
||||
|
||||
def decide() -> None:
|
||||
nonlocal verdict
|
||||
verdict = judge()
|
||||
|
||||
lock = HostileLock(root)
|
||||
if setup is not None:
|
||||
root.after(200, setup)
|
||||
root.after(TICK_MS * TICKS + 400, decide)
|
||||
root.after(TICK_MS * TICKS + 600, root.quit)
|
||||
root.mainloop()
|
||||
root.destroy()
|
||||
if lock.ticks < TICKS:
|
||||
_logger.error(
|
||||
" only %d of %d hostile ticks completed -- the harness itself is "
|
||||
"broken, so this result proves nothing",
|
||||
lock.ticks,
|
||||
TICKS,
|
||||
)
|
||||
return False
|
||||
return verdict
|
||||
|
||||
|
||||
def leaf(name: object) -> str:
|
||||
"""A Tk window path shortened to its last component, "root" for ``.``."""
|
||||
if not name:
|
||||
return "<nothing>"
|
||||
return str(name).rsplit(".", 1)[-1] or "root"
|
||||
|
||||
|
||||
def grab_holder(root: tk.Tk) -> str:
|
||||
"""The leaf name of whatever currently holds the grab."""
|
||||
return leaf(root.tk.call("grab", "current", root))
|
||||
|
||||
|
||||
def check_optionmenu_still_fails() -> bool:
|
||||
"""Show the original mechanism: a posted menu gets covered by the lift."""
|
||||
root = tk.Tk()
|
||||
@ -187,98 +83,13 @@ def check_optionmenu_still_fails() -> bool:
|
||||
return run_ticks(root, judge, setup=open_menu)
|
||||
|
||||
|
||||
class FormHost(UIWidgetsMixin, ManualWorkoutDialogMixin):
|
||||
"""The two hooks the mixin requires, over a real Tk root."""
|
||||
|
||||
def __init__(self, root: tk.Tk) -> None:
|
||||
"""Set only the attributes the form actually reads."""
|
||||
self.root = root
|
||||
self.demo_mode = False
|
||||
self.log_file = (
|
||||
Path(__file__).resolve().parent.parent
|
||||
/ "screen_locker"
|
||||
/ "workout_log.json"
|
||||
)
|
||||
self._colors = LockConfig()
|
||||
self.container = FrameGroup.single(root, bg=self._colors.bg)
|
||||
|
||||
def _on_manual_workout_saved(self, entry: dict[str, object]) -> None:
|
||||
"""Unused here; the form is never submitted."""
|
||||
|
||||
def _on_manual_workout_cancelled(self) -> None:
|
||||
"""Unused here; BACK is never pressed."""
|
||||
|
||||
# Public wrappers so this script never reaches into the mixin's
|
||||
# private surface from outside the class.
|
||||
def render(self) -> None:
|
||||
"""Paint the manual-workout form into the container."""
|
||||
self._show_manual_workout_form()
|
||||
|
||||
def state(self) -> tuple[str, bool, bool]:
|
||||
"""(selected sport code, other fields shown, table-tennis shown)."""
|
||||
return (
|
||||
self._current_mw_sport(),
|
||||
bool(self._mw_other_frame.winfo_ismapped()),
|
||||
bool(self._mw_tt_frame.winfo_ismapped()),
|
||||
)
|
||||
|
||||
|
||||
def radios(widget: tk.Misc) -> list[tk.Radiobutton]:
|
||||
"""Every Radiobutton under ``widget``, depth-first."""
|
||||
found: list[tk.Radiobutton] = []
|
||||
for child in widget.winfo_children():
|
||||
if isinstance(child, tk.Radiobutton):
|
||||
found.append(child)
|
||||
found.extend(radios(child))
|
||||
return found
|
||||
|
||||
|
||||
def check_real_form_survives() -> bool:
|
||||
"""Build the production form, pick "Other", hold it through the ticks."""
|
||||
root = tk.Tk()
|
||||
root.geometry("1600x1200+0+0")
|
||||
host = FormHost(root)
|
||||
host.render()
|
||||
root.update()
|
||||
|
||||
buttons = radios(root)
|
||||
labels = [b.cget("text") for b in buttons]
|
||||
_logger.info(" sport radio buttons rendered: %s", labels)
|
||||
if len(buttons) != len(_manual_workout.SPORT_LABELS):
|
||||
_logger.error(
|
||||
" expected one radio button per sport (%d), got %d",
|
||||
len(_manual_workout.SPORT_LABELS),
|
||||
len(labels),
|
||||
)
|
||||
root.destroy()
|
||||
return False
|
||||
|
||||
def pick_other() -> None:
|
||||
buttons[1].invoke()
|
||||
root.update()
|
||||
|
||||
def judge() -> bool:
|
||||
"""The Other sport must still be selected, with its own fields shown."""
|
||||
sport, other_shown, tt_shown = host.state()
|
||||
_logger.info(
|
||||
" radio buttons after %d ticks: grab=%s sport=%r other_fields=%s "
|
||||
"tt_fields=%s",
|
||||
TICKS,
|
||||
grab_holder(root),
|
||||
sport,
|
||||
other_shown,
|
||||
tt_shown,
|
||||
)
|
||||
return sport == _manual_workout.SPORT_OTHER and other_shown and not tt_shown
|
||||
|
||||
return run_ticks(root, judge, setup=pick_other)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Run both checks under Xvfb and report which held."""
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
|
||||
if os.environ.get(INNER_ENV) != "1":
|
||||
return reexec_under_xvfb()
|
||||
return reexec_under_xvfb(
|
||||
inner_env=INNER_ENV, module="scripts.verify_lock_popup_safety"
|
||||
)
|
||||
|
||||
if not hasattr(RecoveryLoop, "holds_grab"):
|
||||
_logger.error(
|
||||
|
||||
@ -32,8 +32,6 @@ from dataclasses import dataclass
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@ -47,6 +45,7 @@ from screen_locker._surface_group import FrameGroup
|
||||
from screen_locker._ui_flows import UIFlowsMixin
|
||||
from screen_locker._ui_flows_relaxed import UIFlowsRelaxedMixin
|
||||
from screen_locker._ui_widgets import UIWidgetsMixin
|
||||
from scripts._xvfb_reexec import reexec_under_xvfb
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
@ -74,34 +73,6 @@ LONG_MESSAGE = (
|
||||
)
|
||||
|
||||
|
||||
def reexec_under_xvfb() -> int:
|
||||
"""Re-run this script on a throwaway X display, returning its exit code."""
|
||||
xvfb_run = shutil.which("xvfb-run")
|
||||
if xvfb_run is None:
|
||||
_logger.error(
|
||||
"xvfb-run not found. Install it with: sudo pacman -S --needed "
|
||||
"xorg-server-xvfb"
|
||||
)
|
||||
return 1
|
||||
env = dict(os.environ, **{INNER_ENV: "1"})
|
||||
return subprocess.run(
|
||||
[
|
||||
xvfb_run,
|
||||
"-a",
|
||||
# Bigger than every size under test, so each surface is sized by
|
||||
# the geometry this harness sets rather than clamped by the display.
|
||||
"-s",
|
||||
"-screen 0 1600x1200x24",
|
||||
sys.executable,
|
||||
"-m",
|
||||
"scripts.verify_screen_fits",
|
||||
],
|
||||
check=False,
|
||||
cwd=Path(__file__).resolve().parent.parent,
|
||||
env=env,
|
||||
).returncode
|
||||
|
||||
|
||||
class ScreenHost(
|
||||
UIWidgetsMixin,
|
||||
UIFlowsMixin,
|
||||
@ -246,7 +217,9 @@ def main() -> int:
|
||||
"""Measure every screen and fail if any of them overflows."""
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
|
||||
if os.environ.get(INNER_ENV) != "1":
|
||||
return reexec_under_xvfb()
|
||||
return reexec_under_xvfb(
|
||||
inner_env=INNER_ENV, module="scripts.verify_screen_fits"
|
||||
)
|
||||
|
||||
_logger.info("Measuring every lock screen against every supported panel:")
|
||||
results = measure_all()
|
||||
|
||||
@ -10,6 +10,10 @@ library;
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
|
||||
part 'manual_workout_budget.dart';
|
||||
part 'manual_workout_sync.dart';
|
||||
part 'manual_workout_validation.dart';
|
||||
|
||||
// ── Shared constants ─────────────────────────────────────────────────────────
|
||||
// Hand-maintained mirror of the Python source of truth in
|
||||
// `screen_locker/_constants.py` (the `MANUAL_WORKOUT_*` values).
|
||||
@ -181,107 +185,6 @@ class ManualWorkoutDraft {
|
||||
final String equipment;
|
||||
}
|
||||
|
||||
int? _parseHhmm(String value) {
|
||||
final match = RegExp(r'^(\d{1,2}):(\d{2})$').firstMatch(value.trim());
|
||||
if (match == null) return null;
|
||||
final hours = int.parse(match.group(1)!);
|
||||
final minutes = int.parse(match.group(2)!);
|
||||
if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null;
|
||||
return hours * 60 + minutes;
|
||||
}
|
||||
|
||||
/// Minutes between start and end, or null if unparsable / not end-after-start.
|
||||
double? durationMinutes(ManualWorkoutDraft draft) {
|
||||
final start = _parseHhmm(draft.startTime);
|
||||
final end = _parseHhmm(draft.endTime);
|
||||
if (start == null || end == null || end <= start) return null;
|
||||
return (end - start).toDouble();
|
||||
}
|
||||
|
||||
/// Returns an error message if [draft] is invalid, else null.
|
||||
///
|
||||
/// Ports `validate_manual_workout`: required fields, HH:MM with end after
|
||||
/// start, minimum duration, RPE range, per-sport rules, and reflection length.
|
||||
String? validateManualWorkout(ManualWorkoutDraft draft) {
|
||||
if (!kSportChoices.contains(draft.sport)) return 'Please choose a sport';
|
||||
|
||||
final required = <String, String>{
|
||||
'Start time': draft.startTime,
|
||||
'End time': draft.endTime,
|
||||
'Location name': draft.locationName,
|
||||
'Transport method': draft.transportMethod,
|
||||
'Cost': draft.cost,
|
||||
};
|
||||
for (final entry in required.entries) {
|
||||
if (entry.value.trim().isEmpty) return '${entry.key} is required';
|
||||
}
|
||||
|
||||
final duration = durationMinutes(draft);
|
||||
if (duration == null) {
|
||||
return 'Start/end time must be valid HH:MM, with end after start';
|
||||
}
|
||||
// Accept bar carries the hidden leeway; the message advertises the round
|
||||
// number only.
|
||||
if (duration < kWorkoutDurationAcceptMinutes) {
|
||||
return 'Session must be at least $kMinWorkoutDurationMinutes '
|
||||
'minutes (currently ${duration.toStringAsFixed(0)})';
|
||||
}
|
||||
|
||||
if (draft.rpe < kManualWorkoutRpeMin || draft.rpe > kManualWorkoutRpeMax) {
|
||||
return 'RPE must be between $kManualWorkoutRpeMin '
|
||||
'and $kManualWorkoutRpeMax';
|
||||
}
|
||||
|
||||
final sportError = draft.sport == kSportTableTennis
|
||||
? _validateTableTennis(draft)
|
||||
: _validateOtherSport(draft);
|
||||
if (sportError != null) return sportError;
|
||||
|
||||
final reflections = <String, String>{
|
||||
'What went well': draft.wentWell,
|
||||
'What to improve': draft.toImprove,
|
||||
'Overall feeling': draft.overallFeeling,
|
||||
};
|
||||
for (final entry in reflections.entries) {
|
||||
final length = entry.value.trim().length;
|
||||
if (length < kManualWorkoutReflectionMinChars) {
|
||||
return '${entry.key} must be at least $kManualWorkoutReflectionMinChars '
|
||||
'characters (currently $length)';
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _validateTableTennis(ManualWorkoutDraft draft) {
|
||||
final scores = <String, int>{
|
||||
'Matches won': draft.matchesWon,
|
||||
'Matches lost': draft.matchesLost,
|
||||
'Sets won': draft.setsWon,
|
||||
'Sets lost': draft.setsLost,
|
||||
};
|
||||
for (final entry in scores.entries) {
|
||||
if (entry.value < 0) return '${entry.key} cannot be negative';
|
||||
}
|
||||
if (draft.matchesWon + draft.matchesLost == 0) {
|
||||
return 'Enter at least one match played (won + lost)';
|
||||
}
|
||||
if (draft.racket.trim().isEmpty) return 'Racket is required';
|
||||
if (draft.balls.trim().isEmpty) return 'Balls are required';
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _validateOtherSport(ManualWorkoutDraft draft) {
|
||||
if (draft.activityTypeOther.trim().isEmpty) {
|
||||
return 'Activity type is required';
|
||||
}
|
||||
final length = draft.activityDetails.trim().length;
|
||||
if (length < kManualWorkoutDescriptionMinChars) {
|
||||
return 'What was done must be at least '
|
||||
'$kManualWorkoutDescriptionMinChars characters (currently $length)';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Builds the persisted `workout_data` dict for a validated draft.
|
||||
///
|
||||
@ -329,82 +232,3 @@ Map<String, Object?> buildEntry(ManualWorkoutDraft draft) {
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/// Builds the cross-device sync payload: [buildEntry] + `kind` + `date`.
|
||||
Map<String, Object?> buildSyncPayload(ManualWorkoutDraft draft, String date) {
|
||||
return <String, Object?>{
|
||||
...buildEntry(draft),
|
||||
'kind': kManualWorkoutSyncKind,
|
||||
'date': date,
|
||||
};
|
||||
}
|
||||
|
||||
/// The stable crdt-sync record id for a manual workout.
|
||||
///
|
||||
/// Format: `manual:<date>T<HH:MM>`.
|
||||
String manualSyncRecordId(String date, String startTime) =>
|
||||
'manual:${date}T${startTime.trim()}';
|
||||
|
||||
/// Builds the crdt-sync [Record] for a manual workout, stamped with [hlc].
|
||||
Record buildManualRecord(
|
||||
ManualWorkoutDraft draft,
|
||||
String date, {
|
||||
required Hlc hlc,
|
||||
}) {
|
||||
return Record(
|
||||
id: manualSyncRecordId(date, draft.startTime),
|
||||
fields: {'payload': (buildSyncPayload(draft, date), hlc)},
|
||||
);
|
||||
}
|
||||
|
||||
/// Manual-workout counts in the rolling 7-/30-day windows (the shared budget).
|
||||
class ManualBudget {
|
||||
/// Creates a budget snapshot.
|
||||
const ManualBudget({required this.week, required this.month});
|
||||
|
||||
/// Manual workouts in the last 7 days.
|
||||
final int week;
|
||||
|
||||
/// Manual workouts in the last 30 days.
|
||||
final int month;
|
||||
|
||||
/// Whether either window has reached its limit.
|
||||
bool get exhausted =>
|
||||
week >= kManualWorkoutBudgetPer7Days ||
|
||||
month >= kManualWorkoutBudgetPer30Days;
|
||||
}
|
||||
|
||||
/// Counts DAYS with a manual workout in the rolling 7-/30-day windows.
|
||||
///
|
||||
/// The budget is counted per ENTRY, not per day: each self-report consumes its
|
||||
/// own slot, so three workouts logged on one day cost three. That matches the
|
||||
/// PC's `count_in_window` (screen_locker/_manual_workout.py), which is the
|
||||
/// source of truth — each entry separately earns weekly-count and shutdown
|
||||
/// credit, so each must separately cost budget.
|
||||
///
|
||||
/// This counted DAYS until 2026-08-09 (a `Set` of date strings) while the PC
|
||||
/// counted entries, so three same-day workouts read as 3/2 on the PC — over
|
||||
/// its 7-day cap — but 1/2 here, and the phone kept accepting. Callers pass
|
||||
/// one payload per synced record (`manual:<date>T<HH:MM>`), so same-day
|
||||
/// workouts at different times arrive as distinct payloads.
|
||||
ManualBudget countManualBudget(
|
||||
Iterable<Map<String, dynamic>> payloads,
|
||||
DateTime now,
|
||||
) {
|
||||
final today = DateTime(now.year, now.month, now.day);
|
||||
var week = 0;
|
||||
var month = 0;
|
||||
for (final payload in payloads) {
|
||||
final dateStr = payload['date'];
|
||||
if (dateStr is! String) continue;
|
||||
final date = DateTime.tryParse(dateStr);
|
||||
if (date == null) continue;
|
||||
final days = today
|
||||
.difference(DateTime(date.year, date.month, date.day))
|
||||
.inDays;
|
||||
if (days < 0) continue;
|
||||
if (days < 7) week++;
|
||||
if (days < 30) month++;
|
||||
}
|
||||
return ManualBudget(week: week, month: month);
|
||||
}
|
||||
|
||||
@ -0,0 +1,39 @@
|
||||
// Rolling manual-workout budget accounting.
|
||||
//
|
||||
// See manual_workout_validation.dart for why these are `part` files.
|
||||
part of 'manual_workout.dart';
|
||||
|
||||
/// Counts DAYS with a manual workout in the rolling 7-/30-day windows.
|
||||
///
|
||||
/// The budget is counted per ENTRY, not per day: each self-report consumes its
|
||||
/// own slot, so three workouts logged on one day cost three. That matches the
|
||||
/// PC's `count_in_window` (screen_locker/_manual_workout.py), which is the
|
||||
/// source of truth — each entry separately earns weekly-count and shutdown
|
||||
/// credit, so each must separately cost budget.
|
||||
///
|
||||
/// This counted DAYS until 2026-08-09 (a `Set` of date strings) while the PC
|
||||
/// counted entries, so three same-day workouts read as 3/2 on the PC — over
|
||||
/// its 7-day cap — but 1/2 here, and the phone kept accepting. Callers pass
|
||||
/// one payload per synced record (`manual:<date>T<HH:MM>`), so same-day
|
||||
/// workouts at different times arrive as distinct payloads.
|
||||
ManualBudget countManualBudget(
|
||||
Iterable<Map<String, dynamic>> payloads,
|
||||
DateTime now,
|
||||
) {
|
||||
final today = DateTime(now.year, now.month, now.day);
|
||||
var week = 0;
|
||||
var month = 0;
|
||||
for (final payload in payloads) {
|
||||
final dateStr = payload['date'];
|
||||
if (dateStr is! String) continue;
|
||||
final date = DateTime.tryParse(dateStr);
|
||||
if (date == null) continue;
|
||||
final days = today
|
||||
.difference(DateTime(date.year, date.month, date.day))
|
||||
.inDays;
|
||||
if (days < 0) continue;
|
||||
if (days < 7) week++;
|
||||
if (days < 30) month++;
|
||||
}
|
||||
return ManualBudget(week: week, month: month);
|
||||
}
|
||||
@ -0,0 +1,51 @@
|
||||
// The sync payload and record id for a manual workout.
|
||||
//
|
||||
// The key strings here are a cross-language contract with the Python
|
||||
// side's build_sync_payload / manual_sync_record_id -- a shared literal
|
||||
// fixture test pins them on both sides. Moving the code must not touch
|
||||
// a single key.
|
||||
part of 'manual_workout.dart';
|
||||
|
||||
/// Builds the cross-device sync payload: [buildEntry] + `kind` + `date`.
|
||||
Map<String, Object?> buildSyncPayload(ManualWorkoutDraft draft, String date) {
|
||||
return <String, Object?>{
|
||||
...buildEntry(draft),
|
||||
'kind': kManualWorkoutSyncKind,
|
||||
'date': date,
|
||||
};
|
||||
}
|
||||
|
||||
/// The stable crdt-sync record id for a manual workout.
|
||||
///
|
||||
/// Format: `manual:<date>T<HH:MM>`.
|
||||
String manualSyncRecordId(String date, String startTime) =>
|
||||
'manual:${date}T${startTime.trim()}';
|
||||
|
||||
/// Builds the crdt-sync [Record] for a manual workout, stamped with [hlc].
|
||||
Record buildManualRecord(
|
||||
ManualWorkoutDraft draft,
|
||||
String date, {
|
||||
required Hlc hlc,
|
||||
}) {
|
||||
return Record(
|
||||
id: manualSyncRecordId(date, draft.startTime),
|
||||
fields: {'payload': (buildSyncPayload(draft, date), hlc)},
|
||||
);
|
||||
}
|
||||
|
||||
/// Manual-workout counts in the rolling 7-/30-day windows (the shared budget).
|
||||
class ManualBudget {
|
||||
/// Creates a budget snapshot.
|
||||
const ManualBudget({required this.week, required this.month});
|
||||
|
||||
/// Manual workouts in the last 7 days.
|
||||
final int week;
|
||||
|
||||
/// Manual workouts in the last 30 days.
|
||||
final int month;
|
||||
|
||||
/// Whether either window has reached its limit.
|
||||
bool get exhausted =>
|
||||
week >= kManualWorkoutBudgetPer7Days ||
|
||||
month >= kManualWorkoutBudgetPer30Days;
|
||||
}
|
||||
@ -0,0 +1,108 @@
|
||||
// Draft validation: duration, per-sport rules, and the shared minimums.
|
||||
//
|
||||
// A `part` so the constants and the draft stay one library -- this file is
|
||||
// a cross-language contract with the Python side, and the JSON keys it
|
||||
// emits must not move or change.
|
||||
part of 'manual_workout.dart';
|
||||
|
||||
int? _parseHhmm(String value) {
|
||||
final match = RegExp(r'^(\d{1,2}):(\d{2})$').firstMatch(value.trim());
|
||||
if (match == null) return null;
|
||||
final hours = int.parse(match.group(1)!);
|
||||
final minutes = int.parse(match.group(2)!);
|
||||
if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null;
|
||||
return hours * 60 + minutes;
|
||||
}
|
||||
|
||||
/// Minutes between start and end, or null if unparsable / not end-after-start.
|
||||
double? durationMinutes(ManualWorkoutDraft draft) {
|
||||
final start = _parseHhmm(draft.startTime);
|
||||
final end = _parseHhmm(draft.endTime);
|
||||
if (start == null || end == null || end <= start) return null;
|
||||
return (end - start).toDouble();
|
||||
}
|
||||
|
||||
/// Returns an error message if [draft] is invalid, else null.
|
||||
///
|
||||
/// Ports `validate_manual_workout`: required fields, HH:MM with end after
|
||||
/// start, minimum duration, RPE range, per-sport rules, and reflection length.
|
||||
String? validateManualWorkout(ManualWorkoutDraft draft) {
|
||||
if (!kSportChoices.contains(draft.sport)) return 'Please choose a sport';
|
||||
|
||||
final required = <String, String>{
|
||||
'Start time': draft.startTime,
|
||||
'End time': draft.endTime,
|
||||
'Location name': draft.locationName,
|
||||
'Transport method': draft.transportMethod,
|
||||
'Cost': draft.cost,
|
||||
};
|
||||
for (final entry in required.entries) {
|
||||
if (entry.value.trim().isEmpty) return '${entry.key} is required';
|
||||
}
|
||||
|
||||
final duration = durationMinutes(draft);
|
||||
if (duration == null) {
|
||||
return 'Start/end time must be valid HH:MM, with end after start';
|
||||
}
|
||||
// Accept bar carries the hidden leeway; the message advertises the round
|
||||
// number only.
|
||||
if (duration < kWorkoutDurationAcceptMinutes) {
|
||||
return 'Session must be at least $kMinWorkoutDurationMinutes '
|
||||
'minutes (currently ${duration.toStringAsFixed(0)})';
|
||||
}
|
||||
|
||||
if (draft.rpe < kManualWorkoutRpeMin || draft.rpe > kManualWorkoutRpeMax) {
|
||||
return 'RPE must be between $kManualWorkoutRpeMin '
|
||||
'and $kManualWorkoutRpeMax';
|
||||
}
|
||||
|
||||
final sportError = draft.sport == kSportTableTennis
|
||||
? _validateTableTennis(draft)
|
||||
: _validateOtherSport(draft);
|
||||
if (sportError != null) return sportError;
|
||||
|
||||
final reflections = <String, String>{
|
||||
'What went well': draft.wentWell,
|
||||
'What to improve': draft.toImprove,
|
||||
'Overall feeling': draft.overallFeeling,
|
||||
};
|
||||
for (final entry in reflections.entries) {
|
||||
final length = entry.value.trim().length;
|
||||
if (length < kManualWorkoutReflectionMinChars) {
|
||||
return '${entry.key} must be at least $kManualWorkoutReflectionMinChars '
|
||||
'characters (currently $length)';
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _validateTableTennis(ManualWorkoutDraft draft) {
|
||||
final scores = <String, int>{
|
||||
'Matches won': draft.matchesWon,
|
||||
'Matches lost': draft.matchesLost,
|
||||
'Sets won': draft.setsWon,
|
||||
'Sets lost': draft.setsLost,
|
||||
};
|
||||
for (final entry in scores.entries) {
|
||||
if (entry.value < 0) return '${entry.key} cannot be negative';
|
||||
}
|
||||
if (draft.matchesWon + draft.matchesLost == 0) {
|
||||
return 'Enter at least one match played (won + lost)';
|
||||
}
|
||||
if (draft.racket.trim().isEmpty) return 'Racket is required';
|
||||
if (draft.balls.trim().isEmpty) return 'Balls are required';
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _validateOtherSport(ManualWorkoutDraft draft) {
|
||||
if (draft.activityTypeOther.trim().isEmpty) {
|
||||
return 'Activity type is required';
|
||||
}
|
||||
final length = draft.activityDetails.trim().length;
|
||||
if (length < kManualWorkoutDescriptionMinChars) {
|
||||
return 'What was done must be at least '
|
||||
'$kManualWorkoutDescriptionMinChars characters (currently $length)';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@ -21,6 +21,8 @@ import 'package:workout_app/services/github_device_auth.dart';
|
||||
import 'package:workout_app/services/sync_settings.dart';
|
||||
import 'package:workout_app/ui/theme.dart';
|
||||
|
||||
part 'github_mirror_screen_widgets.dart';
|
||||
|
||||
/// How to style a [_SyncStatusBadge].
|
||||
enum _SyncStatusKind { success, pending, error }
|
||||
|
||||
@ -243,199 +245,3 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
||||
}
|
||||
|
||||
/// A visible, colored status pill for the GitHub sync connection state.
|
||||
class _SyncStatusBadge extends StatelessWidget {
|
||||
const _SyncStatusBadge({required this.text, required this.kind});
|
||||
|
||||
final String text;
|
||||
final _SyncStatusKind kind;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
final color = switch (kind) {
|
||||
_SyncStatusKind.success => status.success,
|
||||
_SyncStatusKind.error => colorScheme.error,
|
||||
_SyncStatusKind.pending => colorScheme.onSurfaceVariant,
|
||||
};
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: color.withValues(alpha: 0.4)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
if (kind == _SyncStatusKind.pending)
|
||||
const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
else
|
||||
Icon(
|
||||
kind == _SyncStatusKind.success
|
||||
? Icons.check_circle
|
||||
: Icons.error,
|
||||
color: color,
|
||||
size: 16,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: AppTextSize.label,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SyncTokenField extends StatelessWidget {
|
||||
const _SyncTokenField({required this.controller, required this.onSave});
|
||||
|
||||
final TextEditingController controller;
|
||||
final VoidCallback onSave;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: controller,
|
||||
obscureText: true,
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
// filled/fillColor/border inherit from the shared
|
||||
// inputDecorationTheme (theme.dart) — only the field-specific
|
||||
// hint/padding need setting here.
|
||||
decoration: InputDecoration(
|
||||
hintText: 'GitHub PAT',
|
||||
hintStyle: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 10,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
ElevatedButton(onPressed: onSave, child: const Text('Save')),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Dialog shown during the device flow: displays the user code, opens the
|
||||
/// verification page, and polls until authorized -- popping the token (or
|
||||
/// null if cancelled / failed).
|
||||
class _DeviceCodeDialog extends StatefulWidget {
|
||||
const _DeviceCodeDialog({required this.device, required this.auth});
|
||||
|
||||
final DeviceCodeResponse device;
|
||||
final GitHubDeviceAuth auth;
|
||||
|
||||
@override
|
||||
State<_DeviceCodeDialog> createState() => _DeviceCodeDialogState();
|
||||
}
|
||||
|
||||
class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
unawaited(_poll());
|
||||
}
|
||||
|
||||
Future<void> _poll() async {
|
||||
try {
|
||||
final token = await widget.auth.pollForToken(widget.device);
|
||||
if (mounted) Navigator.of(context).pop(token);
|
||||
} on Exception catch (e) {
|
||||
if (mounted) setState(() => _error = '$e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openPage() async {
|
||||
await Clipboard.setData(ClipboardData(text: widget.device.userCode));
|
||||
await launchUrl(
|
||||
Uri.parse(widget.device.verificationUri),
|
||||
mode: LaunchMode.externalApplication,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return AlertDialog(
|
||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||
title: Text(
|
||||
'Authorize on GitHub',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Enter this code on GitHub:',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SelectableText(
|
||||
widget.device.userCode,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontSize: AppTextSize.title,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (_error == null)
|
||||
Row(
|
||||
children: [
|
||||
const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Waiting for authorization…',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
else
|
||||
Text(_error!, style: TextStyle(color: colorScheme.error)),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(
|
||||
'Cancel',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: _openPage,
|
||||
icon: const Icon(Icons.open_in_new),
|
||||
label: const Text('Open GitHub & copy code'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,202 @@
|
||||
// Status badge, token field and the device-code dialog.
|
||||
//
|
||||
// `part` file: these widgets are library-private and stay that way.
|
||||
// See history_screen_charts.dart for the full reasoning.
|
||||
part of 'github_mirror_screen.dart';
|
||||
|
||||
class _SyncStatusBadge extends StatelessWidget {
|
||||
const _SyncStatusBadge({required this.text, required this.kind});
|
||||
|
||||
final String text;
|
||||
final _SyncStatusKind kind;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
final color = switch (kind) {
|
||||
_SyncStatusKind.success => status.success,
|
||||
_SyncStatusKind.error => colorScheme.error,
|
||||
_SyncStatusKind.pending => colorScheme.onSurfaceVariant,
|
||||
};
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: color.withValues(alpha: 0.4)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
if (kind == _SyncStatusKind.pending)
|
||||
const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
else
|
||||
Icon(
|
||||
kind == _SyncStatusKind.success
|
||||
? Icons.check_circle
|
||||
: Icons.error,
|
||||
color: color,
|
||||
size: 16,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: AppTextSize.label,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SyncTokenField extends StatelessWidget {
|
||||
const _SyncTokenField({required this.controller, required this.onSave});
|
||||
|
||||
final TextEditingController controller;
|
||||
final VoidCallback onSave;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: controller,
|
||||
obscureText: true,
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
// filled/fillColor/border inherit from the shared
|
||||
// inputDecorationTheme (theme.dart) — only the field-specific
|
||||
// hint/padding need setting here.
|
||||
decoration: InputDecoration(
|
||||
hintText: 'GitHub PAT',
|
||||
hintStyle: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 10,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
ElevatedButton(onPressed: onSave, child: const Text('Save')),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Dialog shown during the device flow: displays the user code, opens the
|
||||
/// verification page, and polls until authorized -- popping the token (or
|
||||
/// null if cancelled / failed).
|
||||
class _DeviceCodeDialog extends StatefulWidget {
|
||||
const _DeviceCodeDialog({required this.device, required this.auth});
|
||||
|
||||
final DeviceCodeResponse device;
|
||||
final GitHubDeviceAuth auth;
|
||||
|
||||
@override
|
||||
State<_DeviceCodeDialog> createState() => _DeviceCodeDialogState();
|
||||
}
|
||||
|
||||
class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
unawaited(_poll());
|
||||
}
|
||||
|
||||
Future<void> _poll() async {
|
||||
try {
|
||||
final token = await widget.auth.pollForToken(widget.device);
|
||||
if (mounted) Navigator.of(context).pop(token);
|
||||
} on Exception catch (e) {
|
||||
if (mounted) setState(() => _error = '$e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openPage() async {
|
||||
await Clipboard.setData(ClipboardData(text: widget.device.userCode));
|
||||
await launchUrl(
|
||||
Uri.parse(widget.device.verificationUri),
|
||||
mode: LaunchMode.externalApplication,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return AlertDialog(
|
||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||
title: Text(
|
||||
'Authorize on GitHub',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Enter this code on GitHub:',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SelectableText(
|
||||
widget.device.userCode,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontSize: AppTextSize.title,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (_error == null)
|
||||
Row(
|
||||
children: [
|
||||
const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Waiting for authorization…',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
else
|
||||
Text(_error!, style: TextStyle(color: colorScheme.error)),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(
|
||||
'Cancel',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: _openPage,
|
||||
icon: const Icon(Icons.open_in_new),
|
||||
label: const Text('Open GitHub & copy code'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -16,6 +16,11 @@ import 'package:workout_app/services/workout_sync_service.dart';
|
||||
import 'package:workout_app/ui/theme.dart';
|
||||
import 'package:workout_app/widgets/calendar_widget.dart';
|
||||
|
||||
part 'history_screen_charts.dart';
|
||||
part 'history_screen_data.dart';
|
||||
part 'history_screen_painter.dart';
|
||||
part 'history_screen_tiles.dart';
|
||||
|
||||
const _kTotal = 'Total (all workouts)';
|
||||
|
||||
/// Screen showing workout history with per-exercise drill-down and charts.
|
||||
@ -103,19 +108,6 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
httpClient: widget.httpClient,
|
||||
).readMergedWorkoutPayloads();
|
||||
|
||||
/// Workouts the PC published that this phone has no local record of.
|
||||
///
|
||||
/// The PC pushes its whole `workout_log.json` (RunnerUp runs and manual
|
||||
/// entries included), so pulling them here is what makes both devices show
|
||||
/// the SAME history. Sorted newest-first to match the local session list.
|
||||
/// StrongLifts sessions are deliberately excluded: they are restored into
|
||||
/// local history instead, so listing them here too would double them up.
|
||||
List<Map<String, dynamic>> _syncedOnly(
|
||||
List<Map<String, dynamic>> payloads,
|
||||
) =>
|
||||
payloads.where((p) => _kSyncedOnlyKinds.contains(p['kind'])).toList()
|
||||
..sort((a, b) => '${b['date']}'.compareTo('${a['date']}'));
|
||||
|
||||
Future<void> _pickExercise(String name) async {
|
||||
ExerciseState? state;
|
||||
if (name != _kTotal) {
|
||||
@ -131,109 +123,6 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
|
||||
// ── Data helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
/// All workout dates (YYYY-MM-DD): local sessions plus synced ones.
|
||||
///
|
||||
/// Synced dates are included so a day you only worked out on the PC (a
|
||||
/// RunnerUp run) still marks the calendar here.
|
||||
Set<String> get _allWorkoutDates => {
|
||||
..._rows.map((r) => r['date'] as String),
|
||||
..._syncedRows.map((r) => '${r['date']}'),
|
||||
};
|
||||
|
||||
/// Dates when the selected exercise appeared.
|
||||
Set<String> _exerciseDates(String name) {
|
||||
final result = <String>{};
|
||||
for (final row in _rows) {
|
||||
final json = jsonDecode(row['json'] as String) as Map<String, dynamic>;
|
||||
for (final ex in (json['exercises'] as List? ?? const [])) {
|
||||
if ((ex as Map<String, dynamic>)['name'] == name) {
|
||||
result.add(row['date'] as String);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// (date, total volume) per session – tonnage actually lifted, summed as
|
||||
/// `weight × doneReps` over every logged set.
|
||||
///
|
||||
/// This deliberately uses the per-set actuals rather than
|
||||
/// `targetWeight × targetSets × targetReps`: with targets, a session where
|
||||
/// every set failed plotted identically to one completed in full, so the
|
||||
/// line only moved when progression changed the target.
|
||||
///
|
||||
/// The target-based fallback is defensive only — `ExerciseResult.toJson`
|
||||
/// has emitted `sets` since the app's first commit, so no row written by
|
||||
/// this app lacks it. It exists for hand-edited or truncated backup JSON,
|
||||
/// not for a migration that ever happened.
|
||||
List<(DateTime, double)> _totalVolumePoints() {
|
||||
final points = <(DateTime, double)>[];
|
||||
for (final row in _rows.reversed) {
|
||||
final json = jsonDecode(row['json'] as String) as Map<String, dynamic>;
|
||||
double total = 0;
|
||||
for (final ex in (json['exercises'] as List? ?? const [])) {
|
||||
final m = ex as Map<String, dynamic>;
|
||||
final sets = m['sets'] as List?;
|
||||
if (sets == null || sets.isEmpty) {
|
||||
final w = (m['targetWeight'] as num?)?.toDouble() ?? 0;
|
||||
final s = (m['targetSets'] as num?)?.toInt() ?? 0;
|
||||
final r = (m['targetReps'] as num?)?.toInt() ?? 0;
|
||||
total += w * s * r;
|
||||
continue;
|
||||
}
|
||||
for (final set in sets) {
|
||||
final sm = set as Map<String, dynamic>;
|
||||
// `weight` is a non-nullable double in SetResult and always
|
||||
// serialized, so there is no targetWeight fallback here — an absent
|
||||
// value would mean hand-edited JSON, and silently substituting the
|
||||
// target would overstate a set the user never did.
|
||||
final w = (sm['weight'] as num?)?.toDouble() ?? 0;
|
||||
total += w * ((sm['doneReps'] as num?)?.toInt() ?? 0);
|
||||
}
|
||||
}
|
||||
final date = DateTime.tryParse(row['date'] as String);
|
||||
if (date != null) points.add((date, total));
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
/// (date, weight) for the selected exercise.
|
||||
List<(DateTime, double)> _exerciseWeightPoints(String name) {
|
||||
final points = <(DateTime, double)>[];
|
||||
for (final row in _rows.reversed) {
|
||||
final json = jsonDecode(row['json'] as String) as Map<String, dynamic>;
|
||||
for (final ex in (json['exercises'] as List? ?? const [])) {
|
||||
final m = ex as Map<String, dynamic>;
|
||||
if (m['name'] == name) {
|
||||
final date = DateTime.tryParse(row['date'] as String);
|
||||
final w = (m['targetWeight'] as num?)?.toDouble();
|
||||
if (date != null && w != null) points.add((date, w));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
/// Sessions filtered to those containing the selected exercise, newest first.
|
||||
List<Map<String, dynamic>> _sessionsForExercise(String name) {
|
||||
final result = <Map<String, dynamic>>[];
|
||||
for (final row in _rows) {
|
||||
final json = jsonDecode(row['json'] as String) as Map<String, dynamic>;
|
||||
for (final ex in (json['exercises'] as List? ?? const [])) {
|
||||
final m = ex as Map<String, dynamic>;
|
||||
if (m['name'] == name) {
|
||||
result.add({...row, 'exerciseData': m});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── Build ────────────────────────────────────────────────────────────────
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final allNames = [_kTotal, ..._exerciseNames];
|
||||
@ -276,26 +165,15 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Rolling average of 2 consecutive points to smooth A/B alternation.
|
||||
static List<(DateTime, double)> _rollingAvg2(
|
||||
List<(DateTime, double)> pts,
|
||||
) {
|
||||
if (pts.length < 2) return pts;
|
||||
return [
|
||||
for (int i = 0; i < pts.length; i++)
|
||||
(pts[i].$1, i == 0 ? pts[0].$2 : (pts[i].$2 + pts[i - 1].$2) / 2),
|
||||
];
|
||||
}
|
||||
|
||||
List<Widget> _buildTotalView() => [
|
||||
const _SectionLabel('TOTAL VOLUME (2-session rolling avg, kg)'),
|
||||
const SizedBox(height: 6),
|
||||
_WeightChart(
|
||||
points: _rollingAvg2(_totalVolumePoints()),
|
||||
points: _rollingAvg2(_totalVolumePoints(_rows)),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
WorkoutCalendar(
|
||||
workoutDates: _allWorkoutDates,
|
||||
workoutDates: _allWorkoutDates(_rows, _syncedRows),
|
||||
month: _calendarMonth,
|
||||
onPrevMonth: () => setState(() {
|
||||
_calendarMonth = DateTime(
|
||||
@ -330,11 +208,11 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
const _SectionLabel('WEIGHT OVER TIME'),
|
||||
const SizedBox(height: 6),
|
||||
_WeightChart(
|
||||
points: _exerciseWeightPoints(name),
|
||||
points: _exerciseWeightPoints(_rows, name),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
WorkoutCalendar(
|
||||
workoutDates: _exerciseDates(name),
|
||||
workoutDates: _exerciseDates(_rows, name),
|
||||
month: _calendarMonth,
|
||||
onPrevMonth: () => setState(() {
|
||||
_calendarMonth = DateTime(
|
||||
@ -352,546 +230,9 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
const SizedBox(height: 16),
|
||||
_SectionLabel(name.toUpperCase()),
|
||||
const SizedBox(height: 8),
|
||||
..._sessionsForExercise(name).map((s) => _ExerciseSessionTile(session: s)),
|
||||
..._sessionsForExercise(
|
||||
_rows,
|
||||
name,
|
||||
).map((s) => _ExerciseSessionTile(session: s)),
|
||||
];
|
||||
}
|
||||
|
||||
// ── Shared sub-widgets ──────────────────────────────────────────────────────
|
||||
|
||||
class _SectionLabel extends StatelessWidget {
|
||||
const _SectionLabel(this.text);
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
letterSpacing: 1.3,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ExercisePicker extends StatelessWidget {
|
||||
const _ExercisePicker({
|
||||
required this.names,
|
||||
required this.selected,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final List<String> names;
|
||||
final String selected;
|
||||
final ValueChanged<String> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return DropdownButton<String>(
|
||||
value: selected,
|
||||
dropdownColor: colorScheme.surfaceContainerHigh,
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
underline: const SizedBox(),
|
||||
isExpanded: true,
|
||||
items: names
|
||||
.map(
|
||||
(n) => DropdownMenuItem(
|
||||
value: n,
|
||||
child: Text(
|
||||
n,
|
||||
style: TextStyle(
|
||||
color: n == _kTotal
|
||||
? colorScheme.onSurfaceVariant
|
||||
: colorScheme.onSurface,
|
||||
fontStyle: n == _kTotal ? FontStyle.italic : FontStyle.normal,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
onChanged: (v) {
|
||||
if (v != null) onChanged(v);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProgressStatsCard extends StatelessWidget {
|
||||
const _ProgressStatsCard({required this.state});
|
||||
|
||||
final ExerciseState state;
|
||||
|
||||
String _nextWeightLabel(double current, double max, double inc) {
|
||||
if (current >= max) return '+1 rep';
|
||||
return '+${inc}kg (${(current + inc).clamp(0.0, max)}kg)';
|
||||
}
|
||||
|
||||
String _prevWeightLabel(double current, double inc) {
|
||||
return '-${inc}kg (${(current - inc).clamp(0.0, double.infinity)}kg)';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final successLeft = state.successThreshold - state.successStreak;
|
||||
final failLeft = state.failThreshold - state.failStreak;
|
||||
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${state.name} — ${state.weight}kg',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_StreakRow(
|
||||
icon: Icons.trending_up,
|
||||
color: status.success,
|
||||
current: state.successStreak,
|
||||
threshold: state.successThreshold,
|
||||
leftLabel: '$successLeft more',
|
||||
actionLabel: _nextWeightLabel(
|
||||
state.weight,
|
||||
state.maxWeight,
|
||||
kWeightIncrement,
|
||||
),
|
||||
direction: '↑',
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
_StreakRow(
|
||||
icon: Icons.trending_down,
|
||||
color: colorScheme.error,
|
||||
current: state.failStreak,
|
||||
threshold: state.failThreshold,
|
||||
leftLabel: '$failLeft more',
|
||||
actionLabel: _prevWeightLabel(state.weight, kWeightIncrement),
|
||||
direction: '↓',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StreakRow extends StatelessWidget {
|
||||
const _StreakRow({
|
||||
required this.icon,
|
||||
required this.color,
|
||||
required this.current,
|
||||
required this.threshold,
|
||||
required this.leftLabel,
|
||||
required this.actionLabel,
|
||||
required this.direction,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final Color color;
|
||||
final int current;
|
||||
final int threshold;
|
||||
final String leftLabel;
|
||||
final String actionLabel;
|
||||
final String direction;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Row(
|
||||
children: [
|
||||
Icon(icon, color: color, size: 14),
|
||||
const SizedBox(width: 6),
|
||||
...List.generate(
|
||||
threshold,
|
||||
(i) => Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
margin: const EdgeInsets.only(right: 3),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: i < current ? color : colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'$leftLabel to $direction $actionLabel',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _WeightChart extends StatelessWidget {
|
||||
const _WeightChart({required this.points});
|
||||
|
||||
final List<(DateTime, double)> points;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
if (points.length < 2) {
|
||||
return Container(
|
||||
height: 80,
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
'Not enough data for chart',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
);
|
||||
}
|
||||
return SizedBox(
|
||||
height: 140,
|
||||
child: CustomPaint(
|
||||
painter: _ChartPainter(
|
||||
points,
|
||||
lineColor: colorScheme.primary,
|
||||
labelColor: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
size: Size.infinite,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ChartPainter extends CustomPainter {
|
||||
_ChartPainter(
|
||||
this.points, {
|
||||
required this.lineColor,
|
||||
required this.labelColor,
|
||||
});
|
||||
|
||||
final List<(DateTime, double)> points;
|
||||
|
||||
// CustomPainter.paint() has no BuildContext, so the caller (which does)
|
||||
// passes the themed colors in explicitly.
|
||||
final Color lineColor;
|
||||
final Color labelColor;
|
||||
|
||||
// Layout constants
|
||||
static const _topPad = 14.0; // room for top Y label
|
||||
static const _bottomPad = 22.0; // room for X-axis dates
|
||||
static const _hPad = 8.0;
|
||||
|
||||
static const _months = [
|
||||
'Jan',
|
||||
'Feb',
|
||||
'Mar',
|
||||
'Apr',
|
||||
'May',
|
||||
'Jun',
|
||||
'Jul',
|
||||
'Aug',
|
||||
'Sep',
|
||||
'Oct',
|
||||
'Nov',
|
||||
'Dec',
|
||||
];
|
||||
|
||||
static String _shortDate(DateTime d) => '${_months[d.month - 1]} ${d.day}';
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final minW = points.map((p) => p.$2).reduce(min);
|
||||
final maxW = points.map((p) => p.$2).reduce(max);
|
||||
final minMs = points.first.$1.millisecondsSinceEpoch.toDouble();
|
||||
final maxMs = points.last.$1.millisecondsSinceEpoch.toDouble();
|
||||
final wRange = maxW - minW;
|
||||
final tRange = maxMs - minMs;
|
||||
|
||||
const plotTop = _topPad;
|
||||
final plotBottom = size.height - _bottomPad;
|
||||
const plotLeft = _hPad;
|
||||
final plotRight = size.width - _hPad;
|
||||
final plotHeight = plotBottom - plotTop;
|
||||
final plotWidth = plotRight - plotLeft;
|
||||
|
||||
double xOf(DateTime t) => tRange == 0
|
||||
? (plotLeft + plotRight) / 2
|
||||
: (t.millisecondsSinceEpoch - minMs) / tRange * plotWidth + plotLeft;
|
||||
double yOf(double w) => wRange == 0
|
||||
? (plotTop + plotBottom) / 2
|
||||
: (1 - (w - minW) / wRange) * plotHeight + plotTop;
|
||||
|
||||
final linePaint = Paint()
|
||||
..color = lineColor
|
||||
..strokeWidth = 2
|
||||
..style = PaintingStyle.stroke;
|
||||
final dotPaint = Paint()
|
||||
..color = lineColor
|
||||
..style = PaintingStyle.fill;
|
||||
|
||||
final path = Path()..moveTo(xOf(points.first.$1), yOf(points.first.$2));
|
||||
for (final p in points.skip(1)) {
|
||||
path.lineTo(xOf(p.$1), yOf(p.$2));
|
||||
}
|
||||
canvas.drawPath(path, linePaint);
|
||||
for (final p in points) {
|
||||
canvas.drawCircle(Offset(xOf(p.$1), yOf(p.$2)), 4, dotPaint);
|
||||
}
|
||||
|
||||
// Y-axis labels
|
||||
final tp = TextPainter(textDirection: TextDirection.ltr);
|
||||
void drawText(String text, Offset offset, {double fontSize = 10}) {
|
||||
tp
|
||||
..text = TextSpan(
|
||||
text: text,
|
||||
style: TextStyle(color: labelColor, fontSize: fontSize),
|
||||
)
|
||||
..layout()
|
||||
..paint(canvas, offset);
|
||||
}
|
||||
|
||||
drawText('${maxW.round()}kg', const Offset(plotLeft, 0));
|
||||
drawText('${minW.round()}kg', Offset(plotLeft, plotBottom + 2));
|
||||
|
||||
// X-axis date labels: first, middle, last
|
||||
final n = points.length;
|
||||
final xIndices = n <= 2 ? [0, n - 1] : [0, n ~/ 2, n - 1];
|
||||
for (final i in xIndices) {
|
||||
final p = points[i];
|
||||
final label = _shortDate(p.$1);
|
||||
tp
|
||||
..text = TextSpan(
|
||||
text: label,
|
||||
style: TextStyle(color: labelColor, fontSize: 9),
|
||||
)
|
||||
..layout();
|
||||
final cx = xOf(p.$1);
|
||||
final dx = (cx - tp.width / 2).clamp(plotLeft, plotRight - tp.width);
|
||||
tp.paint(canvas, Offset(dx, size.height - tp.height));
|
||||
}
|
||||
}
|
||||
|
||||
// lineColor/labelColor come from the app's single fixed dark theme, so
|
||||
// they never actually change at runtime — only points varies.
|
||||
@override
|
||||
bool shouldRepaint(_ChartPainter old) => old.points != points;
|
||||
}
|
||||
|
||||
/// One workout the PC published that this phone has no local session for.
|
||||
class _SyncedWorkoutTile extends StatelessWidget {
|
||||
const _SyncedWorkoutTile({required this.payload});
|
||||
|
||||
final Map<String, dynamic> payload;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final kind = '${payload['kind']}';
|
||||
final isRun = kind == 'runnerup_verified';
|
||||
final label = isRun ? 'Run' : 'Manual';
|
||||
final detail = '${payload['source'] ?? ''}';
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
// Neutral — this distinguishes entry TYPE (run vs. manual), not a
|
||||
// status/judgment, so it doesn't borrow a semantic status color.
|
||||
border: Border.all(color: colorScheme.outline),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
isRun ? Icons.directions_run : Icons.edit_note,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${payload['date']} · $label',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
if (detail.isNotEmpty)
|
||||
Text(
|
||||
detail,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AllSessionTile extends StatelessWidget {
|
||||
const _AllSessionTile({required this.row});
|
||||
|
||||
final Map<String, dynamic> row;
|
||||
|
||||
String _formatDuration(int secs) {
|
||||
final h = secs ~/ 3600;
|
||||
final m = (secs ~/ 60).remainder(60).toString().padLeft(2, '0');
|
||||
final s = (secs % 60).toString().padLeft(2, '0');
|
||||
return h > 0 ? '${h}h ${m}m ${s}s' : '${m}m ${s}s';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
final succeeded = (row['succeeded'] as int) == 1;
|
||||
final type = row['workout_type'] as String;
|
||||
final date = row['date'] as String;
|
||||
final dur = _formatDuration(row['duration_seconds'] as int);
|
||||
final statusColor = succeeded ? status.success : colorScheme.error;
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
border: Border.all(color: statusColor),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
succeeded ? Icons.check_circle : Icons.cancel,
|
||||
color: statusColor,
|
||||
size: 18,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Workout $type · $date',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
dur,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ExerciseSessionTile extends StatelessWidget {
|
||||
const _ExerciseSessionTile({required this.session});
|
||||
|
||||
final Map<String, dynamic> session;
|
||||
|
||||
String _formatDuration(int secs) {
|
||||
final h = secs ~/ 3600;
|
||||
final m = (secs ~/ 60).remainder(60).toString().padLeft(2, '0');
|
||||
final s = (secs % 60).toString().padLeft(2, '0');
|
||||
return h > 0 ? '${h}h ${m}m ${s}s' : '${m}m ${s}s';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
final exData = session['exerciseData'] as Map<String, dynamic>;
|
||||
final succeeded = (exData['succeeded'] as bool?) == true;
|
||||
final date = session['date'] as String;
|
||||
final dur = _formatDuration(session['duration_seconds'] as int);
|
||||
final weight = (exData['targetWeight'] as num?)?.toDouble();
|
||||
final warmupDone = exData['warmupDone'] as bool? ?? false;
|
||||
final sets = (exData['sets'] as List?)?.cast<Map<String, dynamic>>() ?? [];
|
||||
final targetSets = exData['targetSets'] as int? ?? sets.length;
|
||||
final doneSets = sets.where((s) => s['succeeded'] == true).length;
|
||||
final repsSummary = sets.map((s) => '${s['doneReps']}').join(', ');
|
||||
final statusColor = succeeded ? status.success : colorScheme.error;
|
||||
final mutedStyle = TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
);
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
border: Border.all(color: statusColor),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 2),
|
||||
child: Icon(
|
||||
succeeded ? Icons.check_circle : Icons.cancel,
|
||||
color: statusColor,
|
||||
size: 18,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
date,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
'${weight ?? '?'}kg · $doneSets/$targetSets sets'
|
||||
' · ${warmupDone ? '⬤ warmup' : '○ no warmup'}',
|
||||
style: mutedStyle,
|
||||
),
|
||||
if (repsSummary.isNotEmpty) ...[
|
||||
const SizedBox(height: 2),
|
||||
Text('reps: $repsSummary', style: mutedStyle),
|
||||
],
|
||||
const SizedBox(height: 2),
|
||||
Text('workout: $dur', style: mutedStyle),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,222 @@
|
||||
// Chart and stat sub-widgets for HistoryScreen.
|
||||
//
|
||||
// A `part` rather than its own library: these widgets are private to
|
||||
// history_screen.dart and stay that way, so the split is a pure move and
|
||||
// public_member_api_docs does not start demanding docs for them.
|
||||
part of 'history_screen.dart';
|
||||
|
||||
// ── Shared sub-widgets ──────────────────────────────────────────────────────
|
||||
|
||||
class _SectionLabel extends StatelessWidget {
|
||||
const _SectionLabel(this.text);
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
letterSpacing: 1.3,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ExercisePicker extends StatelessWidget {
|
||||
const _ExercisePicker({
|
||||
required this.names,
|
||||
required this.selected,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final List<String> names;
|
||||
final String selected;
|
||||
final ValueChanged<String> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return DropdownButton<String>(
|
||||
value: selected,
|
||||
dropdownColor: colorScheme.surfaceContainerHigh,
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
underline: const SizedBox(),
|
||||
isExpanded: true,
|
||||
items: names
|
||||
.map(
|
||||
(n) => DropdownMenuItem(
|
||||
value: n,
|
||||
child: Text(
|
||||
n,
|
||||
style: TextStyle(
|
||||
color: n == _kTotal
|
||||
? colorScheme.onSurfaceVariant
|
||||
: colorScheme.onSurface,
|
||||
fontStyle: n == _kTotal ? FontStyle.italic : FontStyle.normal,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
onChanged: (v) {
|
||||
if (v != null) onChanged(v);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProgressStatsCard extends StatelessWidget {
|
||||
const _ProgressStatsCard({required this.state});
|
||||
|
||||
final ExerciseState state;
|
||||
|
||||
String _nextWeightLabel(double current, double max, double inc) {
|
||||
if (current >= max) return '+1 rep';
|
||||
return '+${inc}kg (${(current + inc).clamp(0.0, max)}kg)';
|
||||
}
|
||||
|
||||
String _prevWeightLabel(double current, double inc) {
|
||||
return '-${inc}kg (${(current - inc).clamp(0.0, double.infinity)}kg)';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final successLeft = state.successThreshold - state.successStreak;
|
||||
final failLeft = state.failThreshold - state.failStreak;
|
||||
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${state.name} — ${state.weight}kg',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_StreakRow(
|
||||
icon: Icons.trending_up,
|
||||
color: status.success,
|
||||
current: state.successStreak,
|
||||
threshold: state.successThreshold,
|
||||
leftLabel: '$successLeft more',
|
||||
actionLabel: _nextWeightLabel(
|
||||
state.weight,
|
||||
state.maxWeight,
|
||||
kWeightIncrement,
|
||||
),
|
||||
direction: '↑',
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
_StreakRow(
|
||||
icon: Icons.trending_down,
|
||||
color: colorScheme.error,
|
||||
current: state.failStreak,
|
||||
threshold: state.failThreshold,
|
||||
leftLabel: '$failLeft more',
|
||||
actionLabel: _prevWeightLabel(state.weight, kWeightIncrement),
|
||||
direction: '↓',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StreakRow extends StatelessWidget {
|
||||
const _StreakRow({
|
||||
required this.icon,
|
||||
required this.color,
|
||||
required this.current,
|
||||
required this.threshold,
|
||||
required this.leftLabel,
|
||||
required this.actionLabel,
|
||||
required this.direction,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final Color color;
|
||||
final int current;
|
||||
final int threshold;
|
||||
final String leftLabel;
|
||||
final String actionLabel;
|
||||
final String direction;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Row(
|
||||
children: [
|
||||
Icon(icon, color: color, size: 14),
|
||||
const SizedBox(width: 6),
|
||||
...List.generate(
|
||||
threshold,
|
||||
(i) => Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
margin: const EdgeInsets.only(right: 3),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: i < current ? color : colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'$leftLabel to $direction $actionLabel',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _WeightChart extends StatelessWidget {
|
||||
const _WeightChart({required this.points});
|
||||
|
||||
final List<(DateTime, double)> points;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
if (points.length < 2) {
|
||||
return Container(
|
||||
height: 80,
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
'Not enough data for chart',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
);
|
||||
}
|
||||
return SizedBox(
|
||||
height: 140,
|
||||
child: CustomPaint(
|
||||
painter: _ChartPainter(
|
||||
points,
|
||||
lineColor: colorScheme.primary,
|
||||
labelColor: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
size: Size.infinite,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,137 @@
|
||||
// Pure transforms over the loaded history rows.
|
||||
//
|
||||
// Top-level rather than methods on the State: they only read `rows`, so
|
||||
// keeping them off the widget makes the data shaping testable on its own.
|
||||
// A `part` so they stay library-private -- see history_screen_charts.dart.
|
||||
part of 'history_screen.dart';
|
||||
|
||||
Set<String> _exerciseDates(List<Map<String, dynamic>> rows, String name) {
|
||||
final result = <String>{};
|
||||
for (final row in rows) {
|
||||
final json = jsonDecode(row['json'] as String) as Map<String, dynamic>;
|
||||
for (final ex in (json['exercises'] as List? ?? const [])) {
|
||||
if ((ex as Map<String, dynamic>)['name'] == name) {
|
||||
result.add(row['date'] as String);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// (date, total volume) per session – tonnage actually lifted, summed as
|
||||
/// `weight × doneReps` over every logged set.
|
||||
///
|
||||
/// This deliberately uses the per-set actuals rather than
|
||||
/// `targetWeight × targetSets × targetReps`: with targets, a session where
|
||||
/// every set failed plotted identically to one completed in full, so the
|
||||
/// line only moved when progression changed the target.
|
||||
///
|
||||
/// The target-based fallback is defensive only — `ExerciseResult.toJson`
|
||||
/// has emitted `sets` since the app's first commit, so no row written by
|
||||
/// this app lacks it. It exists for hand-edited or truncated backup JSON,
|
||||
/// not for a migration that ever happened.
|
||||
List<(DateTime, double)> _totalVolumePoints(List<Map<String, dynamic>> rows) {
|
||||
final points = <(DateTime, double)>[];
|
||||
for (final row in rows.reversed) {
|
||||
final json = jsonDecode(row['json'] as String) as Map<String, dynamic>;
|
||||
double total = 0;
|
||||
for (final ex in (json['exercises'] as List? ?? const [])) {
|
||||
final m = ex as Map<String, dynamic>;
|
||||
final sets = m['sets'] as List?;
|
||||
if (sets == null || sets.isEmpty) {
|
||||
final w = (m['targetWeight'] as num?)?.toDouble() ?? 0;
|
||||
final s = (m['targetSets'] as num?)?.toInt() ?? 0;
|
||||
final r = (m['targetReps'] as num?)?.toInt() ?? 0;
|
||||
total += w * s * r;
|
||||
continue;
|
||||
}
|
||||
for (final set in sets) {
|
||||
final sm = set as Map<String, dynamic>;
|
||||
// `weight` is a non-nullable double in SetResult and always
|
||||
// serialized, so there is no targetWeight fallback here — an absent
|
||||
// value would mean hand-edited JSON, and silently substituting the
|
||||
// target would overstate a set the user never did.
|
||||
final w = (sm['weight'] as num?)?.toDouble() ?? 0;
|
||||
total += w * ((sm['doneReps'] as num?)?.toInt() ?? 0);
|
||||
}
|
||||
}
|
||||
final date = DateTime.tryParse(row['date'] as String);
|
||||
if (date != null) points.add((date, total));
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
/// (date, weight) for the selected exercise.
|
||||
List<(DateTime, double)> _exerciseWeightPoints(
|
||||
List<Map<String, dynamic>> rows,
|
||||
String name,
|
||||
) {
|
||||
final points = <(DateTime, double)>[];
|
||||
for (final row in rows.reversed) {
|
||||
final json = jsonDecode(row['json'] as String) as Map<String, dynamic>;
|
||||
for (final ex in (json['exercises'] as List? ?? const [])) {
|
||||
final m = ex as Map<String, dynamic>;
|
||||
if (m['name'] == name) {
|
||||
final date = DateTime.tryParse(row['date'] as String);
|
||||
final w = (m['targetWeight'] as num?)?.toDouble();
|
||||
if (date != null && w != null) points.add((date, w));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
/// Sessions filtered to those containing the selected exercise, newest first.
|
||||
List<Map<String, dynamic>> _sessionsForExercise(
|
||||
List<Map<String, dynamic>> rows,
|
||||
String name,
|
||||
) {
|
||||
final result = <Map<String, dynamic>>[];
|
||||
for (final row in rows) {
|
||||
final json = jsonDecode(row['json'] as String) as Map<String, dynamic>;
|
||||
for (final ex in (json['exercises'] as List? ?? const [])) {
|
||||
final m = ex as Map<String, dynamic>;
|
||||
if (m['name'] == name) {
|
||||
result.add({...row, 'exerciseData': m});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── Build ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Rolling average of 2 consecutive points to smooth A/B alternation.
|
||||
List<(DateTime, double)> _rollingAvg2(List<(DateTime, double)> pts) {
|
||||
if (pts.length < 2) return pts;
|
||||
return [
|
||||
for (int i = 0; i < pts.length; i++)
|
||||
(pts[i].$1, i == 0 ? pts[0].$2 : (pts[i].$2 + pts[i - 1].$2) / 2),
|
||||
];
|
||||
}
|
||||
|
||||
/// All workout dates (YYYY-MM-DD): local sessions plus synced ones.
|
||||
///
|
||||
/// Synced dates are included so a day you only worked out on the PC (a
|
||||
/// RunnerUp run) still marks the calendar here.
|
||||
Set<String> _allWorkoutDates(
|
||||
List<Map<String, dynamic>> rows,
|
||||
List<Map<String, dynamic>> syncedRows,
|
||||
) => {
|
||||
...rows.map((r) => r['date'] as String),
|
||||
...syncedRows.map((r) => '${r['date']}'),
|
||||
};
|
||||
|
||||
/// Workouts the PC published that this phone has no local record of.
|
||||
///
|
||||
/// The PC pushes its whole `workout_log.json` (RunnerUp runs and manual
|
||||
/// entries included), so pulling them here is what makes both devices show
|
||||
/// the SAME history. Sorted newest-first to match the local session list.
|
||||
/// StrongLifts sessions are deliberately excluded: they are restored into
|
||||
/// local history instead, so listing them here too would double them up.
|
||||
List<Map<String, dynamic>> _syncedOnly(List<Map<String, dynamic>> payloads) =>
|
||||
payloads.where((p) => _kSyncedOnlyKinds.contains(p['kind'])).toList()
|
||||
..sort((a, b) => '${b['date']}'.compareTo('${a['date']}'));
|
||||
@ -0,0 +1,124 @@
|
||||
// The CustomPainter that draws the weight/volume line chart.
|
||||
//
|
||||
// Separated from the chart *widgets* because painting is the part that
|
||||
// changes for visual reasons; see history_screen_charts.dart for why
|
||||
// these are `part` files.
|
||||
part of 'history_screen.dart';
|
||||
|
||||
|
||||
class _ChartPainter extends CustomPainter {
|
||||
_ChartPainter(
|
||||
this.points, {
|
||||
required this.lineColor,
|
||||
required this.labelColor,
|
||||
});
|
||||
|
||||
final List<(DateTime, double)> points;
|
||||
|
||||
// CustomPainter.paint() has no BuildContext, so the caller (which does)
|
||||
// passes the themed colors in explicitly.
|
||||
final Color lineColor;
|
||||
final Color labelColor;
|
||||
|
||||
// Layout constants
|
||||
static const _topPad = 14.0; // room for top Y label
|
||||
static const _bottomPad = 22.0; // room for X-axis dates
|
||||
static const _hPad = 8.0;
|
||||
|
||||
static const _months = [
|
||||
'Jan',
|
||||
'Feb',
|
||||
'Mar',
|
||||
'Apr',
|
||||
'May',
|
||||
'Jun',
|
||||
'Jul',
|
||||
'Aug',
|
||||
'Sep',
|
||||
'Oct',
|
||||
'Nov',
|
||||
'Dec',
|
||||
];
|
||||
|
||||
static String _shortDate(DateTime d) => '${_months[d.month - 1]} ${d.day}';
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final minW = points.map((p) => p.$2).reduce(min);
|
||||
final maxW = points.map((p) => p.$2).reduce(max);
|
||||
final minMs = points.first.$1.millisecondsSinceEpoch.toDouble();
|
||||
final maxMs = points.last.$1.millisecondsSinceEpoch.toDouble();
|
||||
final wRange = maxW - minW;
|
||||
final tRange = maxMs - minMs;
|
||||
|
||||
const plotTop = _topPad;
|
||||
final plotBottom = size.height - _bottomPad;
|
||||
const plotLeft = _hPad;
|
||||
final plotRight = size.width - _hPad;
|
||||
final plotHeight = plotBottom - plotTop;
|
||||
final plotWidth = plotRight - plotLeft;
|
||||
|
||||
double xOf(DateTime t) => tRange == 0
|
||||
? (plotLeft + plotRight) / 2
|
||||
: (t.millisecondsSinceEpoch - minMs) / tRange * plotWidth + plotLeft;
|
||||
double yOf(double w) => wRange == 0
|
||||
? (plotTop + plotBottom) / 2
|
||||
: (1 - (w - minW) / wRange) * plotHeight + plotTop;
|
||||
|
||||
final linePaint = Paint()
|
||||
..color = lineColor
|
||||
..strokeWidth = 2
|
||||
..style = PaintingStyle.stroke;
|
||||
final dotPaint = Paint()
|
||||
..color = lineColor
|
||||
..style = PaintingStyle.fill;
|
||||
|
||||
final path = Path()..moveTo(xOf(points.first.$1), yOf(points.first.$2));
|
||||
for (final p in points.skip(1)) {
|
||||
path.lineTo(xOf(p.$1), yOf(p.$2));
|
||||
}
|
||||
canvas.drawPath(path, linePaint);
|
||||
for (final p in points) {
|
||||
canvas.drawCircle(Offset(xOf(p.$1), yOf(p.$2)), 4, dotPaint);
|
||||
}
|
||||
|
||||
// Y-axis labels
|
||||
final tp = TextPainter(textDirection: TextDirection.ltr);
|
||||
void drawText(String text, Offset offset, {double fontSize = 10}) {
|
||||
tp
|
||||
..text = TextSpan(
|
||||
text: text,
|
||||
style: TextStyle(color: labelColor, fontSize: fontSize),
|
||||
)
|
||||
..layout()
|
||||
..paint(canvas, offset);
|
||||
}
|
||||
|
||||
drawText('${maxW.round()}kg', const Offset(plotLeft, 0));
|
||||
drawText('${minW.round()}kg', Offset(plotLeft, plotBottom + 2));
|
||||
|
||||
// X-axis date labels: first, middle, last
|
||||
final n = points.length;
|
||||
final xIndices = n <= 2 ? [0, n - 1] : [0, n ~/ 2, n - 1];
|
||||
for (final i in xIndices) {
|
||||
final p = points[i];
|
||||
final label = _shortDate(p.$1);
|
||||
tp
|
||||
..text = TextSpan(
|
||||
text: label,
|
||||
style: TextStyle(color: labelColor, fontSize: 9),
|
||||
)
|
||||
..layout();
|
||||
final cx = xOf(p.$1);
|
||||
final dx = (cx - tp.width / 2).clamp(plotLeft, plotRight - tp.width);
|
||||
tp.paint(canvas, Offset(dx, size.height - tp.height));
|
||||
}
|
||||
}
|
||||
|
||||
// lineColor/labelColor come from the app's single fixed dark theme, so
|
||||
// they never actually change at runtime — only points varies.
|
||||
@override
|
||||
bool shouldRepaint(_ChartPainter old) => old.points != points;
|
||||
}
|
||||
|
||||
/// One workout the PC published that this phone has no local session for.
|
||||
@ -0,0 +1,212 @@
|
||||
// Session list tiles for HistoryScreen.
|
||||
//
|
||||
// See history_screen_charts.dart for why these are `part` files.
|
||||
part of 'history_screen.dart';
|
||||
|
||||
class _SyncedWorkoutTile extends StatelessWidget {
|
||||
const _SyncedWorkoutTile({required this.payload});
|
||||
|
||||
final Map<String, dynamic> payload;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final kind = '${payload['kind']}';
|
||||
final isRun = kind == 'runnerup_verified';
|
||||
final label = isRun ? 'Run' : 'Manual';
|
||||
final detail = '${payload['source'] ?? ''}';
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
// Neutral — this distinguishes entry TYPE (run vs. manual), not a
|
||||
// status/judgment, so it doesn't borrow a semantic status color.
|
||||
border: Border.all(color: colorScheme.outline),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
isRun ? Icons.directions_run : Icons.edit_note,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${payload['date']} · $label',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
if (detail.isNotEmpty)
|
||||
Text(
|
||||
detail,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AllSessionTile extends StatelessWidget {
|
||||
const _AllSessionTile({required this.row});
|
||||
|
||||
final Map<String, dynamic> row;
|
||||
|
||||
String _formatDuration(int secs) {
|
||||
final h = secs ~/ 3600;
|
||||
final m = (secs ~/ 60).remainder(60).toString().padLeft(2, '0');
|
||||
final s = (secs % 60).toString().padLeft(2, '0');
|
||||
return h > 0 ? '${h}h ${m}m ${s}s' : '${m}m ${s}s';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
final succeeded = (row['succeeded'] as int) == 1;
|
||||
final type = row['workout_type'] as String;
|
||||
final date = row['date'] as String;
|
||||
final dur = _formatDuration(row['duration_seconds'] as int);
|
||||
final statusColor = succeeded ? status.success : colorScheme.error;
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
border: Border.all(color: statusColor),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
succeeded ? Icons.check_circle : Icons.cancel,
|
||||
color: statusColor,
|
||||
size: 18,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Workout $type · $date',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
dur,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ExerciseSessionTile extends StatelessWidget {
|
||||
const _ExerciseSessionTile({required this.session});
|
||||
|
||||
final Map<String, dynamic> session;
|
||||
|
||||
String _formatDuration(int secs) {
|
||||
final h = secs ~/ 3600;
|
||||
final m = (secs ~/ 60).remainder(60).toString().padLeft(2, '0');
|
||||
final s = (secs % 60).toString().padLeft(2, '0');
|
||||
return h > 0 ? '${h}h ${m}m ${s}s' : '${m}m ${s}s';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
final exData = session['exerciseData'] as Map<String, dynamic>;
|
||||
final succeeded = (exData['succeeded'] as bool?) == true;
|
||||
final date = session['date'] as String;
|
||||
final dur = _formatDuration(session['duration_seconds'] as int);
|
||||
final weight = (exData['targetWeight'] as num?)?.toDouble();
|
||||
final warmupDone = exData['warmupDone'] as bool? ?? false;
|
||||
final sets = (exData['sets'] as List?)?.cast<Map<String, dynamic>>() ?? [];
|
||||
final targetSets = exData['targetSets'] as int? ?? sets.length;
|
||||
final doneSets = sets.where((s) => s['succeeded'] == true).length;
|
||||
final repsSummary = sets.map((s) => '${s['doneReps']}').join(', ');
|
||||
final statusColor = succeeded ? status.success : colorScheme.error;
|
||||
final mutedStyle = TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
);
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
border: Border.all(color: statusColor),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 2),
|
||||
child: Icon(
|
||||
succeeded ? Icons.check_circle : Icons.cancel,
|
||||
color: statusColor,
|
||||
size: 18,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
date,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
'${weight ?? '?'}kg · $doneSets/$targetSets sets'
|
||||
' · ${warmupDone ? '⬤ warmup' : '○ no warmup'}',
|
||||
style: mutedStyle,
|
||||
),
|
||||
if (repsSummary.isNotEmpty) ...[
|
||||
const SizedBox(height: 2),
|
||||
Text('reps: $repsSummary', style: mutedStyle),
|
||||
],
|
||||
const SizedBox(height: 2),
|
||||
Text('workout: $dur', style: mutedStyle),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -14,6 +14,9 @@ import 'package:workout_app/services/workout_sync_service.dart';
|
||||
import 'package:workout_app/ui/theme.dart';
|
||||
import 'package:workout_app/widgets/sync_status_card.dart';
|
||||
|
||||
part 'home_screen_cards.dart';
|
||||
part 'home_screen_navigation.dart';
|
||||
|
||||
/// Home screen: auto-resumes active sessions and shows done-today status.
|
||||
class HomeScreen extends StatefulWidget {
|
||||
/// Creates a [HomeScreen].
|
||||
@ -102,13 +105,6 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
}
|
||||
|
||||
/// Opens settings so the user can connect sync, then re-checks on return.
|
||||
Future<void> _openSyncSettings() async {
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()),
|
||||
);
|
||||
unawaited(_load());
|
||||
}
|
||||
|
||||
/// Runs a sync tick and folds the outcome into the status card.
|
||||
///
|
||||
/// Never throws: [WorkoutSyncService.syncNow] reports failures as a
|
||||
@ -157,32 +153,6 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openWorkout({bool resume = false}) async {
|
||||
final storage = StorageService.instance;
|
||||
Map<String, dynamic>? savedState;
|
||||
var type = _nextType;
|
||||
var exercises = _exercises;
|
||||
|
||||
if (resume && _savedSession != null) {
|
||||
savedState = _savedSession;
|
||||
final savedType = savedState!['workoutType'] as String? ?? _nextType;
|
||||
type = savedType;
|
||||
exercises = await storage.getCurrentExercises(savedType);
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => WorkoutScreen(
|
||||
workoutType: type,
|
||||
exercises: exercises,
|
||||
savedState: savedState,
|
||||
),
|
||||
),
|
||||
);
|
||||
unawaited(_load());
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
@ -256,128 +226,3 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
}
|
||||
|
||||
// ── Sub-widgets ──────────────────────────────────────────────────────────────
|
||||
|
||||
class _WorkoutCard extends StatelessWidget {
|
||||
const _WorkoutCard({
|
||||
required this.type,
|
||||
required this.exercises,
|
||||
required this.doneToday,
|
||||
required this.hasActiveSession,
|
||||
required this.onStart,
|
||||
required this.onResume,
|
||||
});
|
||||
|
||||
final String type;
|
||||
final List<Exercise> exercises;
|
||||
final bool doneToday;
|
||||
final bool hasActiveSession;
|
||||
final VoidCallback onStart;
|
||||
final VoidCallback onResume;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
// Canonical button padding (rule 22): vertical 12, horizontal 24 — an
|
||||
// exact 2x ratio, both on the 4px spacing scale (tokens.md's own example).
|
||||
const buttonPadding = EdgeInsets.symmetric(horizontal: 24, vertical: 12);
|
||||
return Card(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (doneToday && !hasActiveSession) ...[
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle, color: status.success, size: 18),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Done for today!',
|
||||
style: TextStyle(
|
||||
color: status.success,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: AppTextSize.body,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Next: Workout $type — tomorrow',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontSize: AppTextSize.body,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
Text(
|
||||
hasActiveSession
|
||||
? 'Workout $type in progress'
|
||||
: 'Next: Workout $type',
|
||||
style: TextStyle(
|
||||
color: hasActiveSession
|
||||
? status.warning
|
||||
: colorScheme.onSurface,
|
||||
fontSize: AppTextSize.subtitle,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 10),
|
||||
...exercises.map(
|
||||
(e) => Text(
|
||||
'${e.name} ${e.sets}×${e.reps}×${e.weight}kg',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
if (hasActiveSession)
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: status.warning,
|
||||
padding: buttonPadding,
|
||||
),
|
||||
onPressed: onResume,
|
||||
child: Text(
|
||||
'Resume Workout',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onPrimary,
|
||||
fontSize: AppTextSize.body,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (!doneToday)
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: colorScheme.primary,
|
||||
padding: buttonPadding,
|
||||
),
|
||||
onPressed: onStart,
|
||||
child: Text(
|
||||
'Start Workout $type',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onPrimary,
|
||||
fontSize: AppTextSize.body,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,130 @@
|
||||
// The workout and status cards on the home screen.
|
||||
//
|
||||
// `part` file: these widgets are library-private and stay that way.
|
||||
// See history_screen_charts.dart for the full reasoning.
|
||||
part of 'home_screen.dart';
|
||||
|
||||
class _WorkoutCard extends StatelessWidget {
|
||||
const _WorkoutCard({
|
||||
required this.type,
|
||||
required this.exercises,
|
||||
required this.doneToday,
|
||||
required this.hasActiveSession,
|
||||
required this.onStart,
|
||||
required this.onResume,
|
||||
});
|
||||
|
||||
final String type;
|
||||
final List<Exercise> exercises;
|
||||
final bool doneToday;
|
||||
final bool hasActiveSession;
|
||||
final VoidCallback onStart;
|
||||
final VoidCallback onResume;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
// Canonical button padding (rule 22): vertical 12, horizontal 24 — an
|
||||
// exact 2x ratio, both on the 4px spacing scale (tokens.md's own example).
|
||||
const buttonPadding = EdgeInsets.symmetric(horizontal: 24, vertical: 12);
|
||||
return Card(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (doneToday && !hasActiveSession) ...[
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle, color: status.success, size: 18),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Done for today!',
|
||||
style: TextStyle(
|
||||
color: status.success,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: AppTextSize.body,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Next: Workout $type — tomorrow',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontSize: AppTextSize.body,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
Text(
|
||||
hasActiveSession
|
||||
? 'Workout $type in progress'
|
||||
: 'Next: Workout $type',
|
||||
style: TextStyle(
|
||||
color: hasActiveSession
|
||||
? status.warning
|
||||
: colorScheme.onSurface,
|
||||
fontSize: AppTextSize.subtitle,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 10),
|
||||
...exercises.map(
|
||||
(e) => Text(
|
||||
'${e.name} ${e.sets}×${e.reps}×${e.weight}kg',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
if (hasActiveSession)
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: status.warning,
|
||||
padding: buttonPadding,
|
||||
),
|
||||
onPressed: onResume,
|
||||
child: Text(
|
||||
'Resume Workout',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onPrimary,
|
||||
fontSize: AppTextSize.body,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (!doneToday)
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: colorScheme.primary,
|
||||
padding: buttonPadding,
|
||||
),
|
||||
onPressed: onStart,
|
||||
child: Text(
|
||||
'Start Workout $type',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onPrimary,
|
||||
fontSize: AppTextSize.body,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,42 @@
|
||||
// Navigation off the home screen: settings, and starting/resuming a workout.
|
||||
//
|
||||
// A `part` so the extension keeps reaching the private `_HomeScreenState`
|
||||
// fields. Both methods are setState-free — `setState` is `@protected` and
|
||||
// cannot be called from an extension — and both end by reloading the screen.
|
||||
part of 'home_screen.dart';
|
||||
|
||||
/// The two routes the home screen pushes, and the reload each returns to.
|
||||
extension _HomeScreenNavigation on _HomeScreenState {
|
||||
Future<void> _openSyncSettings() async {
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()),
|
||||
);
|
||||
unawaited(_load());
|
||||
}
|
||||
|
||||
Future<void> _openWorkout({bool resume = false}) async {
|
||||
final storage = StorageService.instance;
|
||||
Map<String, dynamic>? savedState;
|
||||
var type = _nextType;
|
||||
var exercises = _exercises;
|
||||
|
||||
if (resume && _savedSession != null) {
|
||||
savedState = _savedSession;
|
||||
final savedType = savedState!['workoutType'] as String? ?? _nextType;
|
||||
type = savedType;
|
||||
exercises = await storage.getCurrentExercises(savedType);
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => WorkoutScreen(
|
||||
workoutType: type,
|
||||
exercises: exercises,
|
||||
savedState: savedState,
|
||||
),
|
||||
),
|
||||
);
|
||||
unawaited(_load());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,83 @@
|
||||
// The small, stateless pieces of the manual-workout form.
|
||||
//
|
||||
// A `part` so the extension keeps reaching `_fields` and `context`. All three
|
||||
// are setState-free — `setState` is `@protected` and unreachable from an
|
||||
// extension — so the interactive controls (the sport dropdown and the RPE
|
||||
// slider) stay on the state class.
|
||||
part of 'manual_workout_screen.dart';
|
||||
|
||||
/// The form's non-interactive building blocks.
|
||||
extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
|
||||
Widget _budgetBanner(ManualBudget budget) => Text(
|
||||
'Manual: ${budget.week}/$kManualWorkoutBudgetPer7Days this week · '
|
||||
'${budget.month}/$kManualWorkoutBudgetPer30Days this month',
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
fontSize: AppTextSize.body,
|
||||
),
|
||||
);
|
||||
|
||||
Widget _section(String title) => Padding(
|
||||
padding: const EdgeInsets.only(top: 16, bottom: 4),
|
||||
child: Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
fontSize: AppTextSize.subtitle,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _text(String key, String label, {int lines = 1}) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: TextField(
|
||||
key: Key('mw_$key'),
|
||||
controller: _fields[key],
|
||||
maxLines: lines,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
|
||||
// filled/fillColor/border inherit from the shared inputDecorationTheme
|
||||
// (theme.dart) — only the field-specific label needs setting here.
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
labelStyle: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/// Reads [key]'s field as an int, treating blank or unparsable as 0.
|
||||
int _int(String key) => int.tryParse(_fields[key]!.text.trim()) ?? 0;
|
||||
|
||||
/// Reads [key]'s field verbatim.
|
||||
String _str(String key) => _fields[key]!.text;
|
||||
|
||||
ManualWorkoutDraft _draft() => ManualWorkoutDraft(
|
||||
sport: _sport,
|
||||
startTime: _str('start_time'),
|
||||
endTime: _str('end_time'),
|
||||
locationName: _str('location_name'),
|
||||
transportMethod: _str('transport_method'),
|
||||
cost: _str('cost'),
|
||||
rpe: _rpe.round(),
|
||||
wentWell: _str('went_well'),
|
||||
toImprove: _str('to_improve'),
|
||||
overallFeeling: _str('overall_feeling'),
|
||||
reservationPhone: _str('reservation_phone'),
|
||||
techniquesPracticed: _str('techniques_practiced'),
|
||||
warmUpMinutes: _str('warm_up_minutes'),
|
||||
painOrInjury: _str('pain_or_injury').trim().isEmpty
|
||||
? 'none'
|
||||
: _str('pain_or_injury'),
|
||||
matchesWon: _int('matches_won'),
|
||||
matchesLost: _int('matches_lost'),
|
||||
setsWon: _int('sets_won'),
|
||||
setsLost: _int('sets_lost'),
|
||||
racket: _str('racket'),
|
||||
balls: _str('balls'),
|
||||
activityTypeOther: _str('activity_type_other'),
|
||||
activityDetails: _str('activity_details'),
|
||||
equipment: _str('equipment'),
|
||||
);
|
||||
}
|
||||
@ -15,6 +15,8 @@ import 'package:workout_app/models/manual_workout.dart';
|
||||
import 'package:workout_app/services/workout_sync_service.dart';
|
||||
import 'package:workout_app/ui/theme.dart';
|
||||
|
||||
part 'manual_workout_form_parts.dart';
|
||||
|
||||
/// A screen that logs an off-app workout and syncs it to the PC.
|
||||
class ManualWorkoutScreen extends StatefulWidget {
|
||||
/// Creates the manual-workout form. [syncService]/[clock] are injectable for
|
||||
@ -93,37 +95,6 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
|
||||
});
|
||||
}
|
||||
|
||||
int _int(String key) => int.tryParse(_fields[key]!.text.trim()) ?? 0;
|
||||
String _str(String key) => _fields[key]!.text;
|
||||
|
||||
ManualWorkoutDraft _draft() => ManualWorkoutDraft(
|
||||
sport: _sport,
|
||||
startTime: _str('start_time'),
|
||||
endTime: _str('end_time'),
|
||||
locationName: _str('location_name'),
|
||||
transportMethod: _str('transport_method'),
|
||||
cost: _str('cost'),
|
||||
rpe: _rpe.round(),
|
||||
wentWell: _str('went_well'),
|
||||
toImprove: _str('to_improve'),
|
||||
overallFeeling: _str('overall_feeling'),
|
||||
reservationPhone: _str('reservation_phone'),
|
||||
techniquesPracticed: _str('techniques_practiced'),
|
||||
warmUpMinutes: _str('warm_up_minutes'),
|
||||
painOrInjury: _str('pain_or_injury').trim().isEmpty
|
||||
? 'none'
|
||||
: _str('pain_or_injury'),
|
||||
matchesWon: _int('matches_won'),
|
||||
matchesLost: _int('matches_lost'),
|
||||
setsWon: _int('sets_won'),
|
||||
setsLost: _int('sets_lost'),
|
||||
racket: _str('racket'),
|
||||
balls: _str('balls'),
|
||||
activityTypeOther: _str('activity_type_other'),
|
||||
activityDetails: _str('activity_details'),
|
||||
equipment: _str('equipment'),
|
||||
);
|
||||
|
||||
Future<void> _submit() async {
|
||||
final draft = _draft();
|
||||
final error = validateManualWorkout(draft);
|
||||
@ -233,27 +204,6 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
|
||||
];
|
||||
}
|
||||
|
||||
Widget _budgetBanner(ManualBudget budget) => Text(
|
||||
'Manual: ${budget.week}/$kManualWorkoutBudgetPer7Days this week · '
|
||||
'${budget.month}/$kManualWorkoutBudgetPer30Days this month',
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
fontSize: AppTextSize.body,
|
||||
),
|
||||
);
|
||||
|
||||
Widget _section(String title) => Padding(
|
||||
padding: const EdgeInsets.only(top: 16, bottom: 4),
|
||||
child: Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
fontSize: AppTextSize.subtitle,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _sportDropdown() => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: DropdownButton<String>(
|
||||
@ -292,22 +242,4 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _text(String key, String label, {int lines = 1}) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: TextField(
|
||||
key: Key('mw_$key'),
|
||||
controller: _fields[key],
|
||||
maxLines: lines,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
|
||||
// filled/fillColor/border inherit from the shared inputDecorationTheme
|
||||
// (theme.dart) — only the field-specific label needs setting here.
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
labelStyle: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@ -22,87 +22,12 @@ import 'package:workout_app/services/progression_sync_service.dart';
|
||||
import 'package:workout_app/services/storage_service.dart';
|
||||
import 'package:workout_app/ui/theme.dart';
|
||||
|
||||
/// Screen for editing per-exercise thresholds and manual weight overrides.
|
||||
///
|
||||
/// No [BackupSlot] is wired into the shared Sync settings screen: unlike the
|
||||
/// notes app and home_inventory, workout_app has no user-facing export/import
|
||||
/// action to hand it. `BackupService.export`/`readBackup` are called only from
|
||||
/// [StorageService]'s automatic paths (on every weight/threshold write, and
|
||||
/// once at startup via `restoreFromBackupIfNeeded`) -- there is nothing for a
|
||||
/// manual "Export"/"Import" button to trigger that isn't already automatic,
|
||||
/// and a blind manual import would risk clobbering current progression with
|
||||
/// whatever is on external storage. The storage-permission affordance itself
|
||||
/// is a device permission, not a sync action, so it stays here rather than
|
||||
/// moving to either sync screen.
|
||||
class SettingsScreen extends StatefulWidget {
|
||||
/// Creates a [SettingsScreen].
|
||||
const SettingsScreen({
|
||||
super.key,
|
||||
this.httpClient,
|
||||
this.firebaseFactory,
|
||||
this.googleFirebaseFactory,
|
||||
this.googleAvailable,
|
||||
this.accountLoader,
|
||||
this.accountSaver,
|
||||
this.accountClearer,
|
||||
this.sessionProbe,
|
||||
this.storageChecker,
|
||||
this.storageRequester,
|
||||
this.progressionPuller,
|
||||
});
|
||||
|
||||
/// Injectable HTTP client, passed through to [GitHubMirrorScreen] so its
|
||||
/// device-flow requests never hit the real network in tests.
|
||||
final http.Client? httpClient;
|
||||
|
||||
/// Builds the Firebase client. Injected so tests need no platform channel.
|
||||
final Future<FirebaseRestClient?> Function()? firebaseFactory;
|
||||
|
||||
/// Builds the Firebase backend via Google sign-in. Separate from
|
||||
/// [firebaseFactory] because it reaches the Google plugin's platform
|
||||
/// channel, which `flutter test` has no binding for.
|
||||
final Future<FirebaseRestClient?> Function()? googleFirebaseFactory;
|
||||
|
||||
/// Whether to offer the Google button. Defaults to what the platform
|
||||
/// supports; injected by tests, whose host reports unsupported.
|
||||
final bool? googleAvailable;
|
||||
|
||||
/// Keystore accessors for the Firebase account. Injected as a group so the
|
||||
/// connect/disconnect flows are testable without a platform channel --
|
||||
/// `flutter test` has no binding for one.
|
||||
final Future<FirebaseAccount?> Function()? accountLoader;
|
||||
|
||||
/// Persists the account. See [accountLoader].
|
||||
final Future<void> Function(FirebaseAccount)? accountSaver;
|
||||
|
||||
/// Forgets the account and any cached session. See [accountLoader].
|
||||
final Future<void> Function()? accountClearer;
|
||||
|
||||
/// Whether a Firebase session is stored. See [accountLoader].
|
||||
///
|
||||
/// Separate from [accountLoader] because the two answer different
|
||||
/// questions: the account marker is bookkeeping, the session is the
|
||||
/// credential. A device can hold the second without the first, and
|
||||
/// reporting only the first is what made a syncing phone read as
|
||||
/// "not connected".
|
||||
final Future<bool> Function()? sessionProbe;
|
||||
|
||||
/// Reads whether storage permission is held. Injected for the same reason as
|
||||
/// [accountLoader]: `permission_handler` is a platform channel, and calling
|
||||
/// it unguarded in `initState` made every settings-screen test throw.
|
||||
final Future<bool> Function()? storageChecker;
|
||||
|
||||
/// Opens the system grant page. See [storageChecker].
|
||||
final Future<bool> Function()? storageRequester;
|
||||
|
||||
/// Pulls progression after returning from Sync settings. See
|
||||
/// [_openSyncSettings] for why this fires on pop rather than being hooked
|
||||
/// into the shared screen's connect flow.
|
||||
final Future<ProgressionSyncResult> Function()? progressionPuller;
|
||||
|
||||
@override
|
||||
State<SettingsScreen> createState() => _SettingsScreenState();
|
||||
}
|
||||
part 'settings_screen_actions.dart';
|
||||
part 'settings_screen_exercise_sections.dart';
|
||||
part 'settings_screen_rows.dart';
|
||||
part 'settings_screen_sections.dart';
|
||||
part 'settings_screen_thresholds.dart';
|
||||
part 'settings_screen_widget.dart';
|
||||
|
||||
class _SettingsScreenState extends State<SettingsScreen> {
|
||||
bool _loading = true;
|
||||
@ -194,20 +119,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
/// immediately instead of waiting for the next app launch, which also
|
||||
/// pulls unconditionally at startup.
|
||||
Future<void> _openSyncSettings() async {
|
||||
await Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => SyncSettingsScreen(
|
||||
accountLoader: widget.accountLoader ?? loadAccount,
|
||||
accountSaver: widget.accountSaver ?? saveAccount,
|
||||
accountClearer: widget.accountClearer ?? clearAccount,
|
||||
sessionProbe: widget.sessionProbe ?? isFirebaseConfigured,
|
||||
firebaseFactory: widget.firebaseFactory ?? openFirebase,
|
||||
googleFirebaseFactory:
|
||||
widget.googleFirebaseFactory ?? openFirebaseWithGoogle,
|
||||
googleAvailable: widget.googleAvailable ?? googleSignInSupported,
|
||||
),
|
||||
),
|
||||
);
|
||||
await _pushSyncSettingsScreen();
|
||||
if (!mounted) return;
|
||||
final restored =
|
||||
await (widget.progressionPuller ??
|
||||
@ -222,14 +134,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openGitHubMirror() async {
|
||||
await Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => GitHubMirrorScreen(httpClient: widget.httpClient),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _onWeightChanged(String name, double value) {
|
||||
setState(() => _weights[name] = value);
|
||||
_weightTimers[name]?.cancel();
|
||||
@ -258,514 +162,50 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _resetToDefaults() async {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||
title: Text(
|
||||
'Reset to defaults?',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
content: Text(
|
||||
'All weights and thresholds will be reset. '
|
||||
'Streak counters will be cleared.',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text(
|
||||
'Cancel',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: Text('Reset', style: TextStyle(color: colorScheme.error)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ok == true) {
|
||||
for (final name in _orderedNames) {
|
||||
await StorageService.instance.resetExerciseToDefaults(name);
|
||||
}
|
||||
await _load();
|
||||
}
|
||||
}
|
||||
|
||||
List<String> get _orderedNames {
|
||||
final seen = <String>{};
|
||||
return [
|
||||
...workoutA,
|
||||
...workoutB,
|
||||
].map((e) => e.name).where(seen.add).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||
title: Text(
|
||||
'Settings',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
iconTheme: IconThemeData(color: colorScheme.onSurface),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _loading ? null : _resetToDefaults,
|
||||
child: Text(
|
||||
'Reset defaults',
|
||||
style: TextStyle(color: colorScheme.error),
|
||||
),
|
||||
),
|
||||
],
|
||||
appBar: _SettingsAppBar(
|
||||
loading: _loading,
|
||||
onReset: () => unawaited(_resetToDefaults()),
|
||||
),
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
const _SectionHeader('WEIGHTS'),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Override current working weight. '
|
||||
'Resets streak counters. Rounded to 2.5 kg.',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
..._orderedNames.map((name) {
|
||||
final w = _weights[name];
|
||||
if (w == null) return const SizedBox.shrink();
|
||||
return _WeightRow(
|
||||
name: name,
|
||||
weight: w,
|
||||
onChanged: (v) => _onWeightChanged(name, v),
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 20),
|
||||
const _SectionHeader('TARGET REPS'),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Override target reps per set. Resets streak counters. '
|
||||
'Progression only ever raises reps, so this is the only way '
|
||||
'to lower one.',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
..._orderedNames.map((name) {
|
||||
final r = _reps[name];
|
||||
if (r == null) return const SizedBox.shrink();
|
||||
return _RepsRow(
|
||||
name: name,
|
||||
reps: r,
|
||||
onChanged: (v) => _onRepsChanged(name, v),
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 20),
|
||||
const _SectionHeader('PROGRESSION THRESHOLDS'),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Consecutive successes (↑) or failures (↓) '
|
||||
'before weight changes.',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
..._orderedNames.map((name) {
|
||||
final sThresh = _successThresholds[name] ?? 3;
|
||||
final fThresh = _failThresholds[name] ?? 2;
|
||||
return _ExerciseThresholdCard(
|
||||
name: name,
|
||||
successThreshold: sThresh,
|
||||
failThreshold: fThresh,
|
||||
onSuccessChanged: (v) =>
|
||||
_onThresholdChanged(name, v, _failThresholds[name]!),
|
||||
onFailChanged: (v) =>
|
||||
_onThresholdChanged(name, _successThresholds[name]!, v),
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 20),
|
||||
const _SectionHeader('SYNC'),
|
||||
const SizedBox(height: 4),
|
||||
if (_progressionStatus != null) ...[
|
||||
Text(
|
||||
_progressionStatus!,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
Card(
|
||||
margin: EdgeInsets.zero,
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
child: Column(
|
||||
children: [
|
||||
ListTile(
|
||||
title: Text(
|
||||
'Sync settings',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
subtitle: Text(
|
||||
'Firebase sync',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
trailing: Icon(
|
||||
Icons.chevron_right,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
onTap: () => unawaited(_openSyncSettings()),
|
||||
),
|
||||
Divider(
|
||||
height: 1,
|
||||
color: colorScheme.onSurfaceVariant.withValues(
|
||||
alpha: 0.2,
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
title: Text(
|
||||
'Advanced sync (GitHub)',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
subtitle: Text(
|
||||
'Cutover mirror — not recommended',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
trailing: Icon(
|
||||
Icons.chevron_right,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
onTap: () => unawaited(_openGitHubMirror()),
|
||||
),
|
||||
],
|
||||
),
|
||||
_WeightsSection(
|
||||
orderedNames: _orderedNames,
|
||||
weights: _weights,
|
||||
onWeightChanged: _onWeightChanged,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
const _SectionHeader('OFFLINE BACKUP'),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
_storageGranted
|
||||
? 'Granted. Progression is also written to '
|
||||
'$kBackupPath, so it survives a reinstall even '
|
||||
'with no network.'
|
||||
: 'Optional. Progression is restored from Firebase on '
|
||||
'a fresh install, so this is a second, offline '
|
||||
'copy — not a requirement. Granting it also keeps '
|
||||
'a readable snapshot at $kBackupPath.',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
_RepsSection(
|
||||
orderedNames: _orderedNames,
|
||||
reps: _reps,
|
||||
onRepsChanged: _onRepsChanged,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_ThresholdsSection(
|
||||
orderedNames: _orderedNames,
|
||||
successThresholds: _successThresholds,
|
||||
failThresholds: _failThresholds,
|
||||
onThresholdChanged: (name, success, fail) =>
|
||||
unawaited(_onThresholdChanged(name, success, fail)),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_SyncSection(
|
||||
progressionStatus: _progressionStatus,
|
||||
onOpenSyncSettings: () => unawaited(_openSyncSettings()),
|
||||
onOpenGitHubMirror: () => unawaited(_openGitHubMirror()),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_OfflineBackupSection(
|
||||
storageGranted: _storageGranted,
|
||||
onGrantStorage: _grantStorage,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (_storageGranted)
|
||||
const Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle, size: 20),
|
||||
SizedBox(width: 8),
|
||||
Expanded(child: Text('Storage permission granted')),
|
||||
],
|
||||
)
|
||||
else
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: _grantStorage,
|
||||
icon: const Icon(Icons.sd_storage),
|
||||
label: const Text('Grant storage permission'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SectionHeader extends StatelessWidget {
|
||||
const _SectionHeader(this.text);
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
letterSpacing: 1.4,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RepsRow extends StatelessWidget {
|
||||
const _RepsRow({
|
||||
required this.name,
|
||||
required this.reps,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final int reps;
|
||||
final ValueChanged<int> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
name,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
),
|
||||
_StepperButton(
|
||||
icon: Icons.remove,
|
||||
onTap: () => onChanged((reps - 1).clamp(1, 999)),
|
||||
),
|
||||
SizedBox(
|
||||
width: 72,
|
||||
child: Text(
|
||||
'$reps reps',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontSize: AppTextSize.label,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
_StepperButton(
|
||||
icon: Icons.add,
|
||||
onTap: () => onChanged((reps + 1).clamp(1, 999)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _WeightRow extends StatelessWidget {
|
||||
const _WeightRow({
|
||||
required this.name,
|
||||
required this.weight,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final double weight;
|
||||
final ValueChanged<double> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
name,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
),
|
||||
_StepperButton(
|
||||
icon: Icons.remove,
|
||||
onTap: () => onChanged(
|
||||
(weight - kWeightIncrement).clamp(0.0, 999.0),
|
||||
),
|
||||
),
|
||||
// Fixed-width container supports up to "999.9kg" (7 chars).
|
||||
SizedBox(
|
||||
width: 72,
|
||||
child: Text(
|
||||
'${weight}kg',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontSize: AppTextSize.label,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
_StepperButton(
|
||||
icon: Icons.add,
|
||||
onTap: () => onChanged(weight + kWeightIncrement),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StepperButton extends StatelessWidget {
|
||||
const _StepperButton({required this.icon, required this.onTap});
|
||||
|
||||
final IconData icon;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
width: 36,
|
||||
height: 36,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
child: Icon(icon, color: colorScheme.onSurface, size: 18),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ExerciseThresholdCard extends StatelessWidget {
|
||||
const _ExerciseThresholdCard({
|
||||
required this.name,
|
||||
required this.successThreshold,
|
||||
required this.failThreshold,
|
||||
required this.onSuccessChanged,
|
||||
required this.onFailChanged,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final int successThreshold;
|
||||
final int failThreshold;
|
||||
final ValueChanged<int> onSuccessChanged;
|
||||
final ValueChanged<int> onFailChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
name,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_ThresholdRow(
|
||||
label: '↑ Increase after N successes',
|
||||
value: successThreshold,
|
||||
color: status.success,
|
||||
onChanged: onSuccessChanged,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
_ThresholdRow(
|
||||
label: '↓ Decrease after N failures',
|
||||
value: failThreshold,
|
||||
color: colorScheme.error,
|
||||
onChanged: onFailChanged,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ThresholdRow extends StatelessWidget {
|
||||
const _ThresholdRow({
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.color,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final int value;
|
||||
final Color color;
|
||||
final ValueChanged<int> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
for (int i = 1; i <= 5; i++)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 4),
|
||||
child: GestureDetector(
|
||||
onTap: () => onChanged(i),
|
||||
child: Container(
|
||||
width: 32,
|
||||
height: 32,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: i == value
|
||||
? color
|
||||
: colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
'$i',
|
||||
style: TextStyle(
|
||||
// on-fill on the selected (filled) circle.
|
||||
color: i == value
|
||||
? colorScheme.onPrimary
|
||||
: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,86 @@
|
||||
// Settings actions that need no `setState`: the GitHub-mirror route, the
|
||||
// reset-to-defaults confirmation, and the exercise ordering both use.
|
||||
//
|
||||
// A `part` so the extension keeps reaching `_load`, `widget` and `context`.
|
||||
// `setState` is `@protected` and unreachable from an extension, which is
|
||||
// exactly the line these three sit on the safe side of — each either
|
||||
// navigates or delegates to `_load`, and `_load` owns the setState.
|
||||
part of 'settings_screen.dart';
|
||||
|
||||
/// The settings screen's setState-free actions.
|
||||
extension _SettingsScreenActions on _SettingsScreenState {
|
||||
Future<void> _openGitHubMirror() async {
|
||||
await Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => GitHubMirrorScreen(httpClient: widget.httpClient),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _resetToDefaults() async {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||
title: Text(
|
||||
'Reset to defaults?',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
content: Text(
|
||||
'All weights and thresholds will be reset. '
|
||||
'Streak counters will be cleared.',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text(
|
||||
'Cancel',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: Text('Reset', style: TextStyle(color: colorScheme.error)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ok == true) {
|
||||
for (final name in _orderedNames) {
|
||||
await StorageService.instance.resetExerciseToDefaults(name);
|
||||
}
|
||||
await _load();
|
||||
}
|
||||
}
|
||||
|
||||
List<String> get _orderedNames {
|
||||
final seen = <String>{};
|
||||
return [
|
||||
...workoutA,
|
||||
...workoutB,
|
||||
].map((e) => e.name).where(seen.add).toList();
|
||||
}
|
||||
|
||||
/// Pushes the shared sync-settings screen, wiring every injectable seam.
|
||||
///
|
||||
/// Split from [_SettingsScreenState._openSyncSettings], which keeps the
|
||||
/// post-return progression pull because that half calls `setState`.
|
||||
Future<void> _pushSyncSettingsScreen() async {
|
||||
await Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => SyncSettingsScreen(
|
||||
accountLoader: widget.accountLoader ?? loadAccount,
|
||||
accountSaver: widget.accountSaver ?? saveAccount,
|
||||
accountClearer: widget.accountClearer ?? clearAccount,
|
||||
sessionProbe: widget.sessionProbe ?? isFirebaseConfigured,
|
||||
firebaseFactory: widget.firebaseFactory ?? openFirebase,
|
||||
googleFirebaseFactory:
|
||||
widget.googleFirebaseFactory ?? openFirebaseWithGoogle,
|
||||
googleAvailable: widget.googleAvailable ?? googleSignInSupported,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,161 @@
|
||||
// The WEIGHTS, TARGET REPS and PROGRESSION THRESHOLDS sections.
|
||||
//
|
||||
// A `part` for the same reason as settings_screen_sections.dart: these stay
|
||||
// library-private. Each takes the ordered names plus the one map it reads, so
|
||||
// every `if (x == null)` and `?? default` below is the one the original
|
||||
// `build()` already had — the coverage gate is at 100% and a new branch is a
|
||||
// line no test reaches.
|
||||
part of 'settings_screen.dart';
|
||||
|
||||
/// The WEIGHTS section: per-exercise working-weight overrides.
|
||||
class _WeightsSection extends StatelessWidget {
|
||||
const _WeightsSection({
|
||||
required this.orderedNames,
|
||||
required this.weights,
|
||||
required this.onWeightChanged,
|
||||
});
|
||||
|
||||
/// Exercise names in display order.
|
||||
final List<String> orderedNames;
|
||||
|
||||
/// Current working weight per exercise; a missing entry renders nothing.
|
||||
final Map<String, double> weights;
|
||||
|
||||
/// Invoked with (name, newWeight) when a row changes.
|
||||
final void Function(String name, double value) onWeightChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const _SectionHeader('WEIGHTS'),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Override current working weight. '
|
||||
'Resets streak counters. Rounded to 2.5 kg.',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
...orderedNames.map((name) {
|
||||
final w = weights[name];
|
||||
if (w == null) return const SizedBox.shrink();
|
||||
return _WeightRow(
|
||||
name: name,
|
||||
weight: w,
|
||||
onChanged: (v) => onWeightChanged(name, v),
|
||||
);
|
||||
}),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The TARGET REPS section: per-exercise target-rep overrides.
|
||||
class _RepsSection extends StatelessWidget {
|
||||
const _RepsSection({
|
||||
required this.orderedNames,
|
||||
required this.reps,
|
||||
required this.onRepsChanged,
|
||||
});
|
||||
|
||||
/// Exercise names in display order.
|
||||
final List<String> orderedNames;
|
||||
|
||||
/// Target reps per exercise; a missing entry renders nothing.
|
||||
final Map<String, int> reps;
|
||||
|
||||
/// Invoked with (name, newReps) when a row changes.
|
||||
final void Function(String name, int value) onRepsChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const _SectionHeader('TARGET REPS'),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Override target reps per set. Resets streak counters. '
|
||||
'Progression only ever raises reps, so this is the only way '
|
||||
'to lower one.',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
...orderedNames.map((name) {
|
||||
final r = reps[name];
|
||||
if (r == null) return const SizedBox.shrink();
|
||||
return _RepsRow(
|
||||
name: name,
|
||||
reps: r,
|
||||
onChanged: (v) => onRepsChanged(name, v),
|
||||
);
|
||||
}),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The PROGRESSION THRESHOLDS section: streak lengths before a weight change.
|
||||
class _ThresholdsSection extends StatelessWidget {
|
||||
const _ThresholdsSection({
|
||||
required this.orderedNames,
|
||||
required this.successThresholds,
|
||||
required this.failThresholds,
|
||||
required this.onThresholdChanged,
|
||||
});
|
||||
|
||||
/// Exercise names in display order.
|
||||
final List<String> orderedNames;
|
||||
|
||||
/// Successes before a weight increase, per exercise; defaults to 3.
|
||||
final Map<String, int> successThresholds;
|
||||
|
||||
/// Failures before a weight decrease, per exercise; defaults to 2.
|
||||
final Map<String, int> failThresholds;
|
||||
|
||||
/// Invoked with (name, successThreshold, failThreshold) on either change.
|
||||
final void Function(String name, int success, int fail) onThresholdChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const _SectionHeader('PROGRESSION THRESHOLDS'),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Consecutive successes (↑) or failures (↓) '
|
||||
'before weight changes.',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
...orderedNames.map((name) {
|
||||
final sThresh = successThresholds[name] ?? 3;
|
||||
final fThresh = failThresholds[name] ?? 2;
|
||||
return _ExerciseThresholdCard(
|
||||
name: name,
|
||||
successThreshold: sThresh,
|
||||
failThreshold: fThresh,
|
||||
onSuccessChanged: (v) =>
|
||||
onThresholdChanged(name, v, failThresholds[name]!),
|
||||
onFailChanged: (v) =>
|
||||
onThresholdChanged(name, successThresholds[name]!, v),
|
||||
);
|
||||
}),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,157 @@
|
||||
// Section header and the reps/weight adjustment rows.
|
||||
//
|
||||
// `part` files: these widgets are library-private and stay that way.
|
||||
// See history_screen_charts.dart for the full reasoning.
|
||||
part of 'settings_screen.dart';
|
||||
|
||||
class _SectionHeader extends StatelessWidget {
|
||||
const _SectionHeader(this.text);
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
letterSpacing: 1.4,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RepsRow extends StatelessWidget {
|
||||
const _RepsRow({
|
||||
required this.name,
|
||||
required this.reps,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final int reps;
|
||||
final ValueChanged<int> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
name,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
),
|
||||
_StepperButton(
|
||||
icon: Icons.remove,
|
||||
onTap: () => onChanged((reps - 1).clamp(1, 999)),
|
||||
),
|
||||
SizedBox(
|
||||
width: 72,
|
||||
child: Text(
|
||||
'$reps reps',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontSize: AppTextSize.label,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
_StepperButton(
|
||||
icon: Icons.add,
|
||||
onTap: () => onChanged((reps + 1).clamp(1, 999)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _WeightRow extends StatelessWidget {
|
||||
const _WeightRow({
|
||||
required this.name,
|
||||
required this.weight,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final double weight;
|
||||
final ValueChanged<double> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
name,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
),
|
||||
_StepperButton(
|
||||
icon: Icons.remove,
|
||||
onTap: () => onChanged(
|
||||
(weight - kWeightIncrement).clamp(0.0, 999.0),
|
||||
),
|
||||
),
|
||||
// Fixed-width container supports up to "999.9kg" (7 chars).
|
||||
SizedBox(
|
||||
width: 72,
|
||||
child: Text(
|
||||
'${weight}kg',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontSize: AppTextSize.label,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
_StepperButton(
|
||||
icon: Icons.add,
|
||||
onTap: () => onChanged(weight + kWeightIncrement),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StepperButton extends StatelessWidget {
|
||||
const _StepperButton({required this.icon, required this.onTap});
|
||||
|
||||
final IconData icon;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
width: 36,
|
||||
height: 36,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
child: Icon(icon, color: colorScheme.onSurface, size: 18),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,190 @@
|
||||
// The SYNC and OFFLINE BACKUP sections of the settings list.
|
||||
//
|
||||
// A `part` so these stay library-private: making them public would trip
|
||||
// `public_member_api_docs` and widen the app's API for no reason.
|
||||
//
|
||||
// Both are pure widgets rather than list-building methods on the state class.
|
||||
// Every conditional here is the one the original `build()` had, in the same
|
||||
// shape — no defaulted parameters, no `??` fallbacks, no extra null checks —
|
||||
// because a new branch is a line no existing test covers and the coverage
|
||||
// gate is at 100%.
|
||||
part of 'settings_screen.dart';
|
||||
|
||||
/// The SYNC section: progression status line plus the two sync routes.
|
||||
class _SyncSection extends StatelessWidget {
|
||||
const _SyncSection({
|
||||
required this.progressionStatus,
|
||||
required this.onOpenSyncSettings,
|
||||
required this.onOpenGitHubMirror,
|
||||
});
|
||||
|
||||
/// Last progression-sync outcome, or null when there is nothing to report.
|
||||
final String? progressionStatus;
|
||||
|
||||
/// Opens the Firebase sync settings screen.
|
||||
final VoidCallback onOpenSyncSettings;
|
||||
|
||||
/// Opens the legacy GitHub mirror screen.
|
||||
final VoidCallback onOpenGitHubMirror;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const _SectionHeader('SYNC'),
|
||||
const SizedBox(height: 4),
|
||||
if (progressionStatus != null) ...[
|
||||
Text(
|
||||
progressionStatus!,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
Card(
|
||||
margin: EdgeInsets.zero,
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
child: Column(
|
||||
children: [
|
||||
ListTile(
|
||||
title: Text(
|
||||
'Sync settings',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
subtitle: Text(
|
||||
'Firebase sync',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
trailing: Icon(
|
||||
Icons.chevron_right,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
onTap: onOpenSyncSettings,
|
||||
),
|
||||
Divider(
|
||||
height: 1,
|
||||
color: colorScheme.onSurfaceVariant.withValues(alpha: 0.2),
|
||||
),
|
||||
ListTile(
|
||||
title: Text(
|
||||
'Advanced sync (GitHub)',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
subtitle: Text(
|
||||
'Cutover mirror — not recommended',
|
||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
trailing: Icon(
|
||||
Icons.chevron_right,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
onTap: onOpenGitHubMirror,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The OFFLINE BACKUP section: what the permission buys, and how to grant it.
|
||||
class _OfflineBackupSection extends StatelessWidget {
|
||||
const _OfflineBackupSection({
|
||||
required this.storageGranted,
|
||||
required this.onGrantStorage,
|
||||
});
|
||||
|
||||
/// Whether storage permission is already held.
|
||||
final bool storageGranted;
|
||||
|
||||
/// Asks the OS for storage permission.
|
||||
final VoidCallback onGrantStorage;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const _SectionHeader('OFFLINE BACKUP'),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
storageGranted
|
||||
? 'Granted. Progression is also written to '
|
||||
'$kBackupPath, so it survives a reinstall even '
|
||||
'with no network.'
|
||||
: 'Optional. Progression is restored from Firebase on '
|
||||
'a fresh install, so this is a second, offline '
|
||||
'copy — not a requirement. Granting it also keeps '
|
||||
'a readable snapshot at $kBackupPath.',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (storageGranted)
|
||||
const Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle, size: 20),
|
||||
SizedBox(width: 8),
|
||||
Expanded(child: Text('Storage permission granted')),
|
||||
],
|
||||
)
|
||||
else
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: onGrantStorage,
|
||||
icon: const Icon(Icons.sd_storage),
|
||||
label: const Text('Grant storage permission'),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// App bar for the settings screen, with the Reset-defaults action.
|
||||
///
|
||||
/// Reset is disabled while [loading] so it cannot fire against half-read
|
||||
/// state — the same `_loading ? null : ...` the original `build()` used.
|
||||
class _SettingsAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
const _SettingsAppBar({required this.loading, required this.onReset});
|
||||
|
||||
/// Whether settings are still being read; disables Reset while true.
|
||||
final bool loading;
|
||||
|
||||
/// Invoked when the user taps Reset defaults.
|
||||
final VoidCallback onReset;
|
||||
|
||||
@override
|
||||
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return AppBar(
|
||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||
title: Text(
|
||||
'Settings',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
iconTheme: IconThemeData(color: colorScheme.onSurface),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: loading ? null : onReset,
|
||||
child: Text(
|
||||
'Reset defaults',
|
||||
style: TextStyle(color: colorScheme.error),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,123 @@
|
||||
// The stepper button and the per-exercise threshold card.
|
||||
//
|
||||
// See settings_screen_rows.dart for why these are `part` files.
|
||||
part of 'settings_screen.dart';
|
||||
|
||||
class _ExerciseThresholdCard extends StatelessWidget {
|
||||
const _ExerciseThresholdCard({
|
||||
required this.name,
|
||||
required this.successThreshold,
|
||||
required this.failThreshold,
|
||||
required this.onSuccessChanged,
|
||||
required this.onFailChanged,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final int successThreshold;
|
||||
final int failThreshold;
|
||||
final ValueChanged<int> onSuccessChanged;
|
||||
final ValueChanged<int> onFailChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final status = Theme.of(context).extension<AppStatusColors>()!;
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
name,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_ThresholdRow(
|
||||
label: '↑ Increase after N successes',
|
||||
value: successThreshold,
|
||||
color: status.success,
|
||||
onChanged: onSuccessChanged,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
_ThresholdRow(
|
||||
label: '↓ Decrease after N failures',
|
||||
value: failThreshold,
|
||||
color: colorScheme.error,
|
||||
onChanged: onFailChanged,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ThresholdRow extends StatelessWidget {
|
||||
const _ThresholdRow({
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.color,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final int value;
|
||||
final Color color;
|
||||
final ValueChanged<int> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
for (int i = 1; i <= 5; i++)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 4),
|
||||
child: GestureDetector(
|
||||
onTap: () => onChanged(i),
|
||||
child: Container(
|
||||
width: 32,
|
||||
height: 32,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: i == value
|
||||
? color
|
||||
: colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
'$i',
|
||||
style: TextStyle(
|
||||
// on-fill on the selected (filled) circle.
|
||||
color: i == value
|
||||
? colorScheme.onPrimary
|
||||
: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: AppTextSize.label,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user