utils/gatelock/gatelock/_keyboard.py
Krzysztof Rudnicki f0be8c5919 Make lock surfaces keyboard-operable and safe on a 768px screen
gatelock v0.3.0. Every change here works around a Tk *default*, not an
application mistake -- which is why they belong in the shared backend rather
than being fixed four times.

On a lock surface these are not accessibility niceties. The lockers hold a
global input grab with VT switching disabled, so a control the keyboard cannot
reach, or a button clipped off the bottom of the screen, is a bricked machine.

LockConfig gains a type scale, a spacing scale and a focus-ring token:

- font() applies Tk's sign convention. Tk encodes the unit in the SIGN of the
  font size -- positive is points, negative is pixels -- so passing the
  design system's px values straight through rendered every string ~30%
  oversized (measured: body at 16pt has a 26px linespace where 16px gives 20).
  That alone pushed diet_guard's meal gate to 866px of content inside a 739px
  pane on a 1366x768 screen.
- focus_kwargs() sets highlightcolor, the *focused* ring. Tk's default is a 1px
  BLACK ring, invisible against the palette's #211D1B background. Note
  highlightbackground is the UNfocused ring: setting only that one inverts the
  affordance, which is what diet_guard was doing.

_keyboard.py collects three Tk defaults that each make a form unusable:

- tk.Text traps Tab (inserts a literal tab and refocuses itself) and no-ops
  Shift-Tab; the only exits are the undocumented Ctrl+Tab / Ctrl+Shift+Tab.
- tk.Button binds <space> on X11 but never <Return>, so the key a user reaches
  for to submit does nothing.
- Escape needs binding at the toplevel to work wherever focus happens to sit.

_scrollable.py adds ScrollableSurface, a viewport that content can actually be
reached in:

- A place()-centred frame takes its *requested* size and is clipped
  SYMMETRICALLY, so overflow removes the heading and the submit button at the
  same time, with no scrollbar and no hint anything is missing.
- A bare tk.Canvas has no class key bindings, so ::tk::FocusOK rejects it as a
  focus stop and the only way to scroll is dragging the thumb with a pointer.
- Canvas clipping does not unmap children, so scrolled-out fields stay in the
  tab ring while Tk never scrolls to follow focus -- Tab lands on fields the
  user can neither see nor reveal.
- A Canvas holds content in a canvas *item*, so it never propagates the
  content's requested size; a toplevel told to size itself has nothing to grow
  to. _request_content_size() fixes that, clamped to the display.

center_when_fits keeps short screens looking exactly as they did, so the
viewport can replace a centred frame without a visual change.

A scrollable dialog Toplevel is deliberately NOT the mechanism: on an
override-redirect lock surface a second toplevel steals the Tk grab, which the
recovery tick then kills -- the 2026-07-26 failure where a frozen sport
selector logged a walk as table tennis.

unified-design-system gains the two rule families this implements (pointer-free
operability, 1366x768 usable / 1024x600 graceful), a focus-ring token, and the
px/pt sign convention written down so it cannot recur.

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

104 lines
3.8 KiB
Python

r"""Keyboard-operability helpers for lock surfaces.
Every function here works around a **Tk default**, not an application mistake.
That is why they belong in the shared backend: the same three defects otherwise
recur in every locker, and each one is a lockout rather than an annoyance,
because a lock surface holds a global input grab with VT switching disabled.
There is no other window to click and no console to escape to.
The defaults, verified against Tk 8.6's own class bindings:
- ``tk.Text`` traps Tab. ``bind Text <Key-Tab>`` runs
``tk::TextInsert %W \\t; focus %W; break``, so Tab inserts a literal tab and
refocuses the widget, and ``<Shift-Tab>`` is bound to do nothing. The only
built-in exits are ``Ctrl+Tab``/``Ctrl+Shift+Tab``, which no UI advertises.
- ``tk.Button`` ignores Enter. On X11 ``bind Button <space>`` exists but there
is **no** ``<Return>`` binding, and ``entry.tcl``/``spinbox.tcl`` bind
``<Return>`` to ``{# nothing}``. So Space works and Enter -- the key a user
reaches for to submit -- does nothing at all.
- Focus is invisible. Tk ships ``highlightcolor="#000000"`` at
``highlightthickness=1``, i.e. a black ring on the palette's near-black
background. See :meth:`gatelock.LockConfig.focus_kwargs`.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import tkinter as tk
def escape_text_tab_trap(text: tk.Text) -> None:
"""Make Tab / Shift-Tab move focus out of a ``tk.Text``.
Without this a keyboard-only user who tabs into a multi-line field cannot
get back out to the submit button, which on a lock surface means they
cannot satisfy the lock at all.
Returning ``"break"`` is what stops Tk's own class binding from also
running and inserting the tab character.
Args:
text: The widget to un-trap.
"""
def _forward(_event: tk.Event) -> str:
text.tk_focusNext().focus_set()
return "break"
def _backward(_event: tk.Event) -> str:
text.tk_focusPrev().focus_set()
return "break"
text.bind("<Tab>", _forward, add="+")
text.bind("<Shift-Tab>", _backward, add="+")
# X11 delivers Shift+Tab as its own keysym, which <Shift-Tab> alone misses.
text.bind("<ISO_Left_Tab>", _backward, add="+")
def bind_activate(widget: tk.Widget) -> None:
"""Make Enter activate a button-like widget, as well as Space.
Tk binds only ``<space>`` on X11, so every button in an unmodified lock UI
is Space-only. Both the main Return key and the keypad's Enter are bound,
since they are distinct keysyms.
Args:
widget: A widget exposing ``invoke()`` (Button, Checkbutton, ...).
"""
def _activate(_event: tk.Event) -> str:
widget.invoke()
return "break"
widget.bind("<Return>", _activate, add="+")
widget.bind("<KP_Enter>", _activate, add="+")
def bind_cancel(widget: tk.Misc, callback: object) -> None:
"""Bind Escape on a widget's toplevel to a cancel/back action.
Bound at the toplevel rather than the widget so Escape works wherever focus
currently sits, which is the point -- a user who has tabbed somewhere
unexpected still needs the way back.
This is for *cancel* affordances only. Some lockers deliberately refuse
dismissal (an alarm you must solve a challenge to silence); making their
sanctioned back/cancel button reachable does not weaken that, but do not
use this to add an exit a lock is designed not to have.
Args:
widget: Any widget in the target toplevel.
callback: Zero-argument callable invoked on Escape.
"""
if not callable(callback):
message = "callback must be callable"
raise TypeError(message)
def _cancel(_event: tk.Event) -> str:
callback()
return "break"
widget.winfo_toplevel().bind("<Escape>", _cancel, add="+")