screen-locker/screen_locker/_ui_widgets.py
Krzysztof kuhy Rudnicki c0aae7d05b Make the lock overlay's sport selector usable, and focus its form fields
The manual-workout sport selector was a `tk.OptionMenu`, and while the screen
was locked it could not be changed. A posted Tk menu is a separate
override-redirect toplevel that takes the Tk grab for itself, and gatelock's
1s recovery tick attacks it from both sides: `_surfaces.enforce()` lifts the
lock surface over the menu, and `_reassert_grab()` read the grab sitting on
the menu as "the grab was lost" and yanked it back. The menu opened on click
and died within a second. On 2026-07-26 that forced an hour-long walk to be
logged through the table-tennis form, with the reason typed into `racket`.

Radio buttons instead. They are ordinary children of the surface, so they
lift with it and live inside the root's grab tree -- neither mechanism can
reach them. That is a structural guarantee, not a tuned workaround; the
alternative, teaching gatelock to skip its lift while a popup is posted,
would open a window where something could cover the lock. They are also the
first version of this control styled from the shared palette, where the
OptionMenu was default grey on the dark overlay.

Nothing on a lock surface may open a popup, so two halves enforce it. The
static half walks each module's AST for popup-creating names -- AST rather
than a source regex because the modules explain this bug in prose that names
the very widgets being banned. Its module list is derived ("imports tkinter",
minus a short reasoned exemption list) rather than hardcoded, so a new lock
screen is in scope the day it is written; a hardcoded list drafted today
would already have missed `_sick_dialog`. The behavioural half is
`scripts/verify_lock_popup_safety.py`: it builds the real form with real Tk,
replays both hostile behaviours for five ticks, and re-runs the original
failure so the mechanism stays demonstrated rather than described. It
re-execs itself under Xvfb -- a global grab on the developer's own session
would freeze it -- and a CI job runs it, because the pytest suite replaces
the whole `tk` module and so cannot host it.

Separately, no field ever took keyboard focus. Under a global grab that means
typing goes nowhere with no other window on screen to reveal why. The
manual-workout and sick-justification forms now each name their own first
field via a `focus=` flag; `on_focus_ready` genuinely has nothing to focus
(it fires before those screens exist) and its docstring now says that instead
of claiming the lock window has no typed input at all.

`scripts/fix_2026_07_26_sport.py` re-files that walk as sport "other",
rebuilt through the form's own draft/validate/build path so it carries
exactly the writer's key set, and re-signed. `start_time` and the date are
untouched so `workout_id` stays stable and the phone converges instead of
gaining a duplicate. Kept as the audit trail for the edit; the walk's details
come from the entry and `--details`, so nothing personal lands in a tracked
file.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 15:08:08 +02:00

172 lines
5.5 KiB
Python

"""UI widget helper methods mixin for the screen locker."""
from __future__ import annotations
import contextlib
import tkinter as tk
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable
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 UIWidgetsMixin:
"""Mixin providing low-level widget creation helpers."""
def clear_container(self) -> None:
"""Remove all widgets from the main container, on every monitor."""
self.container.clear()
def _label(
self,
text: str,
*,
font_size: int = 36,
color: str | None = None,
pady: int = 20,
) -> WidgetGroup:
"""Create and pack a bold label on every monitor."""
label = self.container.child_widgets(
tk.Label,
text=text,
font=(self._colors.font_family, font_size, "bold"),
fg=color or self._colors.fg,
bg=self._colors.bg,
)
label.pack(pady=pady)
return label
def _text(
self,
text: str,
*,
font_size: int = 18,
color: str | None = None,
pady: int = 10,
) -> WidgetGroup:
"""Create and pack a non-bold text label on every monitor."""
label = self.container.child_widgets(
tk.Label,
text=text,
font=(self._colors.font_family, font_size),
fg=color or self._colors.fg,
bg=self._colors.bg,
)
label.pack(pady=pady)
return label
def _fg_for(self, bg: str) -> str:
"""Return the correct label color for a widget with background `bg`.
The four filled semantic surfaces (accent/success/warning/danger)
all sit in the same mid-light lightness band, so `fg` (near-white,
meant for the neutral `bg`/`field_bg` surfaces) under-contrasts on
every one of them -- `on_fill` (dark) is required instead. Deriving
this from `bg` means a new filled-button call site can't reintroduce
the bug by omission.
"""
fills = {
self._colors.accent,
self._colors.success,
self._colors.warning,
self._colors.danger,
}
return self._colors.on_fill if bg in fills else self._colors.fg
def _button(
self,
parent: FrameGroup,
text: str,
*,
bg: str,
command: Callable[[], None],
width: int = 10,
) -> WidgetGroup:
"""Create a styled button on every monitor (caller must pack).
Every copy gets the *same* ``command``, so pressing the button on
whichever screen the user is actually looking at does the one thing
once -- the same trick the shared entry variable plays for typing.
Padding follows the shared 2x horizontal:vertical ratio (rule 22);
`relief="flat"` is the one depth technique every button in the app
uses now (rule 27), matching what `_heat_skip.py` already did alone.
"""
return parent.child_widgets(
tk.Button,
text=text,
font=(self._colors.font_family, 24, "bold"),
bg=bg,
fg=self._fg_for(bg),
width=width,
command=command,
cursor="hand2" if self.demo_mode else "",
relief="flat",
padx=24,
pady=12,
)
def _button_row(self) -> FrameGroup:
"""Create and pack a horizontal button container on every monitor."""
frame = self.container.child_frame(bg=self._colors.bg)
frame.pack(pady=20)
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=8, fill="x")
row.child_widgets(
tk.Label,
text=label,
font=(self._colors.font_family, 14),
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_family, 14),
bg=self._colors.field_bg,
fg=self._colors.fg,
insertbackground=self._colors.fg,
)
entries.pack(side="top", anchor="w", pady=4)
for entry in entries:
disable_paste(entry)
if focus:
entries.first.focus_set()