diet-guard/diet_guard/tests/test_gatelock_keyboard.py
Krzysztof Rudnicki 1702685afd Make the meal gate usable without a pointer on a 1366x768 screen
The Log Meal tab did not fit this laptop, and had not for some time. Measured
under a real 1366x768 X server: it required 866px inside a 739px content pane
with every field EMPTY, and 938px with a day of meals logged.

Because the content frame was place()-centred it was sheared at BOTH edges at
once -- the "Diet Gate" title and the slot header (which meal you are being
asked to log) off the top, the calorie headline and the whole dashboard off the
bottom -- with no scrollbar anywhere in the package and nothing to indicate
content was missing. This is a hard lock: overrideredirect, a global grab, VT
switching disabled. Unreachable content is unrecoverable.

Two independent causes, both needed fixing:

- Every font size was handed to Tk as *points*. Tk encodes the unit in the
  SIGN of the size, and _gatelock_typography carried a comment asserting the
  opposite ("Tk has no separate px/pt distinction"). At ~100 DPI that made
  every string ~30% oversized. Negative sizes now; the docstring records why.
- There was no scroll container. build_layout now uses gatelock's
  ScrollableSurface, which top-anchors, scrolls by keyboard, and scrolls to
  follow focus.

Font sizes alone were not enough: they take the layout to 702px, still over the
571px pane at 1024x600. Both fixes are load-bearing.

The grams/items selector was mouse-only. tk.OptionMenu's Menubutton defaults to
takefocus=0, so ::tk::FocusOK rejects it and it never entered the tab ring --
verified by walking the real ring, which ran Entry -> Text -> Listbox -> Button
-> TNotebook and skipped it entirely. Switching units rescales the whole entry,
so a pointerless user could not correct "250 grams" to "3 items" inside a lock
they cannot leave without logging a meal. It is now two Radiobuttons, which are
in the ring by default and take both Space and Return -- and which post nothing,
unlike a menu, whose grab-stealing is why screen-locker bans OptionMenu on lock
surfaces outright.

Also: the focus ring was invisible (Tk's default is 1px BLACK on #211D1B) and
_build_desc actively inverted it by setting highlightbackground, the UNfocused
ring, so the box outlined while idle and went black the moment it took focus.
Enter now activates buttons (X11 Tk binds only <space>). Text widgets no longer
trap Tab. notebook.enable_traversal() is called, so Ctrl+Tab and Ctrl+PageDown
work. wraplength drops 900 -> 640, the line-length cap, which also stops a
label forcing a 900px-wide layout onto a 1024px screen.

The Flutter app had two controls with no keyboard route at all. Its desktop
target is the web build in a Chrome --app window, so a touch gesture is not a
fallback there, it is the only interaction:

- Deleting a history entry was bound solely to onLongPress. Long-press has no
  keyboard equivalent whatsoever. It now has a focusable IconButton; the
  long-press stays as a redundant pointer shortcut.
- Calendar day cells were a bare GestureDetector, so navigating to
  date-filtered history was pointer-only and invisible to a screen reader.
  Now Semantics(button: true) over an InkWell.

Plus: the filter sheet built a TextEditingController inside build() with the
caret forced to end-of-text, so every keystroke discarded it and silently undid
mid-string Home/End/arrow editing. And nothing capped width, so on the 1366px
desktop window prose ran ~180 characters per line (twice the readable limit)
and a four-digit kcal field spanned ~1334px. AppWidth adds those caps.

Tests: the render check is a failing test, not a script -- ruff runs with
--unsafe-fixes, whose T201 fix DELETES print statements, which would silently
turn a diagnostic into a no-op. test_gate_layout_fits.py was verified red on
the pre-fix code ("content 866 in viewport 768 -> NO SCROLL VIEWPORT ->
UNREACHABLE CONTENT") and green after. The Flutter suite gains its first
keyboard-reachability assertions; it previously had ~109 tester.tap calls and
zero checks that anything was focusable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 16:21:27 +02:00

300 lines
11 KiB
Python

"""Tests for the gate's pointer-free operability.
Every assertion here stands in for something a keyboard-only user could not do
before. The gate is a hard lock -- ``overrideredirect`` + a global grab + VT
switching disabled -- so it cannot be left without submitting the form. A
control that needs a pointer is therefore not an inconvenience but a lockout,
which is why these are correctness tests rather than polish.
The reachability and height side of the same requirement is covered by
``measure_gate_layout.py``; the real focus-ring walk lives in
``probe_gate_keyboard.py``.
"""
from __future__ import annotations
import tkinter as tk
from typing import TYPE_CHECKING, Any
import pytest
from diet_guard import _gatelock_buttons, _gatelock_ui
from diet_guard._gatelock_ui import UNIT_GRAMS, UNIT_ITEMS
from diet_guard.tests import _gate_keyboard_probe
from diet_guard.tests.conftest import _FAKE_TK, FakeRadiobutton
if TYPE_CHECKING:
from diet_guard._gatelock import MealGate
class TestButtonReturnKey:
"""Enter must activate a button; Tk binds only Space on X11."""
def test_return_invokes_the_button(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""The <Return> handler invokes the button and swallows the event."""
monkeypatch.setattr(_gatelock_buttons, "tk", _FAKE_TK)
fired: list[str] = []
bound: dict[str, Any] = {}
class _Button(FakeRadiobutton):
# Signature mirrors FakeWidget.bind so the override type-checks.
def bind(self, *args: object, **_kwargs: object) -> None:
bound[str(args[0])] = args[1]
def invoke(self) -> None:
fired.append("hit")
monkeypatch.setattr(_FAKE_TK, "Button", _Button)
_gatelock_buttons.make_button(
_FAKE_TK.Frame(),
text="Log & Continue",
variant="primary",
command=lambda: None,
)
assert bound["<Return>"](None) == "break"
assert fired == ["hit"]
def test_keypad_enter_is_bound_too(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""The numeric keypad's Enter is a separate keysym from Return."""
monkeypatch.setattr(_gatelock_buttons, "tk", _FAKE_TK)
bound: dict[str, Any] = {}
class _Button(FakeRadiobutton):
# Signature mirrors FakeWidget.bind so the override type-checks.
def bind(self, *args: object, **_kwargs: object) -> None:
bound[str(args[0])] = args[1]
def invoke(self) -> None:
pass
monkeypatch.setattr(_FAKE_TK, "Button", _Button)
_gatelock_buttons.make_button(
_FAKE_TK.Frame(),
text="Close",
variant="danger",
command=lambda: None,
)
assert "<KP_Enter>" in bound
class TestUnitSelectorIsKeyboardReachable:
"""The grams/items selector must not be a ``tk.OptionMenu``.
``OptionMenu``'s ``Menubutton`` defaults to ``takefocus=0``, so it never
entered the tab ring -- and a posted Tk menu also steals the lock's grab,
which the recovery tick then kills. Radiobuttons avoid both.
"""
def test_no_option_menu_is_constructed(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Building the gate never constructs an OptionMenu.
Asserted behaviourally by making the constructor explode, rather than by
grepping the source -- a source scan matches this module's own
explanatory comments about the widget it replaced.
"""
def _explode(*_args: object, **_kwargs: object) -> None:
message = "OptionMenu is banned on a lock surface"
raise AssertionError(message)
monkeypatch.setattr(tk, "OptionMenu", _explode)
root = tk.Tk()
try:
selector_row = tk.Frame(root)
vars_ = _gatelock_ui.make_vars(root)
_gatelock_ui._build_unit_selector(selector_row, vars_, lambda _u: None)
classes = [child.winfo_class() for child in selector_row.winfo_children()]
assert classes == ["Radiobutton", "Radiobutton"]
assert "Menubutton" not in classes
finally:
root.destroy()
def test_radio_options_are_in_the_focus_ring(self) -> None:
"""Both units are tab stops -- the OptionMenu never was."""
root = tk.Tk()
try:
row = tk.Frame(root)
row.pack()
vars_ = _gatelock_ui.make_vars(root)
_gatelock_ui._build_unit_selector(row, vars_, lambda _u: None)
root.focus_force()
root.update()
root.update_idletasks()
for child in row.winfo_children():
assert str(child.cget("takefocus")) != "0"
finally:
root.destroy()
def test_selecting_a_radio_fires_the_unit_callback(self) -> None:
"""Activating an option updates the var and notifies the controller."""
root = tk.Tk()
try:
row = tk.Frame(root)
vars_ = _gatelock_ui.make_vars(root)
seen: list[str] = []
_gatelock_ui._build_unit_selector(row, vars_, seen.append)
items = [
child
for child in row.winfo_children()
if str(child.cget("value")) == UNIT_ITEMS
]
items[0].invoke()
assert vars_.unit.get() == UNIT_ITEMS
assert seen == [UNIT_ITEMS]
finally:
root.destroy()
def test_both_units_are_offered(self, gate: MealGate) -> None:
"""Selecting each radio option drives the unit variable."""
assert gate._vars.unit.get() == UNIT_GRAMS
gate._vars.unit.set(UNIT_ITEMS)
assert gate._vars.unit.get() == UNIT_ITEMS
class TestNotebookTraversal:
"""Ctrl+Tab / Ctrl+PageDown tab switching must be enabled explicitly."""
def test_traversal_is_enabled(self, gate: MealGate) -> None:
"""``enable_traversal()`` is called, or the tab keys are dead.
ttk installs those toplevel bindings only on request, so omitting the
call leaves Ctrl+Tab, Ctrl+PageUp/Down and Alt+mnemonic doing nothing
while looking perfectly normal in the code.
"""
assert gate._notebook.traversal_enabled is True
class TestFocusRingIsVisible:
"""The focus ring must be the accent, not Tk's black default."""
def test_focus_kwargs_sets_the_focused_ring(self) -> None:
"""``highlightcolor`` (focused) is the accent and thickness is non-zero.
Setting only ``highlightbackground`` -- the *unfocused* ring -- is the
bug this replaced: the widget outlined while unfocused and went black
against ``bg`` the moment it took focus.
"""
kwargs = _gatelock_ui._COLORS.focus_kwargs()
assert kwargs["highlightcolor"] == _gatelock_ui._COLORS.accent
assert kwargs["highlightcolor"] != "#000000"
assert int(kwargs["highlightthickness"]) > 0
def test_prose_wrap_respects_the_line_length_cap(self) -> None:
"""Wrap width is the 640px cap, not the old 900px literal."""
assert _gatelock_ui._WRAP_PX == 640
class TestTypeScaleIsPixels:
"""Tk font sizes must be negative, i.e. pixels rather than points."""
@pytest.mark.parametrize(
"size",
[
_gatelock_ui.DISPLAY,
_gatelock_ui.SUBTITLE,
_gatelock_ui.BODY,
_gatelock_ui.LABEL,
_gatelock_ui.CAPTION,
],
)
def test_sizes_are_negative(self, size: int) -> None:
"""A positive size means points and renders ~30% oversized.
Measured: body at 16 points has a 26px linespace where 16 pixels gives
20px. That inflation alone pushed this layout off a 768px screen.
"""
assert size < 0
def test_scale_matches_the_design_system_magnitudes(self) -> None:
"""The magnitudes are still tokens.md's 32/24/20/16/14/12 scale."""
assert abs(_gatelock_ui.DISPLAY) == 32
assert abs(_gatelock_ui.TITLE) == 24
assert abs(_gatelock_ui.SUBTITLE) == 20
assert abs(_gatelock_ui.BODY) == 16
assert abs(_gatelock_ui.LABEL) == 14
assert abs(_gatelock_ui.CAPTION) == 12
class TestRealFocusRing:
"""Walk the ring Tab actually follows, against a real Tk.
Reading the code cannot answer this: Tk decides via ``::tk::FocusOK``, which
also rejects any widget whose *class* has no key bindings. That is why a
Canvas viewport was pointer-only and a Menubutton was skipped entirely --
neither looks unusual in source.
"""
def test_unit_selector_is_in_the_ring(self) -> None:
"""Both grams/items radio options are tab stops.
The ``OptionMenu`` they replaced was absent from the ring entirely, so
the unit -- which rescales the whole entry -- could only be changed with
a pointer, inside a lock requiring a logged meal to exit.
"""
report = _gate_keyboard_probe.probe()
assert report.classes.count("Radiobutton") == 2, report.describe()
def test_every_focusable_class_has_a_visible_ring(self) -> None:
"""No widget in the ring keeps Tk's black default highlight.
Tk ships ``highlightcolor="#000000"`` on a ``#211D1B`` background, so
the default is a ring that cannot be seen.
"""
report = _gate_keyboard_probe.probe()
invisible = {
name: color
for name, color in report.focus_rings_visible.items()
if color.lower() in {"", "#000000", "black"}
}
assert not invisible, f"invisible focus rings: {invisible}"
def test_scroll_viewport_is_a_focus_stop(self) -> None:
"""The Canvas viewport is reachable, so it can be scrolled by keyboard.
A bare ``tk.Canvas`` has no class key bindings and is therefore rejected
by ``FocusOK``; it only appears here because it opts in explicitly.
"""
report = _gate_keyboard_probe.probe()
assert report.has("Canvas"), report.describe()
def test_text_escapes_and_buttons_take_return(self) -> None:
"""The two Tk defaults that make a form unusable are both overridden."""
report = _gate_keyboard_probe.probe()
assert report.text_escapes_tab, report.describe()
assert report.buttons_take_return, report.describe()
class TestRealTkKeyboardBehaviour:
"""End-to-end checks against a real Tk, not the fakes.
The fakes cannot prove anything about Tk's own class bindings, and those
bindings are the whole problem: Tab-traps and missing Return bindings are
Tk defaults, not application code.
"""
def test_text_tab_escape_against_real_tk(self) -> None:
"""A real Text widget releases focus on Tab."""
root = tk.Tk()
try:
first = tk.Text(root)
first.pack()
second = tk.Entry(root)
second.pack()
_gatelock_ui._escape_text_tab_trap(first)
root.focus_force()
root.update()
first.focus_set()
root.update()
first.event_generate("<Tab>")
root.update()
root.update_idletasks()
assert root.focus_get() is not first
# And no literal tab was inserted.
assert "\t" not in first.get("1.0", "end")
finally:
root.destroy()