mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-18 21:54:34 +01:00
Some checks failed
dependency freshness / dependencies on newest stable (push) Waiting to run
file length / file-length (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
gatelock pre-commit / pre-commit (push) Has been cancelled
gatelock tests / test (push) Has been cancelled
A keyring prompt (gcr-prompter) that grabbed input before the leetcode lock armed left the lock visible but unclickable: every click went to the prompt hidden under it. Each failed grab_set_global also froze Tk ~1 s, so the lock barely repainted. - Raise known credential prompts above the lock after 2 s of a blocked grab; games and other grabbers stay covered. - Probe the grab on a side Xlib connection first so a blocked grab never stalls the Tk loop (worst gap 1.05 s -> 0.05 s). - Log the Tk grab error and stop blaming our own claim. - 1.5 s startup grace in wait_for_turn, and a weaker armed lock steps back (windowless, re-arms later) when a stronger one is live, so only one lock is ever on screen. - Real-X checks: verify_prompt_yield, verify_grab_responsive, verify_all_lockers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWZbpxQZj41WpbQPuxB
198 lines
7.3 KiB
Python
198 lines
7.3 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki
|
|
"""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, field
|
|
import logging
|
|
import tkinter as tk
|
|
from typing import TYPE_CHECKING
|
|
|
|
from gatelock._prompts import PromptYield
|
|
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
|
|
|
|
|
|
def _no_grab_listener() -> None:
|
|
"""Default for :attr:`ArmingCollaborators.notify_grab_held`."""
|
|
|
|
|
|
@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.
|
|
notify_grab_held: Called once a grab call has actually succeeded, so
|
|
the claim's ``grab_held`` turns true only then.
|
|
prompt_yield: Times the blocked grab (shared with the recovery loop) and
|
|
decides whether a system credential prompt gets raised over us.
|
|
"""
|
|
|
|
config: LockConfig
|
|
surfaces: SurfaceSet
|
|
enumerator: OutputEnumerator
|
|
detector: OutputChangeDetector
|
|
recovery: RecoveryLoop
|
|
notify_focus_ready: Callable[[], None]
|
|
log_grab_blocked: Callable[[int], None]
|
|
notify_grab_held: Callable[[], None] = _no_grab_listener
|
|
prompt_yield: PromptYield = field(default_factory=PromptYield)
|
|
|
|
|
|
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.notify_grab_held()
|
|
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:
|
|
collab.prompt_yield.check_grab()
|
|
root.grab_set_global()
|
|
except tk.TclError as exc:
|
|
if retry_ms == 0:
|
|
_logger.warning("Global grab failed (%s), falling back to local grab", exc)
|
|
with contextlib.suppress(tk.TclError):
|
|
root.grab_set()
|
|
collab.notify_grab_held()
|
|
return
|
|
collab.prompt_yield.grab_blocked(str(exc))
|
|
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
|
|
if collab.prompt_yield.grab_held():
|
|
collab.surfaces.raise_all()
|
|
collab.notify_grab_held()
|
|
with contextlib.suppress(tk.TclError):
|
|
root.focus_force()
|
|
collab.notify_focus_ready()
|