Compare commits

..

3 Commits

Author SHA1 Message Date
48f6c7420f Gate the 250-line cap on every commit, repo-wide
Some checks are pending
crdt-sync pre-commit / pre-commit (push) Waiting to run
crdt-sync tests / test (3.10) (push) Waiting to run
crdt-sync tests / test (3.11) (push) Waiting to run
crdt-sync tests / test (3.12) (push) Waiting to run
design_system tests / test (push) Waiting to run
gatelock pre-commit / pre-commit (push) Waiting to run
gatelock tests / test (3.10) (push) Waiting to run
gatelock tests / test (3.11) (push) Waiting to run
gatelock tests / test (3.12) (push) Waiting to run
palette drift / palette (push) Waiting to run
sync_settings_ui tests / test (push) Waiting to run
web_ui tests / test (push) Waiting to run
A refactor without a gate silently regrows, so this is the part that makes the
cap stick. Until now the repo had no root .pre-commit-config.yaml at all --
`git commit` ran zero hooks, and the five subproject configs only covered their
own directories.

Adds a root config wiring scripts/check_file_length.sh as a local hook, and
carries the same hook in each of the five subproject configs so committing
with one of those is gated too. Staged files only, so an unrelated commit
never breaks on a violation it did not introduce; exit 1, not a warning; no
baseline and no allowlist, since those are suppressions.

Verified in a throwaway worktree, both directions:
  - a staged 261-line file fails the commit (exit 1, HEAD unchanged, no
    commit object created)
  - a staged 200-line file commits normally (exit 0)

The 44 files still over the cap cannot block this: the hook only ever sees
what a commit touches.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CFSGeWxHPY5rHUGrPqhcmG
2026-08-22 14:31:35 +02:00
e651b1af17 gatelock: split _scrollable.py 495 -> 243 lines across four modules
Cut along concerns rather than line counts, so each file answers one question:

  _scrollfit.py   (180) — does the content fit, and what layout follows?
  _scrollkeys.py  (176) — key/wheel bindings and the six scroll commands
  _userintent.py  (106) — was this focus move the user's doing, or the app's?
  _scrollable.py  (243) — the widget wiring and the public surface

_scrollfit takes an explicit FitTarget bundle rather than the surface, matching
the ArmingCollaborators pattern; UserIntentTracker owns the two fields that
answer "did the user just act?", which is the guard that keeps the viewport
from scrolling itself under someone who touched nothing.

The 45-line module docstring — the three Tk defaults this viewport exists to
prevent, and the failure behind each — moved to docs/scrollable-viewport.md
rather than being trimmed. It is load-bearing rationale, so it is referenced,
not deleted.

389 passed, 100% branch coverage — unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CFSGeWxHPY5rHUGrPqhcmG
2026-08-22 14:28:21 +02:00
940bf19d54 gatelock: split _window.py 571 -> 243 lines across four modules
_window.py was the repo's largest file and could not be read in one piece.
Split along the seams the file already marked out, keeping the public API
and every existing import path intact:

  _config.py  (215) — LockConfig, the design tokens and preset resolution
  _arming.py  (178) — the way up: VT-disable, backdrop, surfaces, input grab
  _preempt.py (118) — naming a blocked grab's holder, standing a weaker one down
  _hooks.py   (51)  — the LockWindowHooks Protocol, pure interface
  _window.py  (243) — construction, focus, and teardown

_arming takes an explicit ArmingCollaborators bundle rather than the window
itself, mirroring the existing RecoveryCollaborators; setup() returns whether
VT was disabled instead of mutating the window. That leaves no reach-back into
private members (ruff SLF001 clean) and makes the arming sequence testable
without a window.

LockConfig is re-exported from _window, so `from gatelock._window import
LockConfig` — which five sibling modules and the tests already do — still
resolves. Tests that patched moved symbols were retargeted to their new home;
the dead _maybe_preempt delegate, whose only callers were tests, is gone.

389 passed, 100% branch coverage — identical to before the split.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CFSGeWxHPY5rHUGrPqhcmG
2026-08-22 14:20:11 +02:00
19 changed files with 1269 additions and 701 deletions

27
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,27 @@
# Repo-wide gate for the shared 250-line file cap (refactor_claude_todo.md).
#
# A file that cannot be read in one piece forces re-reads and partial edits,
# which is the largest avoidable cost in an LLM-assisted workflow. A refactor
# without a gate silently regrows, so this is the part that makes it stick.
#
# Checks only the files in the commit, so an unrelated commit never breaks on
# a violation it did not introduce, and it FAILS (exit 1) rather than warning.
# No baseline and no allowlist -- those are suppressions.
#
# The subprojects (gatelock/, crdt-sync/, web_ui/, design_system/,
# sync_settings_ui/) each keep their own .pre-commit-config.yaml for their own
# linters, and carry this same hook so committing with one of those configs is
# gated too. This root config is what `pre-commit install` wires up, and it is
# the only one that covers the subprojects without a config of their own
# (aur-publish/, guard-lib/, crdt_sync_dart/, file_length/, ...).
#
# `entry` is not run through a shell, so `~` would not expand: the absolute
# path is deliberate.
repos:
- repo: local
hooks:
- id: file-length-cap
name: file length <= 250 lines
entry: bash /home/kuhy/utils/scripts/check_file_length.sh
language: system
pass_filenames: true

View File

@ -40,6 +40,11 @@ repos:
- repo: local
hooks:
- id: file-length-cap
name: file length <= 250 lines
entry: bash /home/kuhy/utils/scripts/check_file_length.sh
language: system
pass_filenames: true
- id: subproject-scope
name: subproject scope regex still matches
entry: scripts/check_subproject_scope.sh crdt-sync

View File

@ -27,6 +27,11 @@ repos:
- repo: local
hooks:
- id: file-length-cap
name: file length <= 250 lines
entry: bash /home/kuhy/utils/scripts/check_file_length.sh
language: system
pass_filenames: true
- id: subproject-scope
name: subproject scope regex still matches
entry: scripts/check_subproject_scope.sh design_system

View File

@ -40,6 +40,11 @@ repos:
- repo: local
hooks:
- id: file-length-cap
name: file length <= 250 lines
entry: bash /home/kuhy/utils/scripts/check_file_length.sh
language: system
pass_filenames: true
- id: subproject-scope
name: subproject scope regex still matches
entry: scripts/check_subproject_scope.sh gatelock

View File

@ -0,0 +1,47 @@
# The scrollable lock viewport
Design rationale for `gatelock/_scrollable.py` and its collaborators
(`_scrollfit.py`, `_scrollkeys.py`, `_userintent.py`). Kept here rather
than in the module docstring so the module itself stays readable in one
piece; the behaviour it describes is load-bearing, not historical.
A keyboard-scrollable, focus-following viewport for lock-surface content.
Lock surfaces cannot solve "content taller than the screen" the obvious way.
A scrollable dialog would be a second ``Toplevel``, and on an
override-redirect lock surface a second toplevel steals the Tk grab, which the
recovery tick then kills a second later -- the 2026-07-26 failure where a
frozen sport selector logged a walk as table tennis. So the viewport has to
live inside the surface's own widget tree, which is what this provides.
Three defects this exists to prevent, all of them Tk defaults rather than
oversights in any one app:
1. **Centered content clips symmetrically.** A ``place``-centered frame takes
its *requested* size, so when it is too tall the parent shears equal
amounts off the top *and* the bottom -- losing the header and the submit
button together, with no scrollbar and no hint anything is missing. This
top-anchors content inside a scroll region instead.
2. **A Canvas viewport is not keyboard-scrollable.** ``tk.Canvas`` has no
class-level key bindings at all, so ``::tk::FocusOK`` rejects it as a focus
stop and the only way to move the view is dragging the scrollbar thumb with
a pointer. This makes the canvas focusable and binds PageUp/PageDown,
Home/End and arrows.
3. **Focus walks into invisible widgets.** Canvas clipping does not *unmap* a
child, so every scrolled-out-of-view field stays ``winfo viewable`` and
stays in the tab chain, while Tk never scrolls to follow focus. Tabbing
therefore lands on fields the user cannot see and cannot bring into view.
:meth:`ScrollableSurface.scroll_into_view` fixes that, but only for focus
the *user* moved.
Wheel scrolling is bound too, but as an addition -- never as the only path.
**Scrolling is the fallback, not the design.** A lock screen is supposed to
fit its screen; content that overflows is a layout defect, and :meth:`finalize`
logs it at ``warning`` so it gets fixed rather than lived with. While the
content fits -- the normal case -- the scroll region is pinned to the viewport
and the scrollbar is hidden, so the view cannot move at all. When it does
overflow, the view still only moves in response to a keypress, a click or the
wheel: an earlier version followed *programmatic* focus too, and since the apps
re-focus a widget on every repaint, the screen scrolled itself to mid-content
and back while the user was doing nothing (reported 2026-08-03, 1366x768).

View File

@ -0,0 +1,178 @@
"""Bringing the lock up: VT-disable, backdrop, surfaces, and the input grab.
Split out of :mod:`gatelock._window`, which keeps the object's construction
and its teardown. Everything here runs once, in order, on the way *up* --
:func:`setup` makes the lock visible and :func:`grab_input` makes it
exclusive.
Arming order matters and is deliberate: **arm first, render second.** The grab
and the VT-disable happen regardless of how many outputs are live, and the
surfaces are then built for whatever the user can actually see -- possibly
nothing. Zero live outputs means "lock without showing", never "decline to
lock". The inverse of that rule is what left the machine unlocked on
2026-07-25.
These are free functions over an explicit :class:`ArmingCollaborators` bundle
rather than methods, mirroring :class:`gatelock._recovery.RecoveryCollaborators`.
Nothing here reaches back into the window, so the arming sequence can be read
-- and tested -- without one.
"""
from __future__ import annotations
import contextlib
from dataclasses import dataclass
import logging
import tkinter as tk
from typing import TYPE_CHECKING
from gatelock._surfaces import needs_backdrop_root
from gatelock._vt import disable_vt_switching
if TYPE_CHECKING:
from collections.abc import Callable
from gatelock._config import LockConfig
from gatelock._detect import OutputChangeDetector
from gatelock._outputs import OutputEnumerator
from gatelock._recovery import RecoveryLoop
from gatelock._surfaces import SurfaceSet
_logger = logging.getLogger(__name__)
# Tk's attributes() takes the value positionally, so a bare `True` here trips
# the boolean-positional lint. Naming it satisfies both that rule and the type
# stubs, which have no keyword overload.
_TOPMOST_ON = True
# Default retry interval for a "global" grab that initially fails (e.g. a
# fullscreen game holds it). Used whenever grab_retry_ms is left unset.
_DEFAULT_GRAB_RETRY_MS = 200
@dataclass(frozen=True)
class ArmingCollaborators:
"""Everything the arming sequence needs from its owning window.
Attributes:
config: Declarative lock behavior for this instance.
surfaces: The per-output surface set to build into.
enumerator: Source of the live-output scan.
detector: Output-change watcher, started once the grab is taken.
recovery: Re-assertion loop, started alongside the detector.
notify_focus_ready: Called once the lock is mapped and grabbed.
log_grab_blocked: Called with the attempt count when a global grab is
still blocked, to name the holder and stand a weaker one down.
"""
config: LockConfig
surfaces: SurfaceSet
enumerator: OutputEnumerator
detector: OutputChangeDetector
recovery: RecoveryLoop
notify_focus_ready: Callable[[], None]
log_grab_blocked: Callable[[int], None]
def setup(root: tk.Tk, collab: ArmingCollaborators) -> bool:
"""Configure the backdrop and build a surface on every live output.
Disables VT switching first: strengthening the lock must not wait on
being able to draw anything. If no output is live, no surface is built
and the lock stays armed and invisible until one appears.
Args:
root: The Tk root acting as backdrop and grab holder.
collab: The window's arming collaborators.
Returns:
Whether VT switching was disabled, for the caller to remember so the
matching restore happens exactly once on the way back down.
"""
vt_disabled = False
if collab.config.resolved_disable_vt():
vt_disabled = disable_vt_switching()
if needs_backdrop_root(collab.config):
# The root is a plain black backdrop spanning the whole X screen,
# including any region a modeless output left behind. It holds the
# grab (X will not grab for a window that is not viewable) and
# never carries widgets.
root.overrideredirect(boolean=collab.config.resolved_overrideredirect())
collab.surfaces.update_backdrop()
else:
root.attributes("-topmost", _TOPMOST_ON)
scan = collab.enumerator.scan()
delta = collab.surfaces.apply(scan)
if not scan.live:
_logger.warning(
"no live outputs at startup (source=%s); arming the lock with "
"nothing displayed -- it will appear as soon as a monitor "
"comes back",
scan.source,
)
else:
_logger.info(
"lock armed on %d output(s): %s",
len(scan.live),
", ".join(output.name for output in scan.live),
)
if delta.unverified:
_logger.error(
"outputs live but not covered at startup: %s",
", ".join(delta.unverified),
)
return vt_disabled
def grab_input(root: tk.Tk, collab: ArmingCollaborators) -> None:
"""Take the configured grab, then start watching for output changes.
Args:
root: The Tk root that holds the grab.
collab: The window's arming collaborators.
"""
root.update_idletasks()
root.focus_force()
grab = collab.config.resolved_grab()
if grab == "global":
acquire_global_grab(root, collab, attempt=1)
elif grab == "local":
with contextlib.suppress(tk.TclError):
root.grab_set()
collab.detector.start()
collab.recovery.start()
root.after(100, collab.notify_focus_ready)
def acquire_global_grab(
root: tk.Tk, collab: ArmingCollaborators, *, attempt: int
) -> None:
"""Acquire the global input grab, retrying per ``grab_retry_ms``.
Args:
root: The Tk root that holds the grab.
collab: The window's arming collaborators.
attempt: 1-based attempt counter, used only to throttle the log.
"""
retry_ms = collab.config.grab_retry_ms
try:
root.grab_set_global()
except tk.TclError:
if retry_ms == 0:
_logger.warning("Global grab failed, falling back to local grab")
with contextlib.suppress(tk.TclError):
root.grab_set()
return
effective_retry_ms = retry_ms or _DEFAULT_GRAB_RETRY_MS
if not attempt % collab.config.grab_log_every:
collab.log_grab_blocked(attempt)
root.after(
effective_retry_ms,
lambda: acquire_global_grab(root, collab, attempt=attempt + 1),
)
return
with contextlib.suppress(tk.TclError):
root.focus_force()
collab.notify_focus_ready()

View File

@ -0,0 +1,215 @@
"""Declarative configuration and design tokens for :class:`LockWindow`.
Split out of :mod:`gatelock._window` so that the runtime mechanics (grab, VT,
lifecycle) and the *declarative* surface an embedding app actually fills in
can each be read in one piece. :class:`LockConfig` carries no behaviour beyond
resolving its own presets and the design-system scales, and nothing here
imports the window machinery -- the dependency runs one way only.
Imported from :mod:`gatelock._window` as well, so ``from gatelock._window
import LockConfig`` keeps working for the modules and tests that already do.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal
from gatelock import _density
from gatelock._arbiter import RANK_SCREEN_LOCKER
GrabKind = Literal["none", "local", "global"]
LockMode = Literal["soft", "hard"]
TypeRole = Literal["display", "title", "subtitle", "body", "label", "caption"]
SpaceStep = Literal["xs", "sm", "md", "lg", "xl", "xxl"]
@dataclass(frozen=True)
class LockConfig:
"""Declarative knobs for one :class:`LockWindow` instance.
Each field left as ``None`` is derived from ``mode``; an explicit value
always overrides the preset for that one axis.
Attributes:
mode: Preset bundling the common combination. "soft" = topmost only,
typeable, WM-escapable. "hard" = overrideredirect + global grab +
VT-disable (the production lock for all three apps).
overrideredirect: Force a WM-unmanaged window. None = derive from mode.
Note that per-output placement *requires* this: a window manager
rewrites a managed window's geometry wholesale.
grab: Input grab strategy. None = derive from mode.
disable_vt: Disable Ctrl+Alt+Fn VT switching. None = derive from mode.
grab_retry_ms: Retry interval in ms for a "global" grab that initially
fails. 0 means "try once, then fall back to a local grab". Left
unset (None), a "global" grab retries forever every 200ms.
grab_log_every: Log a warning every N failed retry-forever attempts.
preempt_weaker_holder: SIGTERM a lower-ranked incumbent that is
blocking our grab, instead of retrying against it forever. Only
the *direction* the arbiter's own ranking already sanctions: we
never signal a holder that outranks us. SIGTERM (not SIGKILL) so
the holder's own signal handler runs its normal close() path --
same teardown as a clean dismiss, just triggered externally.
Defaults to False, and must stay opt-in: for an *enforcement*
lock (screen_locker), being preempted means the machine unlocks
with the obligation unmet. Only an app whose own dismissal is
harmless -- or which genuinely outranks every enforcer -- should
turn this on, and only after considering who it can now evict.
app_name: This app's name, used in arbitration logs so a blocked app
can say who is actually holding the screen.
rank: Arbitration priority; higher wins. See the ``RANK_*`` constants
in :mod:`gatelock._arbiter`.
recovery_tick_ms: Interval of the full re-assertion pass.
detect_drain_ms: Interval of the cheap "did anything change?" drain.
bg: Background color for the lock surfaces.
fg: Primary (near-white) text color.
muted: Secondary/caption text color.
field_bg: Background for "raised" surfaces (entry/spinbox fields,
input wells) -- one step lighter than ``bg``.
accent: The shared brand accent (buttons, primary actions).
success: Positive/on-track status color.
warning: Caution/pending status color.
danger: Negative/error status color.
on_fill: Text/icon color for anything drawn on top of a filled
accent/success/warning/danger surface (e.g. a button's label) --
NOT ``fg``. All four fills sit in the same mid-light band, so
near-white text under-contrasts on every one of them; callers
must pick ``fg`` vs. ``on_fill`` based on the widget's own
background, never hardcode one for all buttons.
font_family: Default font family for lock-window widgets.
focus_ring: Color of the *focused* widget's highlight ring. Defaults to
``accent``, because Tk's own default is black -- invisible against
``bg``. Pass to ``highlightcolor``; note ``highlightbackground`` is
the *unfocused* ring, so setting that one inverts the affordance.
focus_thickness: Ring width in px. Never set 0 on a focusable widget.
type_display, type_title, type_subtitle, type_body, type_label,
type_caption: The type scale, in **pixels**. Do not pass these to
Tk directly -- use :meth:`font`, which applies the sign convention.
space_xs, space_sm, space_md, space_lg, space_xl, space_xxl: The 4px
spacing scale, in pixels. Use for ``padx``/``pady``/``ipadx``.
All color/font defaults come from the ``unified-design-system`` docs
(``~/utils/unified-design-system/tokens.md``) -- the same palette used by
every one of kuhy's apps, Flutter and web included.
"""
mode: LockMode = "hard"
overrideredirect: bool | None = None
grab: GrabKind | None = None
disable_vt: bool | None = None
grab_retry_ms: int | None = None
grab_log_every: int = 25
preempt_weaker_holder: bool = False
app_name: str = "gatelock"
rank: int = RANK_SCREEN_LOCKER
recovery_tick_ms: int = 1000
detect_drain_ms: int = 100
bg: str = "#211D1B"
fg: str = "#ECEAE9"
muted: str = "#AAA09A"
field_bg: str = "#2B2624"
accent: str = "#B8862E"
success: str = "#8A9A3C"
warning: str = "#E0A63C"
danger: str = "#E2585F"
on_fill: str = "#211D1B"
font_family: str = "Arial"
focus_ring: str = "#B8862E"
focus_thickness: int = 2
# Type scale in PIXELS (unified-design-system tokens.md). Convert via
# font(); a raw positive value handed to Tk means *points*, ~37% bigger.
type_display: int = 32
type_title: int = 24
type_subtitle: int = 20
type_body: int = 16
type_label: int = 14
type_caption: int = 12
# 4px spacing scale, in pixels.
space_xs: int = 4
space_sm: int = 8
space_md: int = 16
space_lg: int = 24
space_xl: int = 32
space_xxl: int = 48
def type_px(self, role: TypeRole = "body") -> int:
"""Return the type-scale size for ``role``, in pixels.
Compacted on short displays -- see :mod:`gatelock._density`. The scale
is authored for 1080p; a 768px panel gets 0.8 of it, because a lock
surface has to fit one screen and cannot scroll its way out of being
too tall.
"""
return _density.scale_type(int(getattr(self, f"type_{role}")))
def space(self, step: SpaceStep = "md") -> int:
"""Return the spacing-scale value for ``step``, in pixels.
Compacted on short displays, exactly like :meth:`type_px`.
"""
return _density.scale_space(int(getattr(self, f"space_{step}")))
def font(
self,
role: TypeRole = "body",
*,
bold: bool = False,
family: str | None = None,
scale: float = 1.0,
) -> tuple[str, int] | tuple[str, int, str]:
"""Return a Tk font tuple for a type-scale role, sized in **pixels**.
Tk encodes the unit in the *sign* of the size: positive means points,
negative means pixels. The design-system scale is in pixels, so passing
e.g. ``type_body`` (16) straight to Tk yields 16 *points* -- about 37%
larger than intended (measured: linespace 26px vs 19px). Inflating
every string by a third is enough on its own to push a layout off a
768px-tall screen, which is exactly what happened to the diet_guard
meal gate. Always build lock-window fonts through this method.
Args:
role: Type-scale role.
bold: Append Tk's ``"bold"`` weight.
family: Override the font family. Defaults to ``font_family``.
scale: Multiplier for display-only emphasis (e.g. an oversized
countdown). Kept explicit so outliers are visible rather than
hidden behind a fresh literal.
Returns:
A Tk font tuple with a negative (pixel) size.
"""
px = max(1, round(self.type_px(role) * scale))
name = family if family is not None else self.font_family
return (name, -px, "bold") if bold else (name, -px)
def focus_kwargs(self) -> dict[str, str | int]:
"""Return widget kwargs that make focus visible on this palette.
``highlightcolor`` is the *focused* ring; ``highlightbackground`` is the
unfocused one. Both are set so the widget shows a subdued edge when
unfocused and the accent ring when focused -- rather than Tk's default
black-on-``bg``, which reads as no ring at all.
"""
return {
"highlightcolor": self.focus_ring,
"highlightbackground": self.bg,
"highlightthickness": self.focus_thickness,
}
def resolved_overrideredirect(self) -> bool:
"""Return the effective overrideredirect setting."""
if self.overrideredirect is not None:
return self.overrideredirect
return self.mode == "hard"
def resolved_grab(self) -> GrabKind:
"""Return the effective grab strategy."""
if self.grab is not None:
return self.grab
return "global" if self.mode == "hard" else "none"
def resolved_disable_vt(self) -> bool:
"""Return whether VT switching should be disabled."""
if self.disable_vt is not None:
return self.disable_vt
return self.mode == "hard"

View File

@ -0,0 +1,51 @@
"""The callback interface an app embedding :class:`~gatelock.LockWindow` fills.
Split out of :mod:`gatelock._window` so the pure *interface* -- what an app
must implement -- can be read without the window mechanics that call it. This
module deliberately imports nothing from the runtime half, so an app can type
against the protocol without pulling in Tk window machinery.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Protocol
if TYPE_CHECKING:
import tkinter as tk
from gatelock._surfaces import SurfaceInfo
class LockWindowHooks(Protocol):
"""Callbacks :class:`LockWindow` invokes; the embedding app supplies all."""
def build_surface(self, parent: tk.Misc, surface: SurfaceInfo) -> None:
"""Build this app's widgets inside ``parent``, for one output.
Called once per live output, and again whenever an output comes back.
Tk variables should stay mastered on the root so every surface shows
the same state, and every surface's submit path should call the same
handler -- solving the lock on any monitor dismisses all of them.
"""
def teardown_surface(self, surface: SurfaceInfo) -> None:
"""Forget per-surface state; that output went dark and is closing."""
def on_focus_ready(self, surface: SurfaceInfo | None) -> None:
"""Called once the lock is mapped and (if applicable) grabbed.
Args:
surface: The surface that took initial focus, or None when no
output is live and there is therefore nothing to focus.
"""
def on_callback_error(self) -> None:
"""Called when a Tk callback raised (see :class:`~gatelock.GateRoot`)."""
def on_close(self) -> None:
"""Called once, from :meth:`LockWindow.close`, before VT is restored.
Runs on every exit path -- normal dismiss, SIGTERM, SIGINT -- not just
a clean close, so app-specific teardown (restoring hardware state,
etc.) can't be skipped by killing the process.
"""

View File

@ -0,0 +1,118 @@
"""Diagnosing and clearing a blocked global input grab.
Split out of :mod:`gatelock._window`, which owns the *acquisition* loop; this
module owns what happens when that loop keeps failing -- naming the holder in
the log, and standing a weaker one down.
Both are free functions rather than methods because neither touches the Tk
window: they need only the arbiter, the config knobs and the set of pids
already signalled. That keeps the retry path in one file and the arbitration
policy in another, and lets this half be tested without a display.
"""
from __future__ import annotations
import logging
import os
import signal
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from gatelock._arbiter import Arbiter, Claim
from gatelock._config import LockConfig
_logger = logging.getLogger(__name__)
def log_grab_blocked(
attempt: int,
*,
arbiter: Arbiter | None,
config: LockConfig,
preempted_pids: set[int],
) -> None:
"""Say who is actually holding the grab, rather than guessing.
v0.1.1 always blamed "a fullscreen game". On 2026-07-25 the holder was
the other locker, and that guess sent the diagnosis in the wrong
direction for the length of the outage.
A holder that outranks us is left alone entirely -- retrying is the
correct behavior there, matching :func:`gatelock.wait_for_turn`'s own
rule for an app that has not armed yet. A *weaker* holder is preempted
by :func:`maybe_preempt`, once per pid, rather than left to block us for
as long as it takes to finish on its own (diet_guard held the grab for
~3 minutes against a higher-ranked screen_locker on 2026-08-21).
Args:
attempt: 1-based attempt counter, reported in the log line.
arbiter: This app's arbiter, or None when arbitration is disabled.
config: The window's configuration, consulted for the preempt opt-in.
preempted_pids: Pids already signalled; mutated by the preempt path.
"""
holder = arbiter.describe_holder() if arbiter else None
if holder is None:
_logger.warning(
"global grab still blocked after %d attempts; no gatelock app "
"holds it -- likely another X client (e.g. a fullscreen game)",
attempt,
)
return
_logger.warning(
"global grab still blocked after %d attempts; held by gatelock app "
"%r (rank %d, pid %d) since %s",
attempt,
holder.app,
holder.rank,
holder.pid,
holder.started,
)
maybe_preempt(holder, arbiter=arbiter, config=config, preempted_pids=preempted_pids)
def maybe_preempt(
holder: Claim,
*,
arbiter: Arbiter | None,
config: LockConfig,
preempted_pids: set[int],
) -> None:
"""SIGTERM a weaker holder once, so it stands down instead of blocking.
SIGTERM (not SIGKILL): the holder's own signal handler
(``LockWindow._install_signal_handlers``) raises ``SystemExit(0)``,
which unwinds through its ``run()``'s ``finally`` into its own
``close()`` -- the identical teardown a clean dismiss gets (VT
restored, arbiter claim released, app-specific ``on_close`` hook
run), just triggered externally instead of by the user.
Args:
holder: The claim currently holding the grab.
arbiter: This app's arbiter, or None when arbitration is disabled.
config: The window's configuration; ``preempt_weaker_holder`` gates
this entirely and defaults to off.
preempted_pids: Pids already signalled, so each is signalled once.
"""
if not config.preempt_weaker_holder or arbiter is None:
return
if holder.rank >= arbiter.claim.rank:
return
if holder.pid in preempted_pids:
return
preempted_pids.add(holder.pid)
_logger.warning(
"preempting weaker holder %r (rank %d, pid %d) so rank %d can arm",
holder.app,
holder.rank,
holder.pid,
arbiter.claim.rank,
)
try:
os.kill(holder.pid, signal.SIGTERM)
except ProcessLookupError:
_logger.info(
"holder pid %d was already gone by the time we signalled it",
holder.pid,
)
except OSError:
_logger.exception("could not signal holder pid %d", holder.pid)

View File

@ -1,74 +1,41 @@
"""A keyboard-scrollable, focus-following viewport for lock-surface content.
Lock surfaces cannot solve "content taller than the screen" the obvious way.
A scrollable dialog would be a second ``Toplevel``, and on an
override-redirect lock surface a second toplevel steals the Tk grab, which the
recovery tick then kills a second later -- the 2026-07-26 failure where a
frozen sport selector logged a walk as table tennis. So the viewport has to
live inside the surface's own widget tree, which is what this provides.
Build it inside a lock surface, pack widgets into :attr:`content`, then call
:meth:`ScrollableSurface.finalize`. Content that fits cannot scroll at all;
content that overflows scrolls by key, click or wheel -- never on its own.
Three defects this exists to prevent, all of them Tk defaults rather than
oversights in any one app:
Scrolling is the fallback, not the design: a lock surface is supposed to fit
its screen, and :meth:`ScrollableSurface.finalize` logs an overflow at
``warning`` so it gets fixed. See ``docs/scrollable-viewport.md`` for the
three Tk defaults this exists to prevent and the failures behind each.
1. **Centered content clips symmetrically.** A ``place``-centered frame takes
its *requested* size, so when it is too tall the parent shears equal
amounts off the top *and* the bottom -- losing the header and the submit
button together, with no scrollbar and no hint anything is missing. This
top-anchors content inside a scroll region instead.
2. **A Canvas viewport is not keyboard-scrollable.** ``tk.Canvas`` has no
class-level key bindings at all, so ``::tk::FocusOK`` rejects it as a focus
stop and the only way to move the view is dragging the scrollbar thumb with
a pointer. This makes the canvas focusable and binds PageUp/PageDown,
Home/End and arrows.
3. **Focus walks into invisible widgets.** Canvas clipping does not *unmap* a
child, so every scrolled-out-of-view field stays ``winfo viewable`` and
stays in the tab chain, while Tk never scrolls to follow focus. Tabbing
therefore lands on fields the user cannot see and cannot bring into view.
:meth:`ScrollableSurface.scroll_into_view` fixes that, but only for focus
the *user* moved.
Wheel scrolling is bound too, but as an addition -- never as the only path.
**Scrolling is the fallback, not the design.** A lock screen is supposed to
fit its screen; content that overflows is a layout defect, and :meth:`finalize`
logs it at ``warning`` so it gets fixed rather than lived with. While the
content fits -- the normal case -- the scroll region is pinned to the viewport
and the scrollbar is hidden, so the view cannot move at all. When it does
overflow, the view still only moves in response to a keypress, a click or the
wheel: an earlier version followed *programmatic* focus too, and since the apps
re-focus a widget on every repaint, the screen scrolled itself to mid-content
and back while the user was doing nothing (reported 2026-08-03, 1366x768).
Collaborators: :mod:`gatelock._scrollfit` measures and lays out,
:mod:`gatelock._scrollkeys` binds the keys and wheel, and
:mod:`gatelock._userintent` decides whether a focus move was the user's.
"""
from __future__ import annotations
import logging
import time
import tkinter as tk
from typing import TYPE_CHECKING
import weakref
from gatelock._scrollfit import (
FitTarget,
apply_fit_state,
content_span,
report_overflow,
request_content_size,
)
from gatelock._scrollkeys import bind_scroll_keys, track_focus
from gatelock._userintent import UserIntentTracker, viewport_targets
if TYPE_CHECKING:
from gatelock._window import LockConfig
_logger = logging.getLogger(__name__)
# Tk reports wheel notches as Button-4/5 on X11 rather than <MouseWheel>.
_WHEEL_UP = "<Button-4>"
_WHEEL_DOWN = "<Button-5>"
# Scroll step in "units" for arrow keys; pages use the viewport height.
_ARROW_UNITS = 3
# Extra px kept visible around a widget scrolled into view, so a focused
# field never sits flush against the viewport edge.
_FOCUS_MARGIN_PX = 12
# How long a keypress or click keeps ownership of the viewport. Focus that
# arrives within this window is treated as the user's own navigation (Tab,
# clicking a field, a button press that opens the next screen) and may scroll;
# focus set outside it is the app's own doing and must not move anything.
_USER_INPUT_WINDOW_S = 0.25
# Tk reports 1px for a widget it has not laid out yet. Treating that as a real
# viewport height would report every not-yet-mapped surface as overflowing.
_UNMAPPED_VIEWPORT_PX = 1
class ScrollableSurface:
@ -159,11 +126,16 @@ class ScrollableSurface:
# binding on `content` alone would miss every Tab.
self.content.bind("<FocusIn>", self._on_descendant_focus, add="+")
self._focus_bound: weakref.WeakSet[tk.Misc] = weakref.WeakSet()
self._last_user_input = 0.0
self._clicked: tk.Misc | None = None
self._overflowing: bool | None = None
self._bind_scroll_keys()
self._bind_user_input()
self._intent = UserIntentTracker()
self._fit = FitTarget(
canvas=self.canvas,
content=self.content,
content_id=self._content_id,
scrollbar=self._scrollbar,
center_when_fits=self._center_when_fits,
)
bind_scroll_keys(self.canvas, self.content)
self._intent.bind(viewport_targets(self.canvas, self.content))
def _on_content_resize(self, _event: tk.Event) -> None:
"""Keep the scroll region matched to the content's real size."""
@ -181,193 +153,9 @@ class ScrollableSurface:
def _apply_fit_state(self) -> None:
"""Switch between "fits" and "overflows" layout.
Fitting is the normal, intended state: the scroll region is pinned to
the viewport so *nothing* can scroll, the content is centred, and the
scrollbar is taken down because there is nothing for it to do.
Scrolling only exists as the fallback for content that genuinely does
not fit, and that is a defect worth reporting (see :meth:`finalize`),
not a layout mode to design for.
Pinning the region is also what makes centring survive. It used to be
cancelled: content was centred by moving the canvas *item* down, which
moved the scroll region's top edge down with it, and the reset in
:meth:`finalize` then scrolled to that top edge -- putting the content
back flush against the screen's top edge on every repaint.
Delegates to :func:`gatelock._scrollfit.apply_fit_state`.
"""
view_h = self.canvas.winfo_height()
view_w = self.canvas.winfo_width()
wanted_h = self.content.winfo_reqheight()
overflowing = wanted_h > view_h
if overflowing:
self.canvas.coords(self._content_id, view_w / 2, 0)
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
else:
top = max(0, (view_h - wanted_h) // 2) if self._center_when_fits else 0
self.canvas.coords(self._content_id, view_w / 2, top)
# Region == the *scrollable* area, so yview is exactly (0.0, 1.0)
# and nothing -- key, wheel or scrollbar -- can move it. The focus
# ring is drawn outside that area, so it has to come off both
# dimensions or the region is a hair taller than the viewport and
# a page-down still nudges the screen.
inset = 2 * self._border_px()
self.canvas.configure(
scrollregion=(0, 0, max(1, view_w - inset), max(1, view_h - inset))
)
if overflowing != self._overflowing:
self._overflowing = overflowing
self._show_scrollbar(visible=overflowing)
def _border_px(self) -> int:
"""Width of the canvas's own edge: focus ring plus border."""
return int(self.canvas.cget("highlightthickness")) + int(
self.canvas.cget("borderwidth")
)
def _show_scrollbar(self, *, visible: bool) -> None:
"""Show the scrollbar only while there is something to scroll."""
if self._scrollbar is None:
return
if visible:
# Re-packed before the canvas would put it on the wrong side, so
# the canvas is re-packed after it to keep left/right ordering.
self._scrollbar.pack(side="right", fill="y")
self.canvas.pack_forget()
self.canvas.pack(side="left", fill="both", expand=True)
else:
self._scrollbar.pack_forget()
def _bind_user_input(self) -> None:
"""Record when the user last pressed a key or a mouse button.
Focus-following scrolling is gated on this: the app focuses widgets
programmatically on every repaint (and gatelock re-asserts focus from
its recovery tick), and a viewport that follows *those* moves the
screen under a user who has touched nothing.
"""
targets: list[tk.Misc] = [self.canvas, self.content]
try:
targets.append(self.canvas.winfo_toplevel())
except (tk.TclError, KeyError, AttributeError):
_logger.warning(
"no toplevel for scroll viewport; user-input tracking is "
"bound to the viewport only, so focus-following scrolling "
"stays off unless the viewport itself saw the event"
)
for target in targets:
target.bind("<Key>", self._note_key, add="+")
target.bind("<Button>", self._note_click, add="+")
def _note_key(self, _event: tk.Event | None = None) -> None:
"""Timestamp a keypress -- Tab and arrows move focus deliberately."""
self._last_user_input = time.monotonic()
self._clicked = None
def _note_click(self, event: tk.Event | None = None) -> None:
"""Timestamp a click and remember what was clicked."""
self._last_user_input = time.monotonic()
self._clicked = getattr(event, "widget", None)
def _focus_is_user_driven(self, focused: tk.Misc) -> bool:
"""Whether the user, not the app, is responsible for this focus move.
Time alone is not enough. Clicking "Log Manual Workout" is a user
event, but the focus that follows belongs to the *next screen*, which
the app focuses itself while building -- scrolling there is the same
unasked-for movement as scrolling on a repaint. So a click only counts
when focus landed on the thing that was clicked; a keypress always
counts, because Tab and the arrows are how a user moves focus without
a pointer.
"""
if time.monotonic() - self._last_user_input > _USER_INPUT_WINDOW_S:
return False
if self._clicked is None:
return True
return self._clicked is focused
def _bind_scroll_keys(self) -> None:
"""Bind keyboard and wheel scrolling.
PageUp/PageDown/Home/End go on the *toplevel* where possible: in a
fullscreen lock those keys have no competing meaning, and binding there
means they work wherever focus currently sits rather than only when the
canvas holds it. Arrows bind to the canvas only -- bound globally they
would fight Listbox, Spinbox and Entry navigation.
"""
paging = (
("<Prior>", self._page_up),
("<Next>", self._page_down),
("<Home>", self._scroll_home),
("<End>", self._scroll_end),
)
target: tk.Misc = self.canvas
try:
target = self.canvas.winfo_toplevel()
except (tk.TclError, KeyError, AttributeError):
# Reachable when the widget tree's root is not a real toplevel --
# notably under tests that mock the Tk root. Degrade to binding on
# the canvas rather than failing to build the viewport at all:
# paging then works while the viewport has focus, which is strictly
# better than no keyboard scrolling. Logged rather than swallowed
# so a production occurrence is visible.
_logger.warning(
"no toplevel for scroll viewport; paging keys bound to the "
"canvas only, so they work only while it holds focus"
)
for seq, handler in paging:
target.bind(seq, handler, add="+")
self.canvas.bind("<Up>", self._line_up, add="+")
self.canvas.bind("<Down>", self._line_down, add="+")
for seq, handler in (
(_WHEEL_UP, self._line_up),
(_WHEEL_DOWN, self._line_down),
):
self.canvas.bind(seq, handler, add="+")
self.content.bind(seq, handler, add="+")
def _page_up(self, _event: tk.Event | None = None) -> None:
self.canvas.yview_scroll(-1, "pages")
def _page_down(self, _event: tk.Event | None = None) -> None:
self.canvas.yview_scroll(1, "pages")
def _line_up(self, _event: tk.Event | None = None) -> None:
self.canvas.yview_scroll(-_ARROW_UNITS, "units")
def _line_down(self, _event: tk.Event | None = None) -> None:
self.canvas.yview_scroll(_ARROW_UNITS, "units")
def _scroll_home(self, _event: tk.Event | None = None) -> None:
self.canvas.yview_moveto(0.0)
def _scroll_end(self, _event: tk.Event | None = None) -> None:
self.canvas.yview_moveto(1.0)
def _track_focus(self, parent: tk.Misc) -> None:
"""Bind <FocusIn> and the wheel on every descendant, each exactly once.
A repaint destroys and rebuilds the widgets, so this re-runs per
screen; the WeakSet is what keeps a second :meth:`finalize` on the
*same* widgets from stacking a second handler on each of them, and
drops entries as the widgets are destroyed.
The wheel has to be bound per descendant because Tk dispatches through
*bindtags*, not the parent chain: a child's tags are ``(itself, its
class, the toplevel, "all")``, so an event over a Label never reaches
a binding on ``content``. Content that fills its viewport covers that
frame completely, which means wheel-over-text -- the only way anyone
actually scrolls with a mouse -- would do nothing. The donor this
replaced reached for ``bind_all`` instead, which works but installs
the handler on *every* widget in the application, including other
windows' scroll regions.
"""
for child in parent.winfo_children():
if child not in self._focus_bound:
child.bind("<FocusIn>", self._on_descendant_focus, add="+")
child.bind(_WHEEL_UP, self._line_up, add="+")
child.bind(_WHEEL_DOWN, self._line_down, add="+")
self._focus_bound.add(child)
self._track_focus(child)
apply_fit_state(self._fit)
def _on_descendant_focus(self, event: tk.Event) -> None:
"""Reveal a widget the *user* just tabbed or clicked onto.
@ -389,7 +177,7 @@ class ScrollableSurface:
true for every surface behind the one the user is looking at.)
"""
widget = event.widget
if widget.winfo_children() or not self._focus_is_user_driven(widget):
if widget.winfo_children() or not self._intent.focus_is_user_driven(widget):
return
self.scroll_into_view(widget)
@ -400,7 +188,7 @@ class ScrollableSurface:
out yet (a zero height means Tk has not placed it).
"""
self.canvas.update_idletasks()
span = self._content_span()
span = content_span(self.canvas)
view_h = self.canvas.winfo_height()
if span <= view_h or widget.winfo_height() <= 0:
return
@ -416,11 +204,6 @@ class ScrollableSurface:
return
self.canvas.yview_moveto(target / span)
def _content_span(self) -> int:
"""Return the scrollable content height in px."""
box = self.canvas.bbox("all")
return (box[3] - box[1]) if box else 0
def finalize(self) -> None:
"""Settle geometry for freshly built content.
@ -439,48 +222,13 @@ class ScrollableSurface:
each consuming app asserts the same property before it ships.
"""
self.content.update_idletasks()
self._track_focus(self.content)
self._request_content_size()
track_focus(
self.content, self.canvas, self._on_descendant_focus, self._focus_bound
)
request_content_size(self._fit)
self._apply_fit_state()
self.canvas.yview_moveto(0.0)
wanted_h = self.content.winfo_reqheight()
view_h = self.canvas.winfo_height()
# A viewport Tk has not laid out yet reports 1px, which is not an
# overflow -- reporting it would cry wolf on every startup and teach
# the reader to ignore the one message that matters.
if view_h > _UNMAPPED_VIEWPORT_PX and wanted_h > view_h:
_logger.warning(
"lock content overflows its surface: %dpx of content in a "
"%dpx viewport (%dpx off-screen); it is reachable only by "
"scrolling, which no screen should require",
wanted_h,
view_h,
wanted_h - view_h,
)
def _request_content_size(self) -> None:
"""Ask for a canvas big enough for the content, clamped to the screen.
A ``Canvas`` holds its content in a canvas *item*, not as a
geometry-managed child, so it never propagates the content's requested
size into its own. A toplevel told to size itself (``geometry("")``)
therefore has nothing to grow to and stays at its minimum -- which is
how a 862px-wide button row ended up sheared inside a 700px window even
after a viewport was added.
Requesting the content's size fixes that where there is room, and the
clamp keeps a window from growing off a small display; anything still
too big scrolls instead of clipping. On a lock surface the container is
``place``d at ``relwidth/relheight=1``, which overrides this request --
correctly, since there the surface size is the screen.
"""
wanted_w = self.content.winfo_reqwidth()
wanted_h = self.content.winfo_reqheight()
bar = self._scrollbar.winfo_reqwidth() if self._scrollbar else 0
self.canvas.configure(
width=max(1, min(wanted_w, self.canvas.winfo_screenwidth() - bar)),
height=max(1, min(wanted_h, self.canvas.winfo_screenheight())),
)
report_overflow(self._fit)
def fits(self) -> bool:
"""Whether the content currently fits without scrolling.

View File

@ -0,0 +1,183 @@
"""Measuring a scroll viewport's content and switching its layout to match.
Split out of :mod:`gatelock._scrollable`, which keeps the widget wiring, focus
tracking and the public surface. Everything here answers one question -- does
the content fit? -- and applies the consequences: pinning or releasing the
scroll region, centring, showing or hiding the scrollbar, and asking for a
canvas big enough to avoid the problem in the first place.
Fitting is the normal, intended state. Scrolling exists only as the fallback
for content that genuinely does not fit, and that is a layout defect worth
reporting, not a mode to design for.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import tkinter as tk
_logger = logging.getLogger(__name__)
# Tk reports 1px for a widget it has not laid out yet. Treating that as a real
# viewport height would report every not-yet-mapped surface as overflowing.
_UNMAPPED_VIEWPORT_PX = 1
@dataclass
class FitTarget:
"""The viewport being measured, and the layout knobs that depend on it.
Attributes:
canvas: The scroll viewport.
content: The frame held inside it as a canvas item.
content_id: The canvas item id of ``content``, whose coords are moved
to centre the content.
scrollbar: The scrollbar to show and hide, or None when the surface
was built without one.
center_when_fits: Whether content that fits is centred vertically
rather than pinned to the top.
overflowing: Last known overflow state, or None before the first
measurement. Kept so the scrollbar is only re-packed on a genuine
change rather than on every resize event.
"""
canvas: tk.Canvas
content: tk.Frame
content_id: int
scrollbar: tk.Scrollbar | None
center_when_fits: bool
overflowing: bool | None = field(default=None)
def border_px(canvas: tk.Canvas) -> int:
"""Width of the canvas's own edge: focus ring plus border."""
return int(canvas.cget("highlightthickness")) + int(canvas.cget("borderwidth"))
def content_span(canvas: tk.Canvas) -> int:
"""Return the scrollable content height in px."""
box = canvas.bbox("all")
return (box[3] - box[1]) if box else 0
def show_scrollbar(target: FitTarget, *, visible: bool) -> None:
"""Show the scrollbar only while there is something to scroll.
Args:
target: The viewport whose scrollbar is being toggled.
visible: Whether the scrollbar should be packed.
"""
if target.scrollbar is None:
return
if visible:
# Re-packed before the canvas would put it on the wrong side, so
# the canvas is re-packed after it to keep left/right ordering.
target.scrollbar.pack(side="right", fill="y")
target.canvas.pack_forget()
target.canvas.pack(side="left", fill="both", expand=True)
else:
target.scrollbar.pack_forget()
def apply_fit_state(target: FitTarget) -> None:
"""Switch between "fits" and "overflows" layout.
Fitting is the normal, intended state: the scroll region is pinned to
the viewport so *nothing* can scroll, the content is centred, and the
scrollbar is taken down because there is nothing for it to do.
Scrolling only exists as the fallback for content that genuinely does
not fit, and that is a defect worth reporting (see
:meth:`gatelock._scrollable.ScrollableSurface.finalize`), not a layout
mode to design for.
Pinning the region is also what makes centring survive. It used to be
cancelled: content was centred by moving the canvas *item* down, which
moved the scroll region's top edge down with it, and the reset in
``finalize`` then scrolled to that top edge -- putting the content
back flush against the screen's top edge on every repaint.
Args:
target: The viewport to measure and re-lay out.
"""
view_h = target.canvas.winfo_height()
view_w = target.canvas.winfo_width()
wanted_h = target.content.winfo_reqheight()
overflowing = wanted_h > view_h
if overflowing:
target.canvas.coords(target.content_id, view_w / 2, 0)
target.canvas.configure(scrollregion=target.canvas.bbox("all"))
else:
top = max(0, (view_h - wanted_h) // 2) if target.center_when_fits else 0
target.canvas.coords(target.content_id, view_w / 2, top)
# Region == the *scrollable* area, so yview is exactly (0.0, 1.0)
# and nothing -- key, wheel or scrollbar -- can move it. The focus
# ring is drawn outside that area, so it has to come off both
# dimensions or the region is a hair taller than the viewport and
# a page-down still nudges the screen.
inset = 2 * border_px(target.canvas)
target.canvas.configure(
scrollregion=(0, 0, max(1, view_w - inset), max(1, view_h - inset))
)
if overflowing != target.overflowing:
target.overflowing = overflowing
show_scrollbar(target, visible=overflowing)
def request_content_size(target: FitTarget) -> None:
"""Ask for a canvas big enough for the content, clamped to the screen.
A ``Canvas`` holds its content in a canvas *item*, not as a
geometry-managed child, so it never propagates the content's requested
size into its own. A toplevel told to size itself (``geometry("")``)
therefore has nothing to grow to and stays at its minimum -- which is
how a 862px-wide button row ended up sheared inside a 700px window even
after a viewport was added.
Requesting the content's size fixes that where there is room, and the
clamp keeps a window from growing off a small display; anything still
too big scrolls instead of clipping. On a lock surface the container is
``place``d at ``relwidth/relheight=1``, which overrides this request --
correctly, since there the surface size is the screen.
Args:
target: The viewport to resize.
"""
wanted_w = target.content.winfo_reqwidth()
wanted_h = target.content.winfo_reqheight()
bar = target.scrollbar.winfo_reqwidth() if target.scrollbar else 0
target.canvas.configure(
width=max(1, min(wanted_w, target.canvas.winfo_screenwidth() - bar)),
height=max(1, min(wanted_h, target.canvas.winfo_screenheight())),
)
def report_overflow(target: FitTarget) -> None:
"""Log a warning when the content does not fit its viewport.
The surface is supposed to fit its screen, so needing a scrollbar is a
layout defect to fix, not a mode to live in.
``scripts/verify_screen_fits.py`` in each consuming app asserts the same
property before it ships.
Args:
target: The viewport to measure.
"""
wanted_h = target.content.winfo_reqheight()
view_h = target.canvas.winfo_height()
# A viewport Tk has not laid out yet reports 1px, which is not an
# overflow -- reporting it would cry wolf on every startup and teach
# the reader to ignore the one message that matters.
if view_h > _UNMAPPED_VIEWPORT_PX and wanted_h > view_h:
_logger.warning(
"lock content overflows its surface: %dpx of content in a "
"%dpx viewport (%dpx off-screen); it is reachable only by "
"scrolling, which no screen should require",
wanted_h,
view_h,
wanted_h - view_h,
)

View File

@ -0,0 +1,180 @@
"""Keyboard and wheel scrolling for a :class:`~gatelock._scrollable.ScrollableSurface`.
Split out of :mod:`gatelock._scrollable`, which keeps the viewport's geometry
and fit logic. Everything here is about *driving* an existing viewport: the
key and wheel bindings, and the six one-line scroll commands they call.
The commands take the canvas directly rather than the surface, so this module
knows nothing about fit state, focus tracking or scrollbars.
"""
from __future__ import annotations
import logging
import tkinter as tk
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable, MutableSet
_logger = logging.getLogger(__name__)
# Tk reports wheel notches as Button-4/5 on X11 rather than <MouseWheel>.
_WHEEL_UP = "<Button-4>"
_WHEEL_DOWN = "<Button-5>"
# Lines moved per arrow keypress / wheel notch. Three matches the scroll step
# of a typical toolkit list and keeps a long form from crawling.
_ARROW_UNITS = 3
def page_up(canvas: tk.Canvas) -> None:
"""Scroll up one viewport height."""
canvas.yview_scroll(-1, "pages")
def page_down(canvas: tk.Canvas) -> None:
"""Scroll down one viewport height."""
canvas.yview_scroll(1, "pages")
def line_up(canvas: tk.Canvas) -> None:
"""Scroll up one arrow/wheel step."""
canvas.yview_scroll(-_ARROW_UNITS, "units")
def line_down(canvas: tk.Canvas) -> None:
"""Scroll down one arrow/wheel step."""
canvas.yview_scroll(_ARROW_UNITS, "units")
def scroll_home(canvas: tk.Canvas) -> None:
"""Jump to the top of the content."""
canvas.yview_moveto(0.0)
def scroll_end(canvas: tk.Canvas) -> None:
"""Jump to the bottom of the content."""
canvas.yview_moveto(1.0)
def bind_scroll_keys(canvas: tk.Canvas, content: tk.Misc) -> None:
"""Bind keyboard and wheel scrolling.
PageUp/PageDown/Home/End go on the *toplevel* where possible: in a
fullscreen lock those keys have no competing meaning, and binding there
means they work wherever focus currently sits rather than only when the
canvas holds it. Arrows bind to the canvas only -- bound globally they
would fight Listbox, Spinbox and Entry navigation.
Args:
canvas: The scroll viewport.
content: The frame scrolled inside it, bound for the wheel so a notch
over the content scrolls rather than falling through.
"""
def on_page_up(_event: tk.Event | None = None) -> None:
page_up(canvas)
def on_page_down(_event: tk.Event | None = None) -> None:
page_down(canvas)
def on_home(_event: tk.Event | None = None) -> None:
scroll_home(canvas)
def on_end(_event: tk.Event | None = None) -> None:
scroll_end(canvas)
def on_line_up(_event: tk.Event | None = None) -> None:
line_up(canvas)
def on_line_down(_event: tk.Event | None = None) -> None:
line_down(canvas)
paging = (
("<Prior>", on_page_up),
("<Next>", on_page_down),
("<Home>", on_home),
("<End>", on_end),
)
target: tk.Misc = canvas
try:
target = canvas.winfo_toplevel()
except (tk.TclError, KeyError, AttributeError):
# Reachable when the widget tree's root is not a real toplevel --
# notably under tests that mock the Tk root. Degrade to binding on
# the canvas rather than failing to build the viewport at all:
# paging then works while the viewport has focus, which is strictly
# better than no keyboard scrolling. Logged rather than swallowed
# so a production occurrence is visible.
_logger.warning(
"no toplevel for scroll viewport; paging keys bound to the "
"canvas only, so they work only while it holds focus"
)
for seq, handler in paging:
target.bind(seq, handler, add="+")
canvas.bind("<Up>", on_line_up, add="+")
canvas.bind("<Down>", on_line_down, add="+")
for seq, handler in ((_WHEEL_UP, on_line_up), (_WHEEL_DOWN, on_line_down)):
canvas.bind(seq, handler, add="+")
content.bind(seq, handler, add="+")
def bind_wheel(widget: tk.Misc, canvas: tk.Canvas) -> None:
"""Bind wheel scrolling on one descendant of a viewport.
A widget that handles its own events (a Listbox, an Entry) otherwise
swallows the notch, so the wheel appears dead over exactly the parts of a
form the user is most likely to be pointing at.
Args:
widget: The descendant to bind on.
canvas: The viewport the notch should scroll.
"""
def on_line_up(_event: tk.Event | None = None) -> None:
line_up(canvas)
def on_line_down(_event: tk.Event | None = None) -> None:
line_down(canvas)
widget.bind(_WHEEL_UP, on_line_up, add="+")
widget.bind(_WHEEL_DOWN, on_line_down, add="+")
def track_focus(
parent: tk.Misc,
canvas: tk.Canvas,
on_focus: Callable[[tk.Event], None],
bound: MutableSet[tk.Misc],
) -> None:
"""Bind <FocusIn> and the wheel on every descendant, each exactly once.
A repaint destroys and rebuilds the widgets, so this re-runs per screen;
``bound`` is what keeps a second ``finalize`` on the *same* widgets from
stacking a second handler on each of them.
The wheel has to be bound per descendant because Tk dispatches through
*bindtags*, not the parent chain: a child's tags are ``(itself, its
class, the toplevel, "all")``, so an event over a Label never reaches
a binding on ``content``. Content that fills its viewport covers that
frame completely, which means wheel-over-text -- the only way anyone
actually scrolls with a mouse -- would do nothing. The donor this
replaced reached for ``bind_all`` instead, which works but installs
the handler on *every* widget in the application, including other
windows' scroll regions.
Args:
parent: Widget whose descendants are bound, recursively.
canvas: The viewport the wheel should scroll.
on_focus: Handler bound to each descendant's ``<FocusIn>``.
bound: Widgets already bound; a WeakSet, so entries drop as widgets
are destroyed. Mutated in place.
"""
for child in parent.winfo_children():
if child not in bound:
child.bind("<FocusIn>", on_focus, add="+")
bind_wheel(child, canvas)
bound.add(child)
track_focus(child, canvas, on_focus, bound)

View File

@ -0,0 +1,106 @@
"""Deciding whether a focus change was driven by the user or by the app.
Split out of :mod:`gatelock._scrollable`, which owns the viewport itself.
Focus-following scrolling has to answer one question -- "did the user just
do something?" -- and getting it wrong is what moves the screen under
someone who has touched nothing.
The tracker owns only the two facts needed to answer it, so the viewport
does not have to carry input bookkeeping alongside its geometry.
"""
from __future__ import annotations
import logging
import time
import tkinter as tk
_logger = logging.getLogger(__name__)
# How long after a keypress or click a focus change still counts as the
# user's doing. Long enough to cover the focus that follows an event,
# short enough not to adopt the next repaint.
_USER_INPUT_WINDOW_S = 0.25
class UserIntentTracker:
"""Records recent user input so focus moves can be attributed to it."""
def __init__(self) -> None:
"""Start with no recorded input, so nothing counts as user-driven."""
self._last_user_input = 0.0
self._clicked: tk.Misc | None = None
def bind(self, targets: list[tk.Misc]) -> None:
"""Record when the user last pressed a key or a mouse button.
Focus-following scrolling is gated on this: the app focuses widgets
programmatically on every repaint (and gatelock re-asserts focus from
its recovery tick), and a viewport that follows *those* moves the
screen under a user who has touched nothing.
Args:
targets: Widgets to bind on. Bindings are added (``add="+"``) so
they never displace the app's own handlers.
"""
for target in targets:
target.bind("<Key>", self.note_key, add="+")
target.bind("<Button>", self.note_click, add="+")
def note_key(self, _event: tk.Event | None = None) -> None:
"""Timestamp a keypress -- Tab and arrows move focus deliberately."""
self._last_user_input = time.monotonic()
self._clicked = None
def note_click(self, event: tk.Event | None = None) -> None:
"""Timestamp a click and remember what was clicked."""
self._last_user_input = time.monotonic()
self._clicked = getattr(event, "widget", None)
def focus_is_user_driven(self, focused: tk.Misc) -> bool:
"""Whether the user, not the app, is responsible for this focus move.
Time alone is not enough. Clicking "Log Manual Workout" is a user
event, but the focus that follows belongs to the *next screen*, which
the app focuses itself while building -- scrolling there is the same
unasked-for movement as scrolling on a repaint. So a click only counts
when focus landed on the thing that was clicked; a keypress always
counts, because Tab and the arrows are how a user moves focus without
a pointer.
Args:
focused: The widget that just took focus.
Returns:
True when the focus move should be followed by the viewport.
"""
if time.monotonic() - self._last_user_input > _USER_INPUT_WINDOW_S:
return False
if self._clicked is None:
return True
return self._clicked is focused
def viewport_targets(canvas: tk.Misc, content: tk.Misc) -> list[tk.Misc]:
"""The widgets a viewport should watch for user input.
The toplevel is included when it can be reached, so input anywhere in the
lock counts; without it, only events on the viewport itself do.
Args:
canvas: The scroll viewport.
content: The frame scrolled inside it.
Returns:
The bind targets, most-specific first.
"""
targets: list[tk.Misc] = [canvas, content]
try:
targets.append(canvas.winfo_toplevel())
except (tk.TclError, KeyError, AttributeError):
_logger.warning(
"no toplevel for scroll viewport; user-input tracking is "
"bound to the viewport only, so focus-following scrolling "
"stays off unless the viewport itself saw the event"
)
return targets

View File

@ -26,271 +26,49 @@ from __future__ import annotations
import atexit
import contextlib
from dataclasses import dataclass
import logging
import os
import signal
import tkinter as tk
from typing import TYPE_CHECKING, Literal, Protocol
from typing import TYPE_CHECKING
from gatelock import _density
from gatelock._arbiter import RANK_SCREEN_LOCKER
from gatelock import _arming, _preempt
from gatelock._config import (
GrabKind,
LockConfig,
LockMode,
SpaceStep,
TypeRole,
)
from gatelock._detect import OutputChangeDetector
from gatelock._hooks import LockWindowHooks
from gatelock._outputs import OutputEnumerator
from gatelock._recovery import RecoveryCollaborators, RecoveryLoop
from gatelock._surfaces import SurfaceSet, needs_backdrop_root
from gatelock._vt import disable_vt_switching, restore_vt_switching
from gatelock._surfaces import SurfaceSet
from gatelock._vt import restore_vt_switching
if TYPE_CHECKING:
from types import FrameType
from gatelock._arbiter import Arbiter, Claim
from gatelock._surfaces import SurfaceInfo
from gatelock._arbiter import Arbiter
_logger = logging.getLogger(__name__)
GrabKind = Literal["none", "local", "global"]
LockMode = Literal["soft", "hard"]
TypeRole = Literal["display", "title", "subtitle", "body", "label", "caption"]
SpaceStep = Literal["xs", "sm", "md", "lg", "xl", "xxl"]
# Re-exported so `from gatelock._window import LockConfig` -- which several
# sibling modules and the test suite already do -- keeps resolving after the
# declarative half moved to :mod:`gatelock._config`.
__all__ = [
"GrabKind",
"LockConfig",
"LockMode",
"LockWindow",
"LockWindowHooks",
"SpaceStep",
"TypeRole",
]
# Periodic no-op so a grabbed, event-starved loop keeps handing control back
# to Python, letting SIGTERM/SIGINT be serviced promptly.
# Tk's attributes() takes the value positionally, so a bare `True` here
# trips the boolean-positional lint. Naming it satisfies both that rule
# and the type stubs, which have no keyword overload.
_TOPMOST_ON = True
_KEEPALIVE_MS = 250
# Default retry interval for a "global" grab that initially fails (e.g. a
# fullscreen game holds it). Used whenever grab_retry_ms is left unset.
_DEFAULT_GRAB_RETRY_MS = 200
@dataclass(frozen=True)
class LockConfig:
"""Declarative knobs for one :class:`LockWindow` instance.
Each field left as ``None`` is derived from ``mode``; an explicit value
always overrides the preset for that one axis.
Attributes:
mode: Preset bundling the common combination. "soft" = topmost only,
typeable, WM-escapable. "hard" = overrideredirect + global grab +
VT-disable (the production lock for all three apps).
overrideredirect: Force a WM-unmanaged window. None = derive from mode.
Note that per-output placement *requires* this: a window manager
rewrites a managed window's geometry wholesale.
grab: Input grab strategy. None = derive from mode.
disable_vt: Disable Ctrl+Alt+Fn VT switching. None = derive from mode.
grab_retry_ms: Retry interval in ms for a "global" grab that initially
fails. 0 means "try once, then fall back to a local grab". Left
unset (None), a "global" grab retries forever every 200ms.
grab_log_every: Log a warning every N failed retry-forever attempts.
preempt_weaker_holder: SIGTERM a lower-ranked incumbent that is
blocking our grab, instead of retrying against it forever. Only
the *direction* the arbiter's own ranking already sanctions: we
never signal a holder that outranks us. SIGTERM (not SIGKILL) so
the holder's own signal handler runs its normal close() path --
same teardown as a clean dismiss, just triggered externally.
Defaults to False, and must stay opt-in: for an *enforcement*
lock (screen_locker), being preempted means the machine unlocks
with the obligation unmet. Only an app whose own dismissal is
harmless -- or which genuinely outranks every enforcer -- should
turn this on, and only after considering who it can now evict.
app_name: This app's name, used in arbitration logs so a blocked app
can say who is actually holding the screen.
rank: Arbitration priority; higher wins. See the ``RANK_*`` constants
in :mod:`gatelock._arbiter`.
recovery_tick_ms: Interval of the full re-assertion pass.
detect_drain_ms: Interval of the cheap "did anything change?" drain.
bg: Background color for the lock surfaces.
fg: Primary (near-white) text color.
muted: Secondary/caption text color.
field_bg: Background for "raised" surfaces (entry/spinbox fields,
input wells) -- one step lighter than ``bg``.
accent: The shared brand accent (buttons, primary actions).
success: Positive/on-track status color.
warning: Caution/pending status color.
danger: Negative/error status color.
on_fill: Text/icon color for anything drawn on top of a filled
accent/success/warning/danger surface (e.g. a button's label) --
NOT ``fg``. All four fills sit in the same mid-light band, so
near-white text under-contrasts on every one of them; callers
must pick ``fg`` vs. ``on_fill`` based on the widget's own
background, never hardcode one for all buttons.
font_family: Default font family for lock-window widgets.
focus_ring: Color of the *focused* widget's highlight ring. Defaults to
``accent``, because Tk's own default is black -- invisible against
``bg``. Pass to ``highlightcolor``; note ``highlightbackground`` is
the *unfocused* ring, so setting that one inverts the affordance.
focus_thickness: Ring width in px. Never set 0 on a focusable widget.
type_display, type_title, type_subtitle, type_body, type_label,
type_caption: The type scale, in **pixels**. Do not pass these to
Tk directly -- use :meth:`font`, which applies the sign convention.
space_xs, space_sm, space_md, space_lg, space_xl, space_xxl: The 4px
spacing scale, in pixels. Use for ``padx``/``pady``/``ipadx``.
All color/font defaults come from the ``unified-design-system`` docs
(``~/utils/unified-design-system/tokens.md``) -- the same palette used by
every one of kuhy's apps, Flutter and web included.
"""
mode: LockMode = "hard"
overrideredirect: bool | None = None
grab: GrabKind | None = None
disable_vt: bool | None = None
grab_retry_ms: int | None = None
grab_log_every: int = 25
preempt_weaker_holder: bool = False
app_name: str = "gatelock"
rank: int = RANK_SCREEN_LOCKER
recovery_tick_ms: int = 1000
detect_drain_ms: int = 100
bg: str = "#211D1B"
fg: str = "#ECEAE9"
muted: str = "#AAA09A"
field_bg: str = "#2B2624"
accent: str = "#B8862E"
success: str = "#8A9A3C"
warning: str = "#E0A63C"
danger: str = "#E2585F"
on_fill: str = "#211D1B"
font_family: str = "Arial"
focus_ring: str = "#B8862E"
focus_thickness: int = 2
# Type scale in PIXELS (unified-design-system tokens.md). Convert via
# font(); a raw positive value handed to Tk means *points*, ~37% bigger.
type_display: int = 32
type_title: int = 24
type_subtitle: int = 20
type_body: int = 16
type_label: int = 14
type_caption: int = 12
# 4px spacing scale, in pixels.
space_xs: int = 4
space_sm: int = 8
space_md: int = 16
space_lg: int = 24
space_xl: int = 32
space_xxl: int = 48
def type_px(self, role: TypeRole = "body") -> int:
"""Return the type-scale size for ``role``, in pixels.
Compacted on short displays -- see :mod:`gatelock._density`. The scale
is authored for 1080p; a 768px panel gets 0.8 of it, because a lock
surface has to fit one screen and cannot scroll its way out of being
too tall.
"""
return _density.scale_type(int(getattr(self, f"type_{role}")))
def space(self, step: SpaceStep = "md") -> int:
"""Return the spacing-scale value for ``step``, in pixels.
Compacted on short displays, exactly like :meth:`type_px`.
"""
return _density.scale_space(int(getattr(self, f"space_{step}")))
def font(
self,
role: TypeRole = "body",
*,
bold: bool = False,
family: str | None = None,
scale: float = 1.0,
) -> tuple[str, int] | tuple[str, int, str]:
"""Return a Tk font tuple for a type-scale role, sized in **pixels**.
Tk encodes the unit in the *sign* of the size: positive means points,
negative means pixels. The design-system scale is in pixels, so passing
e.g. ``type_body`` (16) straight to Tk yields 16 *points* -- about 37%
larger than intended (measured: linespace 26px vs 19px). Inflating
every string by a third is enough on its own to push a layout off a
768px-tall screen, which is exactly what happened to the diet_guard
meal gate. Always build lock-window fonts through this method.
Args:
role: Type-scale role.
bold: Append Tk's ``"bold"`` weight.
family: Override the font family. Defaults to ``font_family``.
scale: Multiplier for display-only emphasis (e.g. an oversized
countdown). Kept explicit so outliers are visible rather than
hidden behind a fresh literal.
Returns:
A Tk font tuple with a negative (pixel) size.
"""
px = max(1, round(self.type_px(role) * scale))
name = family if family is not None else self.font_family
return (name, -px, "bold") if bold else (name, -px)
def focus_kwargs(self) -> dict[str, str | int]:
"""Return widget kwargs that make focus visible on this palette.
``highlightcolor`` is the *focused* ring; ``highlightbackground`` is the
unfocused one. Both are set so the widget shows a subdued edge when
unfocused and the accent ring when focused -- rather than Tk's default
black-on-``bg``, which reads as no ring at all.
"""
return {
"highlightcolor": self.focus_ring,
"highlightbackground": self.bg,
"highlightthickness": self.focus_thickness,
}
def resolved_overrideredirect(self) -> bool:
"""Return the effective overrideredirect setting."""
if self.overrideredirect is not None:
return self.overrideredirect
return self.mode == "hard"
def resolved_grab(self) -> GrabKind:
"""Return the effective grab strategy."""
if self.grab is not None:
return self.grab
return "global" if self.mode == "hard" else "none"
def resolved_disable_vt(self) -> bool:
"""Return whether VT switching should be disabled."""
if self.disable_vt is not None:
return self.disable_vt
return self.mode == "hard"
class LockWindowHooks(Protocol):
"""Callbacks :class:`LockWindow` invokes; the embedding app supplies all."""
def build_surface(self, parent: tk.Misc, surface: SurfaceInfo) -> None:
"""Build this app's widgets inside ``parent``, for one output.
Called once per live output, and again whenever an output comes back.
Tk variables should stay mastered on the root so every surface shows
the same state, and every surface's submit path should call the same
handler -- solving the lock on any monitor dismisses all of them.
"""
def teardown_surface(self, surface: SurfaceInfo) -> None:
"""Forget per-surface state; that output went dark and is closing."""
def on_focus_ready(self, surface: SurfaceInfo | None) -> None:
"""Called once the lock is mapped and (if applicable) grabbed.
Args:
surface: The surface that took initial focus, or None when no
output is live and there is therefore nothing to focus.
"""
def on_callback_error(self) -> None:
"""Called when a Tk callback raised (see :class:`~gatelock.GateRoot`)."""
def on_close(self) -> None:
"""Called once, from :meth:`LockWindow.close`, before VT is restored.
Runs on every exit path -- normal dismiss, SIGTERM, SIGINT -- not just
a clean close, so app-specific teardown (restoring hardware state,
etc.) can't be skipped by killing the process.
"""
class LockWindow:
@ -337,6 +115,15 @@ class LockWindow:
hooks=hooks,
),
)
self._arming = _arming.ArmingCollaborators(
config=config,
surfaces=self._surfaces,
enumerator=self._enumerator,
detector=self._detector,
recovery=self._recovery,
notify_focus_ready=self._notify_focus_ready,
log_grab_blocked=self._log_grab_blocked,
)
@property
def surfaces(self) -> SurfaceSet:
@ -348,151 +135,36 @@ class LockWindow:
def setup(self) -> None:
"""Configure the backdrop and build a surface on every live output.
Disables VT switching first: strengthening the lock must not wait on
being able to draw anything. If no output is live, no surface is built
and the lock stays armed and invisible until one appears.
Delegates to :func:`gatelock._arming.setup`.
"""
if self._config.resolved_disable_vt():
self._vt_disabled = disable_vt_switching()
if needs_backdrop_root(self._config):
# The root is a plain black backdrop spanning the whole X screen,
# including any region a modeless output left behind. It holds the
# grab (X will not grab for a window that is not viewable) and
# never carries widgets.
self.root.overrideredirect(boolean=self._config.resolved_overrideredirect())
self._surfaces.update_backdrop()
else:
self.root.attributes("-topmost", _TOPMOST_ON)
scan = self._enumerator.scan()
delta = self._surfaces.apply(scan)
if not scan.live:
_logger.warning(
"no live outputs at startup (source=%s); arming the lock with "
"nothing displayed -- it will appear as soon as a monitor "
"comes back",
scan.source,
)
else:
_logger.info(
"lock armed on %d output(s): %s",
len(scan.live),
", ".join(output.name for output in scan.live),
)
if delta.unverified:
_logger.error(
"outputs live but not covered at startup: %s",
", ".join(delta.unverified),
)
self._vt_disabled = _arming.setup(self.root, self._arming)
def grab_input(self) -> None:
"""Take the configured grab, then start watching for output changes."""
self.root.update_idletasks()
self.root.focus_force()
grab = self._config.resolved_grab()
if grab == "global":
self._acquire_global_grab(attempt=1)
elif grab == "local":
with contextlib.suppress(tk.TclError):
self.root.grab_set()
self._detector.start()
self._recovery.start()
self.root.after(100, self._notify_focus_ready)
"""Take the configured grab, then start watching for output changes.
Delegates to :func:`gatelock._arming.grab_input`.
"""
_arming.grab_input(self.root, self._arming)
def _acquire_global_grab(self, *, attempt: int) -> None:
"""Acquire the global input grab, retrying per ``grab_retry_ms``.
"""Acquire the global grab, retrying per ``grab_retry_ms``.
Args:
attempt: 1-based attempt counter, used only to throttle the log.
Delegates to :func:`gatelock._arming.acquire_global_grab`.
"""
retry_ms = self._config.grab_retry_ms
try:
self.root.grab_set_global()
except tk.TclError:
if retry_ms == 0:
_logger.warning("Global grab failed, falling back to local grab")
with contextlib.suppress(tk.TclError):
self.root.grab_set()
return
effective_retry_ms = retry_ms or _DEFAULT_GRAB_RETRY_MS
if not attempt % self._config.grab_log_every:
self._log_grab_blocked(attempt)
self.root.after(
effective_retry_ms,
lambda: self._acquire_global_grab(attempt=attempt + 1),
)
return
with contextlib.suppress(tk.TclError):
self.root.focus_force()
self._notify_focus_ready()
_arming.acquire_global_grab(self.root, self._arming, attempt=attempt)
def _log_grab_blocked(self, attempt: int) -> None:
"""Say who is actually holding the grab, rather than guessing.
"""Log who holds the grab, and stand a weaker holder down.
v0.1.1 always blamed "a fullscreen game". On 2026-07-25 the holder was
the other locker, and that guess sent the diagnosis in the wrong
direction for the length of the outage.
A holder that outranks us is left alone entirely -- retrying is the
correct behavior there, matching :func:`gatelock.wait_for_turn`'s own
rule for an app that has not armed yet. A *weaker* holder is preempted
below, once per pid, rather than left to block us for as long as it
takes to finish on its own (diet_guard held the grab for ~3 minutes
against a higher-ranked screen_locker on 2026-08-21).
Delegates to :mod:`gatelock._preempt`; see there for the policy and
why a stronger holder is left alone.
"""
holder = self._arbiter.describe_holder() if self._arbiter else None
if holder is None:
_logger.warning(
"global grab still blocked after %d attempts; no gatelock app "
"holds it -- likely another X client (e.g. a fullscreen game)",
attempt,
)
return
_logger.warning(
"global grab still blocked after %d attempts; held by gatelock app "
"%r (rank %d, pid %d) since %s",
_preempt.log_grab_blocked(
attempt,
holder.app,
holder.rank,
holder.pid,
holder.started,
arbiter=self._arbiter,
config=self._config,
preempted_pids=self._preempted_pids,
)
self._maybe_preempt(holder)
def _maybe_preempt(self, holder: Claim) -> None:
"""SIGTERM a weaker holder once, so it stands down instead of blocking.
SIGTERM (not SIGKILL): the holder's own signal handler
(``LockWindow._install_signal_handlers``) raises ``SystemExit(0)``,
which unwinds through its ``run()``'s ``finally`` into its own
``close()`` -- the identical teardown a clean dismiss gets (VT
restored, arbiter claim released, app-specific ``on_close`` hook
run), just triggered externally instead of by the user.
"""
if not self._config.preempt_weaker_holder or self._arbiter is None:
return
if holder.rank >= self._arbiter.claim.rank:
return
if holder.pid in self._preempted_pids:
return
self._preempted_pids.add(holder.pid)
_logger.warning(
"preempting weaker holder %r (rank %d, pid %d) so rank %d can arm",
holder.app,
holder.rank,
holder.pid,
self._arbiter.claim.rank,
)
try:
os.kill(holder.pid, signal.SIGTERM)
except ProcessLookupError:
_logger.info(
"holder pid %d was already gone by the time we signalled it",
holder.pid,
)
except OSError:
_logger.exception("could not signal holder pid %d", holder.pid)
def _notify_focus_ready(self) -> None:
"""Tell the app it can focus its first input widget now.

View File

@ -20,6 +20,8 @@ import tkinter as tk
import pytest
from gatelock._scrollable import ScrollableSurface
from gatelock._scrollkeys import bind_scroll_keys
from gatelock._userintent import viewport_targets
from gatelock._window import LockConfig
pytestmark = pytest.mark.skipif(
@ -275,8 +277,8 @@ def test_paging_degrades_to_the_canvas_without_a_toplevel(
surface.canvas.winfo_toplevel = _no_toplevel
with caplog.at_level("WARNING"):
surface._bind_scroll_keys()
surface._bind_user_input()
bind_scroll_keys(surface.canvas, surface.content)
surface._intent.bind(viewport_targets(surface.canvas, surface.content))
assert "paging keys bound to the canvas only" in caplog.text
assert "user-input tracking is bound to the viewport only" in caplog.text

View File

@ -53,7 +53,7 @@ class TestSetup:
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
with patch(
"gatelock._window.disable_vt_switching", return_value=True
"gatelock._arming.disable_vt_switching", return_value=True
) as mock_disable:
window.setup()
@ -75,7 +75,7 @@ class TestSetup:
"""Soft mode never calls overrideredirect or disables VT switching."""
window, _hooks = make_window(mock_root, config=LockConfig(mode="soft"))
with patch("gatelock._window.disable_vt_switching") as mock_disable:
with patch("gatelock._arming.disable_vt_switching") as mock_disable:
window.setup()
mock_root.overrideredirect.assert_not_called()
@ -106,10 +106,10 @@ class TestGrabInput:
mock_root, config=LockConfig(mode="soft", grab="global")
)
with patch.object(window, "_acquire_global_grab") as mock_acquire:
with patch("gatelock._arming.acquire_global_grab") as mock_acquire:
window.grab_input()
mock_acquire.assert_called_once_with(attempt=1)
mock_acquire.assert_called_once_with(window.root, window._arming, attempt=1)
mock_root.after.assert_any_call(100, window._notify_focus_ready)
def test_local_grab_calls_grab_set(self, mock_root: MagicMock) -> None:
@ -213,11 +213,11 @@ class TestAcquireGlobalGrab:
mock_root, config=LockConfig(mode="hard", grab_log_every=5)
)
with patch("gatelock._window._logger") as mock_logger:
with patch("gatelock._preempt._logger") as mock_logger:
window._acquire_global_grab(attempt=5)
mock_logger.warning.assert_called_once()
with patch("gatelock._window._logger") as mock_logger:
with patch("gatelock._preempt._logger") as mock_logger:
window._acquire_global_grab(attempt=3)
mock_logger.warning.assert_not_called()
@ -243,10 +243,10 @@ class TestAcquireGlobalGrab:
window._acquire_global_grab(attempt=1)
scheduled_callback = mock_root.after.call_args[0][1]
with patch.object(window, "_acquire_global_grab") as mock_acquire:
with patch("gatelock._arming.acquire_global_grab") as mock_acquire:
scheduled_callback()
mock_acquire.assert_called_once_with(attempt=2)
mock_acquire.assert_called_once_with(window.root, window._arming, attempt=2)
class TestNotifyFocusReady:

View File

@ -6,6 +6,7 @@ import queue
import signal
from unittest.mock import MagicMock, patch
from gatelock import _preempt
from gatelock._arbiter import (
RANK_DIET_GUARD,
RANK_SCREEN_LOCKER,
@ -89,7 +90,7 @@ class TestGrabBlockedLogging:
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=False)
)
window._arbiter = arbiter
with patch("gatelock._window._logger") as logger:
with patch("gatelock._preempt._logger") as logger:
window._log_grab_blocked(25)
assert "diet_guard" in str(logger.warning.call_args)
@ -98,7 +99,7 @@ class TestGrabBlockedLogging:
) -> None:
"""With no gatelock holder, a foreign X client is the honest guess."""
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
with patch("gatelock._window._logger") as logger:
with patch("gatelock._preempt._logger") as logger:
window._log_grab_blocked(25)
assert "fullscreen game" in str(logger.warning.call_args)
@ -108,7 +109,7 @@ class TestGrabBlockedLogging:
arbiter.describe_holder.return_value = None
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._arbiter = arbiter
with patch("gatelock._window._logger") as logger:
with patch("gatelock._preempt._logger") as logger:
window._log_grab_blocked(50)
assert "fullscreen game" in str(logger.warning.call_args)
@ -144,9 +145,11 @@ class TestPreemptWeakerHolder:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True))
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with patch("gatelock._window.os.kill") as kill:
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_called_once_with(4075, signal.SIGTERM)
@ -154,9 +157,11 @@ class TestPreemptWeakerHolder:
arbiter = self._arbiter_with(
our_rank=RANK_DIET_GUARD, holder_rank=RANK_SCREEN_LOCKER, holder_pid=4137
)
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True))
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with patch("gatelock._window.os.kill") as kill:
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_not_called()
@ -164,9 +169,11 @@ class TestPreemptWeakerHolder:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True))
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with patch("gatelock._window.os.kill") as kill:
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
window._log_grab_blocked(50)
kill.assert_called_once_with(4075, signal.SIGTERM)
@ -179,7 +186,7 @@ class TestPreemptWeakerHolder:
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=False)
)
window._arbiter = arbiter
with patch("gatelock._window.os.kill") as kill:
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_not_called()
@ -197,14 +204,16 @@ class TestPreemptWeakerHolder:
)
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._arbiter = arbiter
with patch("gatelock._window.os.kill") as kill:
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_not_called()
def test_no_arbiter_means_no_preemption(self, mock_root: MagicMock) -> None:
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True))
with patch("gatelock._window.os.kill") as kill:
window._maybe_preempt(
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
with patch("gatelock._preempt.os.kill") as kill:
_preempt.maybe_preempt(
Claim(
app="holder",
rank=RANK_DIET_GUARD,
@ -213,7 +222,10 @@ class TestPreemptWeakerHolder:
grab="global",
disable_vt=True,
instance_id="theirs",
)
),
arbiter=None,
config=window._config,
preempted_pids=set(),
)
kill.assert_not_called()
@ -223,11 +235,13 @@ class TestPreemptWeakerHolder:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True))
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with (
patch("gatelock._window.os.kill", side_effect=ProcessLookupError),
patch("gatelock._window._logger") as logger,
patch("gatelock._preempt.os.kill", side_effect=ProcessLookupError),
patch("gatelock._preempt._logger") as logger,
):
window._log_grab_blocked(25)
assert logger.info.called
@ -238,11 +252,13 @@ class TestPreemptWeakerHolder:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True))
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with (
patch("gatelock._window.os.kill", side_effect=OSError("nope")),
patch("gatelock._window._logger") as logger,
patch("gatelock._preempt.os.kill", side_effect=OSError("nope")),
patch("gatelock._preempt._logger") as logger,
):
window._log_grab_blocked(25)
assert logger.exception.called

View File

@ -27,6 +27,11 @@ repos:
- repo: local
hooks:
- id: file-length-cap
name: file length <= 250 lines
entry: bash /home/kuhy/utils/scripts/check_file_length.sh
language: system
pass_filenames: true
- id: subproject-scope
name: subproject scope regex still matches
entry: scripts/check_subproject_scope.sh sync_settings_ui

View File

@ -35,6 +35,11 @@ repos:
- repo: local
hooks:
- id: file-length-cap
name: file length <= 250 lines
entry: bash /home/kuhy/utils/scripts/check_file_length.sh
language: system
pass_filenames: true
- id: subproject-scope
name: subproject scope regex still matches
entry: scripts/check_subproject_scope.sh web_ui