Compare commits

..

No commits in common. "68ec316b28ccf798a4e029b083f3b8157b39253f" and "8274a3e918df4a2e47786f38fb4567b39a4c3ece" have entirely different histories.

35 changed files with 244 additions and 408 deletions

View File

@ -101,18 +101,15 @@ repos:
- --disable-error-code=list-item - --disable-error-code=list-item
- repo: https://github.com/pylint-dev/pylint - repo: https://github.com/pylint-dev/pylint
rev: v4.0.8 rev: v3.3.2
hooks: hooks:
- id: pylint - id: pylint
args: args:
- --rcfile=freedays/pyproject.toml - --rcfile=freedays/pyproject.toml
- --fail-under=10 - --fail-under=8.0
- --jobs=4 - --jobs=4
additional_dependencies: additional_dependencies:
- pytest - pytest
# Kept in step with pyproject.toml, so pylint resolves the crdt_sync
# imports instead of scoring every one of them as import-error.
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
- repo: https://github.com/PyCQA/bandit - repo: https://github.com/PyCQA/bandit
rev: 1.9.4 rev: 1.9.4

View File

@ -138,7 +138,7 @@ def sync_quietly(*, paths: Paths | None = None) -> bool:
# this is normal on a laptop and must not fill the journal. # this is normal on a laptop and must not fill the journal.
_logger.debug("free-day sync skipped: %s", exc) _logger.debug("free-day sync skipped: %s", exc)
return False return False
except Exception: # pylint: disable=broad-exception-caught except Exception:
_logger.exception("free-day sync failed unexpectedly") _logger.exception("free-day sync failed unexpectedly")
return False return False
return True return True

View File

@ -90,22 +90,11 @@ color_output = true
exclude = [".venv/"] exclude = [".venv/"]
[tool.pylint.main] [tool.pylint.main]
# The repo root on the path, so pylint resolves the package's own imports the
# same way pytest does instead of reporting import-error for them.
init-hook = "import sys; sys.path.insert(0, 'freedays')"
analyse-fallback-blocks = true analyse-fallback-blocks = true
persistent = true persistent = true
jobs = 0 jobs = 0
py-version = "3.14" py-version = "3.14"
ignore = [".venv", "__pycache__"] ignore = [".venv", "__pycache__"]
# Test suites intentionally use patterns (protected-access, fixture-arg
# shadowing) that don't apply to source code; ruff's per-file-ignores carry
# the equivalent exemptions, so tests stay linted -- by ruff. This is the same
# source-only pylint scope wake-alarm / diet-guard / testsAndMisc use. It has
# to be `ignore-paths`, not `ignore = ["tests"]`: `ignore` only matches the
# basename of what pylint is *given*, and pre-commit hands it explicit file
# paths, so a directory name in `ignore` never fires under the hook.
ignore-paths = ["^(.*/)?tests/.*$"]
ignore-patterns = [".*\\.pyi$"] ignore-patterns = [".*\\.pyi$"]
[tool.pylint.messages_control] [tool.pylint.messages_control]

View File

@ -101,12 +101,12 @@ repos:
- --disable-error-code=list-item - --disable-error-code=list-item
- repo: https://github.com/pylint-dev/pylint - repo: https://github.com/pylint-dev/pylint
rev: v4.0.8 rev: v3.3.2
hooks: hooks:
- id: pylint - id: pylint
args: args:
- --rcfile=gatelock/pyproject.toml - --rcfile=gatelock/pyproject.toml
- --fail-under=10 - --fail-under=8.0
- --jobs=4 - --jobs=4
additional_dependencies: additional_dependencies:
- pytest - pytest

View File

@ -55,11 +55,9 @@ class MyGate:
`LockConfig`'s `mode` preset bundles the common combination ("soft" = topmost `LockConfig`'s `mode` preset bundles the common combination ("soft" = topmost
only, typeable, WM-escapable; "hard" = overrideredirect + global grab + only, typeable, WM-escapable; "hard" = overrideredirect + global grab +
VT-disable). `overrideredirect` and the `grab=GrabPolicy(kind=..., disable_vt=..., VT-disable). Each axis (`overrideredirect`, `grab`, `disable_vt`,
retry_ms=...)` axes can be set explicitly to reproduce a consumer's exact prior `grab_retry_ms`) can be set explicitly to reproduce a consumer's exact prior
behavior where it diverges from the preset. Colours, type scale and spacing are behavior where it diverges from the preset.
the `palette`, `typography` and `spacing` records (`gatelock.LockPalette` etc.),
overridden as a unit.
`gatelock.log_integrity` ports the HMAC-signed state module used by all three `gatelock.log_integrity` ports the HMAC-signed state module used by all three
projects; `DEFAULT_HMAC_KEY_FILE` (`/etc/workout-locker/hmac.key`) is projects; `DEFAULT_HMAC_KEY_FILE` (`/etc/workout-locker/hmac.key`) is

View File

@ -13,9 +13,11 @@ from gatelock._arbiter import (
RANK_SCREEN_LOCKER, RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM, RANK_WAKE_ALARM,
Arbiter, Arbiter,
ArbiterVerdict,
Claim,
default_runtime_dir,
grab_strength,
) )
from gatelock._claims import ArbiterVerdict, Claim, default_runtime_dir, grab_strength
from gatelock._config import GrabPolicy
from gatelock._detect import OutputChangeDetector from gatelock._detect import OutputChangeDetector
from gatelock._escape import ( from gatelock._escape import (
EscapeDraft, EscapeDraft,
@ -54,7 +56,6 @@ from gatelock._surfaces import (
mirror_text_widgets, mirror_text_widgets,
needs_backdrop_root, needs_backdrop_root,
) )
from gatelock._theme import LockPalette, LockSpacing, LockTypography
from gatelock._vt import disable_vt_switching, restore_vt_switching from gatelock._vt import disable_vt_switching, restore_vt_switching
from gatelock._window import ( from gatelock._window import (
LockConfig, LockConfig,
@ -94,11 +95,7 @@ __all__ = [
"EscapeTracker", "EscapeTracker",
"FitResult", "FitResult",
"GateRoot", "GateRoot",
"GrabPolicy",
"LockConfig", "LockConfig",
"LockPalette",
"LockSpacing",
"LockTypography",
"LockWindow", "LockWindow",
"LockWindowHooks", "LockWindowHooks",
"Output", "Output",

View File

@ -42,6 +42,7 @@ from gatelock._claims import (
Claim, Claim,
_try_lock, _try_lock,
default_runtime_dir, default_runtime_dir,
grab_strength,
live_claims, live_claims,
read_claim_if_held, read_claim_if_held,
) )
@ -51,6 +52,20 @@ if TYPE_CHECKING:
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
# Re-exported after the 250-line split: `from gatelock._arbiter import
# Claim` is used by _window, the tests and gatelock's own __init__.
__all__ = [
"RANK_DIET_GUARD",
"RANK_SCREEN_LOCKER",
"RANK_WAKE_ALARM",
"Arbiter",
"ArbiterVerdict",
"Claim",
"default_runtime_dir",
"grab_strength",
]
RANK_WAKE_ALARM: Final = 300 RANK_WAKE_ALARM: Final = 300
RANK_SCREEN_LOCKER: Final = 200 RANK_SCREEN_LOCKER: Final = 200
RANK_DIET_GUARD: Final = 100 RANK_DIET_GUARD: Final = 100

View File

@ -157,7 +157,7 @@ def acquire_global_grab(
collab: The window's arming collaborators. collab: The window's arming collaborators.
attempt: 1-based attempt counter, used only to throttle the log. attempt: 1-based attempt counter, used only to throttle the log.
""" """
retry_ms = collab.config.grab.retry_ms retry_ms = collab.config.grab_retry_ms
try: try:
root.grab_set_global() root.grab_set_global()
except tk.TclError: except tk.TclError:
@ -167,7 +167,7 @@ def acquire_global_grab(
root.grab_set() root.grab_set()
return return
effective_retry_ms = retry_ms or _DEFAULT_GRAB_RETRY_MS effective_retry_ms = retry_ms or _DEFAULT_GRAB_RETRY_MS
if not attempt % collab.config.grab.log_every: if not attempt % collab.config.grab_log_every:
collab.log_grab_blocked(attempt) collab.log_grab_blocked(attempt)
root.after( root.after(
effective_retry_ms, effective_retry_ms,

View File

@ -13,37 +13,38 @@ import LockConfig`` keeps working for the modules and tests that already do.
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass
from typing import Literal from typing import Literal
from gatelock import _density from gatelock import _density
from gatelock._arbiter import RANK_SCREEN_LOCKER from gatelock._arbiter import RANK_SCREEN_LOCKER
from gatelock._theme import (
LockPalette,
LockSpacing,
LockTypography,
SpaceStep,
TypeRole,
)
GrabKind = Literal["none", "local", "global"] GrabKind = Literal["none", "local", "global"]
LockMode = Literal["soft", "hard"] LockMode = Literal["soft", "hard"]
TypeRole = Literal["display", "title", "subtitle", "body", "label", "caption"]
SpaceStep = Literal["xs", "sm", "md", "lg", "xl", "xxl"]
@dataclass(frozen=True) @dataclass(frozen=True)
class GrabPolicy: class LockConfig:
"""How the lock takes and keeps the input grab. """Declarative knobs for one :class:`LockWindow` instance.
Each field left as ``None`` is derived from :attr:`LockConfig.mode`; an Each field left as ``None`` is derived from ``mode``; an explicit value
explicit value always overrides the preset for that one axis. always overrides the preset for that one axis.
Attributes: Attributes:
kind: Input grab strategy. None = derive from mode. 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. disable_vt: Disable Ctrl+Alt+Fn VT switching. None = derive from mode.
retry_ms: Retry interval in ms for a "global" grab that initially 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 fails. 0 means "try once, then fall back to a local grab". Left
unset (None), a "global" grab retries forever every 200ms. unset (None), a "global" grab retries forever every 200ms.
log_every: Log a warning every N failed retry-forever attempts. grab_log_every: Log a warning every N failed retry-forever attempts.
preempt_weaker_holder: SIGTERM a lower-ranked incumbent that is preempt_weaker_holder: SIGTERM a lower-ranked incumbent that is
blocking our grab, instead of retrying against it forever. Only blocking our grab, instead of retrying against it forever. Only
the *direction* the arbiter's own ranking already sanctions: we the *direction* the arbiter's own ranking already sanctions: we
@ -55,55 +56,82 @@ class GrabPolicy:
with the obligation unmet. Only an app whose own dismissal is with the obligation unmet. Only an app whose own dismissal is
harmless -- or which genuinely outranks every enforcer -- should harmless -- or which genuinely outranks every enforcer -- should
turn this on, and only after considering who it can now evict. turn this on, and only after considering who it can now evict.
"""
kind: GrabKind | None = None
disable_vt: bool | None = None
retry_ms: int | None = None
log_every: int = 25
preempt_weaker_holder: bool = False
@dataclass(frozen=True)
class LockConfig:
"""Declarative knobs for one :class:`LockWindow` instance.
``overrideredirect`` and the grab policy's ``None`` fields are derived
from ``mode``; an explicit value always overrides the preset for that one
axis. The visual vocabulary lives in the three :mod:`gatelock._theme`
records, overridden as a unit.
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: How the input grab is taken and kept; see :class:`GrabPolicy`.
app_name: This app's name, used in arbitration logs so a blocked app app_name: This app's name, used in arbitration logs so a blocked app
can say who is actually holding the screen. can say who is actually holding the screen.
rank: Arbitration priority; higher wins. See the ``RANK_*`` constants rank: Arbitration priority; higher wins. See the ``RANK_*`` constants
in :mod:`gatelock._arbiter`. in :mod:`gatelock._arbiter`.
recovery_tick_ms: Interval of the full re-assertion pass. recovery_tick_ms: Interval of the full re-assertion pass.
detect_drain_ms: Interval of the cheap "did anything change?" drain. detect_drain_ms: Interval of the cheap "did anything change?" drain.
palette: Colours; see :class:`gatelock._theme.LockPalette`. bg: Background color for the lock surfaces.
typography: Font family and type scale; fg: Primary (near-white) text color.
see :class:`gatelock._theme.LockTypography`. muted: Secondary/caption text color.
spacing: Spacing scale and focus-ring width; field_bg: Background for "raised" surfaces (entry/spinbox fields,
see :class:`gatelock._theme.LockSpacing`. 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
(``~/src/utils/unified-design-system/tokens.md``) -- the same palette used by
every one of kuhy's apps, Flutter and web included.
""" """
mode: LockMode = "hard" mode: LockMode = "hard"
overrideredirect: bool | None = None overrideredirect: bool | None = None
grab: GrabPolicy = field(default_factory=GrabPolicy) 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" app_name: str = "gatelock"
rank: int = RANK_SCREEN_LOCKER rank: int = RANK_SCREEN_LOCKER
recovery_tick_ms: int = 1000 recovery_tick_ms: int = 1000
detect_drain_ms: int = 100 detect_drain_ms: int = 100
palette: LockPalette = field(default_factory=LockPalette) bg: str = "#211D1B"
typography: LockTypography = field(default_factory=LockTypography) fg: str = "#ECEAE9"
spacing: LockSpacing = field(default_factory=LockSpacing) 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: def type_px(self, role: TypeRole = "body") -> int:
"""Return the type-scale size for ``role``, in pixels. """Return the type-scale size for ``role``, in pixels.
@ -113,14 +141,14 @@ class LockConfig:
surface has to fit one screen and cannot scroll its way out of being surface has to fit one screen and cannot scroll its way out of being
too tall. too tall.
""" """
return _density.scale_type(int(getattr(self.typography, role))) return _density.scale_type(int(getattr(self, f"type_{role}")))
def space(self, step: SpaceStep = "md") -> int: def space(self, step: SpaceStep = "md") -> int:
"""Return the spacing-scale value for ``step``, in pixels. """Return the spacing-scale value for ``step``, in pixels.
Compacted on short displays, exactly like :meth:`type_px`. Compacted on short displays, exactly like :meth:`type_px`.
""" """
return _density.scale_space(int(getattr(self.spacing, step))) return _density.scale_space(int(getattr(self, f"space_{step}")))
def font( def font(
self, self,
@ -143,7 +171,7 @@ class LockConfig:
Args: Args:
role: Type-scale role. role: Type-scale role.
bold: Append Tk's ``"bold"`` weight. bold: Append Tk's ``"bold"`` weight.
family: Override the font family. Defaults to the typography's. family: Override the font family. Defaults to ``font_family``.
scale: Multiplier for display-only emphasis (e.g. an oversized scale: Multiplier for display-only emphasis (e.g. an oversized
countdown). Kept explicit so outliers are visible rather than countdown). Kept explicit so outliers are visible rather than
hidden behind a fresh literal. hidden behind a fresh literal.
@ -152,7 +180,7 @@ class LockConfig:
A Tk font tuple with a negative (pixel) size. A Tk font tuple with a negative (pixel) size.
""" """
px = max(1, round(self.type_px(role) * scale)) px = max(1, round(self.type_px(role) * scale))
name = family if family is not None else self.typography.font_family name = family if family is not None else self.font_family
return (name, -px, "bold") if bold else (name, -px) return (name, -px, "bold") if bold else (name, -px)
def focus_kwargs(self) -> dict[str, str | int]: def focus_kwargs(self) -> dict[str, str | int]:
@ -164,9 +192,9 @@ class LockConfig:
black-on-``bg``, which reads as no ring at all. black-on-``bg``, which reads as no ring at all.
""" """
return { return {
"highlightcolor": self.palette.focus_ring, "highlightcolor": self.focus_ring,
"highlightbackground": self.palette.bg, "highlightbackground": self.bg,
"highlightthickness": self.spacing.focus_thickness, "highlightthickness": self.focus_thickness,
} }
def resolved_overrideredirect(self) -> bool: def resolved_overrideredirect(self) -> bool:
@ -177,12 +205,12 @@ class LockConfig:
def resolved_grab(self) -> GrabKind: def resolved_grab(self) -> GrabKind:
"""Return the effective grab strategy.""" """Return the effective grab strategy."""
if self.grab.kind is not None: if self.grab is not None:
return self.grab.kind return self.grab
return "global" if self.mode == "hard" else "none" return "global" if self.mode == "hard" else "none"
def resolved_disable_vt(self) -> bool: def resolved_disable_vt(self) -> bool:
"""Return whether VT switching should be disabled.""" """Return whether VT switching should be disabled."""
if self.grab.disable_vt is not None: if self.disable_vt is not None:
return self.grab.disable_vt return self.disable_vt
return self.mode == "hard" return self.mode == "hard"

View File

@ -32,8 +32,6 @@ import threading
import tkinter as tk import tkinter as tk
from typing import Any from typing import Any
from gatelock._xlib import load_xlib
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
_SELECT_TIMEOUT_S = 0.5 _SELECT_TIMEOUT_S = 0.5
@ -66,14 +64,15 @@ class _RandrEventSource:
def _connect(self) -> bool: def _connect(self) -> bool:
"""Open the connection and subscribe to layout changes.""" """Open the connection and subscribe to layout changes."""
modules = load_xlib("Xlib.display", "Xlib.ext.randr") try:
if modules is None: from Xlib import display as xdisplay
from Xlib.ext import randr
except ImportError:
_logger.info( _logger.info(
"python-xlib is not installed; falling back to Tk <Configure> " "python-xlib is not installed; falling back to Tk <Configure> "
"plus xrandr polling for output-change detection" "plus xrandr polling for output-change detection"
) )
return False return False
xdisplay, randr = modules
try: try:
self._display = xdisplay.Display() self._display = xdisplay.Display()
root = self._display.screen().root root = self._display.screen().root

View File

@ -31,6 +31,11 @@ import json
import logging import logging
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
if TYPE_CHECKING:
from pathlib import Path
from gatelock._escape_types import ( from gatelock._escape_types import (
EscapeDraft, EscapeDraft,
EscapeHistory, EscapeHistory,
@ -38,10 +43,6 @@ from gatelock._escape_types import (
_parse_iso, _parse_iso,
_today_iso, _today_iso,
) )
from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
if TYPE_CHECKING:
from pathlib import Path
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)

View File

@ -17,11 +17,11 @@ Two backends compute the same predicate:
* **``xrandr --query``** text -- a re-derivation of the same predicate for * **``xrandr --query``** text -- a re-derivation of the same predicate for
systems without ``python-xlib``. systems without ``python-xlib``.
``python-xlib`` is an optional dependency, loaded on demand through ``python-xlib`` is an optional dependency, so its import lives inside a
:mod:`gatelock._xlib` rather than at module scope. That is deliberate and function rather than at module scope. That is deliberate and load-bearing: a
load-bearing: a module-scope ``try/except ImportError`` is resolved at import module-scope ``try/except ImportError`` is resolved at import time, which makes
time, which makes the ``except`` arm permanently unreachable for branch the ``except`` arm permanently unreachable for branch coverage -- and this is
coverage -- and this is precisely the degradation path that must stay tested. precisely the degradation path that must stay tested.
""" """
from __future__ import annotations from __future__ import annotations
@ -30,13 +30,13 @@ import logging
import re import re
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
if TYPE_CHECKING:
import tkinter as tk
from gatelock._output_types import Output, OutputRect, OutputScan from gatelock._output_types import Output, OutputRect, OutputScan
from gatelock._randr import RandrBackend from gatelock._randr import RandrBackend
from gatelock._xrandr import parse_xrandr_query, scan_xrandr from gatelock._xrandr import parse_xrandr_query, scan_xrandr
if TYPE_CHECKING:
import tkinter as tk
# Re-exported after the 250-line split, so `from gatelock._outputs import # Re-exported after the 250-line split, so `from gatelock._outputs import
# Output` -- which the tests and sibling modules do -- keeps resolving. # Output` -- which the tests and sibling modules do -- keeps resolving.
__all__ = [ __all__ = [

View File

@ -19,8 +19,7 @@ import signal
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from gatelock._arbiter import Arbiter from gatelock._arbiter import Arbiter, Claim
from gatelock._claims import Claim
from gatelock._config import LockConfig from gatelock._config import LockConfig
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -95,7 +94,7 @@ def maybe_preempt(
this entirely and defaults to off. this entirely and defaults to off.
preempted_pids: Pids already signalled, so each is signalled once. preempted_pids: Pids already signalled, so each is signalled once.
""" """
if not config.grab.preempt_weaker_holder or arbiter is None: if not config.preempt_weaker_holder or arbiter is None:
return return
if holder.rank >= arbiter.claim.rank: if holder.rank >= arbiter.claim.rank:
return return

View File

@ -40,8 +40,7 @@ QUEUE_HEARTBEAT_SECONDS: Final = 300.0
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable from collections.abc import Callable
from gatelock._arbiter import Arbiter from gatelock._arbiter import Arbiter, Claim
from gatelock._claims import Claim
@dataclass(frozen=True) @dataclass(frozen=True)

View File

@ -13,7 +13,6 @@ import logging
from typing import TYPE_CHECKING, Protocol from typing import TYPE_CHECKING, Protocol
from gatelock._output_types import Output, OutputRect from gatelock._output_types import Output, OutputRect
from gatelock._xlib import load_xlib
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Sequence from collections.abc import Sequence
@ -42,27 +41,23 @@ if TYPE_CHECKING:
output: int output: int
class _XRoot(Protocol): class _XRoot(Protocol):
def xrandr_get_screen_resources(self) -> _ScreenResources: def xrandr_get_screen_resources(self) -> _ScreenResources: ...
"""Mirror ``root.xrandr_get_screen_resources()``."""
def xrandr_get_output_primary(self) -> _PrimaryReply: def xrandr_get_output_primary(self) -> _PrimaryReply: ...
"""Mirror ``root.xrandr_get_output_primary()``."""
class _XScreen(Protocol): class _XScreen(Protocol):
root: _XRoot root: _XRoot
class _XDisplay(Protocol): class _XDisplay(Protocol):
def screen(self) -> _XScreen: def screen(self) -> _XScreen: ...
"""Mirror ``Display.screen()``."""
def xrandr_get_output_info(self, output: int, timestamp: int) -> _OutputInfo: def xrandr_get_output_info(
"""Mirror ``Display.xrandr_get_output_info()``.""" self, output: int, timestamp: int
) -> _OutputInfo: ...
def xrandr_get_crtc_info(self, crtc: int, timestamp: int) -> _CrtcInfo: def xrandr_get_crtc_info(self, crtc: int, timestamp: int) -> _CrtcInfo: ...
"""Mirror ``Display.xrandr_get_crtc_info()``."""
def close(self) -> None: def close(self) -> None: ...
"""Mirror ``Display.close()``."""
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -93,15 +88,16 @@ class RandrBackend:
@classmethod @classmethod
def create(cls) -> RandrBackend | None: def create(cls) -> RandrBackend | None:
"""Open an X connection for RandR queries, or None if unavailable.""" """Open an X connection for RandR queries, or None if unavailable."""
modules = load_xlib("Xlib.display") try:
if modules is None: from Xlib import display as xdisplay
except ImportError:
_logger.debug( _logger.debug(
"python-xlib is not installed; RandR events and RandR " "python-xlib is not installed; RandR events and RandR "
"enumeration are unavailable, falling back to xrandr" "enumeration are unavailable, falling back to xrandr"
) )
return None return None
try: try:
return cls(modules[0].Display()) return cls(xdisplay.Display())
except (OSError, ValueError) as exc: except (OSError, ValueError) as exc:
_logger.warning("could not open an X display for RandR: %s", exc) _logger.warning("could not open an X display for RandR: %s", exc)
return None return None

View File

@ -56,7 +56,11 @@ class RecoveryLoop:
def __init__(self, root: tk.Misc, collaborators: RecoveryCollaborators) -> None: def __init__(self, root: tk.Misc, collaborators: RecoveryCollaborators) -> None:
"""Wire the loop to the pieces it re-asserts over.""" """Wire the loop to the pieces it re-asserts over."""
self._root = root self._root = root
self._parts = collaborators self._config = collaborators.config
self._surfaces = collaborators.surfaces
self._enumerator = collaborators.enumerator
self._detector = collaborators.detector
self._hooks = collaborators.hooks
self._running = False self._running = False
self._ticks = 0 self._ticks = 0
self._drain_job: str | None = None self._drain_job: str | None = None
@ -88,26 +92,22 @@ class RecoveryLoop:
"""Queue the next cheap drain tick.""" """Queue the next cheap drain tick."""
if not self._running: if not self._running:
return return
self._drain_job = self._root.after( self._drain_job = self._root.after(self._config.detect_drain_ms, self._drain)
self._parts.config.detect_drain_ms, self._drain
)
def _schedule_verify(self) -> None: def _schedule_verify(self) -> None:
"""Queue the next full verify tick.""" """Queue the next full verify tick."""
if not self._running: if not self._running:
return return
self._verify_job = self._root.after( self._verify_job = self._root.after(self._config.recovery_tick_ms, self._verify)
self._parts.config.recovery_tick_ms, self._verify
)
def _drain(self) -> None: def _drain(self) -> None:
"""Run a full tick only if a push signal arrived. Cheap otherwise.""" """Run a full tick only if a push signal arrived. Cheap otherwise."""
try: try:
if self._parts.detector.take_pending(): if self._detector.take_pending():
_logger.debug("output-change signal received; re-asserting the lock") _logger.debug("output-change signal received; re-asserting the lock")
self.tick() self.tick()
# Same fail-open reasoning as _verify. # Same fail-open reasoning as _verify.
except Exception: # pylint: disable=broad-exception-caught except Exception:
_logger.exception("drain tick raised; the lock loop keeps running") _logger.exception("drain tick raised; the lock loop keeps running")
finally: finally:
self._schedule_drain() self._schedule_drain()
@ -124,7 +124,7 @@ class RecoveryLoop:
""" """
try: try:
self.tick() self.tick()
except Exception: # pylint: disable=broad-exception-caught except Exception:
_logger.exception("verify tick raised; the lock loop keeps running") _logger.exception("verify tick raised; the lock loop keeps running")
finally: finally:
self._schedule_verify() self._schedule_verify()
@ -136,7 +136,7 @@ class RecoveryLoop:
What this pass saw and corrected. What this pass saw and corrected.
""" """
self._ticks += 1 self._ticks += 1
scan = self._parts.enumerator.scan() scan = self._enumerator.scan()
if not scan.ok: if not scan.ok:
# No information is not a reason to change anything. Keep every # No information is not a reason to change anything. Keep every
@ -146,9 +146,9 @@ class RecoveryLoop:
) )
return RecoveryReport(scan_ok=False, source=scan.source) return RecoveryReport(scan_ok=False, source=scan.source)
self._parts.surfaces.update_backdrop() self._surfaces.update_backdrop()
delta = self._parts.surfaces.apply(scan) delta = self._surfaces.apply(scan)
corrected = self._parts.surfaces.enforce() corrected = self._surfaces.enforce()
grab_reasserted = self._reassert_grab() grab_reasserted = self._reassert_grab()
vt_reasserted = self._reassert_vt() vt_reasserted = self._reassert_vt()
if delta.created: if delta.created:
@ -191,7 +191,7 @@ class RecoveryLoop:
Returns: Returns:
True if the grab had to be re-taken. True if the grab had to be re-taken.
""" """
if self._parts.config.resolved_grab() != "global": if self._config.resolved_grab() != "global":
return False return False
if self.holds_grab(): if self.holds_grab():
return False return False
@ -226,8 +226,8 @@ class RecoveryLoop:
that widget the actual Tk focus target. that widget the actual Tk focus target.
""" """
with contextlib.suppress(tk.TclError): with contextlib.suppress(tk.TclError):
index = self._parts.surfaces.preferred_focus_index() index = self._surfaces.preferred_focus_index()
self._parts.hooks.on_focus_ready(self._parts.surfaces.focus_surface(index)) self._hooks.on_focus_ready(self._surfaces.focus_surface(index))
def _reassert_vt(self) -> bool: def _reassert_vt(self) -> bool:
"""Periodically re-disable VT switching. Never re-enables it. """Periodically re-disable VT switching. Never re-enables it.
@ -235,7 +235,7 @@ class RecoveryLoop:
Returns: Returns:
True on ticks where the re-assert ran. True on ticks where the re-assert ran.
""" """
if not self._parts.config.resolved_disable_vt(): if not self._config.resolved_disable_vt():
return False return False
if self._ticks % _VT_REASSERT_EVERY: if self._ticks % _VT_REASSERT_EVERY:
return False return False

View File

@ -80,13 +80,13 @@ class ScrollableSurface:
""" """
self._config = config self._config = config
self._center_when_fits = center_when_fits self._center_when_fits = center_when_fits
self.container = tk.Frame(parent, bg=config.palette.bg) self.container = tk.Frame(parent, bg=config.bg)
self.canvas = tk.Canvas( self.canvas = tk.Canvas(
self.container, self.container,
bg=config.palette.bg, bg=config.bg,
highlightthickness=config.spacing.focus_thickness, highlightthickness=config.focus_thickness,
highlightcolor=config.palette.focus_ring, highlightcolor=config.focus_ring,
highlightbackground=config.palette.bg, highlightbackground=config.bg,
borderwidth=0, borderwidth=0,
# Tk gives Canvas no key bindings, so it is not a focus stop by # Tk gives Canvas no key bindings, so it is not a focus stop by
# default and the viewport becomes pointer-only. Opt in. # default and the viewport becomes pointer-only. Opt in.
@ -111,7 +111,7 @@ class ScrollableSurface:
self.canvas.configure(yscrollcommand=self._scrollbar.set) self.canvas.configure(yscrollcommand=self._scrollbar.set)
self.canvas.pack(side="left", fill="both", expand=True) self.canvas.pack(side="left", fill="both", expand=True)
self.content = tk.Frame(self.canvas, bg=config.palette.bg) self.content = tk.Frame(self.canvas, bg=config.bg)
# anchor="n": top-anchored, so overflow scrolls instead of shearing # anchor="n": top-anchored, so overflow scrolls instead of shearing
# the header and the submit button off opposite edges. # the header and the submit button off opposite edges.
self._content_id = self.canvas.create_window( self._content_id = self.canvas.create_window(

View File

@ -150,9 +150,9 @@ def request_content_size(target: FitTarget) -> None:
""" """
wanted_w = target.content.winfo_reqwidth() wanted_w = target.content.winfo_reqwidth()
wanted_h = target.content.winfo_reqheight() wanted_h = target.content.winfo_reqheight()
bar_w = target.scrollbar.winfo_reqwidth() if target.scrollbar else 0 bar = target.scrollbar.winfo_reqwidth() if target.scrollbar else 0
target.canvas.configure( target.canvas.configure(
width=max(1, min(wanted_w, target.canvas.winfo_screenwidth() - bar_w)), width=max(1, min(wanted_w, target.canvas.winfo_screenwidth() - bar)),
height=max(1, min(wanted_h, target.canvas.winfo_screenheight())), height=max(1, min(wanted_h, target.canvas.winfo_screenheight())),
) )
@ -173,7 +173,7 @@ def report_overflow(target: FitTarget) -> None:
# A viewport Tk has not laid out yet reports 1px, which is not an # 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 # overflow -- reporting it would cry wolf on every startup and teach
# the reader to ignore the one message that matters. # the reader to ignore the one message that matters.
if _UNMAPPED_VIEWPORT_PX < view_h < wanted_h: if view_h > _UNMAPPED_VIEWPORT_PX and wanted_h > view_h:
_logger.warning( _logger.warning(
"lock content overflows its surface: %dpx of content in a " "lock content overflows its surface: %dpx of content in a "
"%dpx viewport (%dpx off-screen); it is reachable only by " "%dpx viewport (%dpx off-screen); it is reachable only by "

View File

@ -117,7 +117,7 @@ class SurfaceSet:
width = self._root.winfo_screenwidth() width = self._root.winfo_screenwidth()
height = self._root.winfo_screenheight() height = self._root.winfo_screenheight()
self._root.geometry(f"{width}x{height}+0+0") self._root.geometry(f"{width}x{height}+0+0")
self._root.configure(bg=self._config.palette.bg, cursor="arrow") self._root.configure(bg=self._config.bg, cursor="arrow")
def apply(self, scan: OutputScan) -> SurfaceDelta: def apply(self, scan: OutputScan) -> SurfaceDelta:
"""Bring the surface set in line with ``scan``. """Bring the surface set in line with ``scan``.
@ -201,7 +201,7 @@ class SurfaceSet:
window.withdraw() window.withdraw()
if self._config.resolved_overrideredirect(): if self._config.resolved_overrideredirect():
window.overrideredirect(boolean=True) window.overrideredirect(boolean=True)
window.configure(bg=self._config.palette.bg, cursor="arrow") window.configure(bg=self._config.bg, cursor="arrow")
set_geometry(window, info.rect) set_geometry(window, info.rect)
if not self._config.resolved_overrideredirect(): if not self._config.resolved_overrideredirect():
window.attributes("-topmost", _TOPMOST_ON) window.attributes("-topmost", _TOPMOST_ON)

View File

@ -1,93 +0,0 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Design tokens for lock surfaces: palette, type scale and spacing scale.
Split from :mod:`gatelock._config` so that :class:`LockConfig` reads as the
handful of behavioural knobs it is, with the visual vocabulary held by three
records an app overrides as a unit -- a palette is swapped whole, never one
colour at a time.
All defaults come from the ``unified-design-system`` docs
(``~/src/utils/unified-design-system/tokens.md``) -- the same palette used by
every one of kuhy's apps, Flutter and web included.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal
TypeRole = Literal["display", "title", "subtitle", "body", "label", "caption"]
SpaceStep = Literal["xs", "sm", "md", "lg", "xl", "xxl"]
@dataclass(frozen=True)
class LockPalette:
"""The colours a lock surface is drawn with.
Attributes:
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.
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.
"""
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"
focus_ring: str = "#B8862E"
@dataclass(frozen=True)
class LockTypography:
"""The font family and the type scale, in **pixels**.
Do not pass the sizes to Tk directly -- use :meth:`LockConfig.font`,
which applies Tk's sign convention (a raw positive value means *points*,
~37% bigger).
"""
font_family: str = "Arial"
display: int = 32
title: int = 24
subtitle: int = 20
body: int = 16
label: int = 14
caption: int = 12
@dataclass(frozen=True)
class LockSpacing:
"""The 4px spacing scale, in pixels, plus the focus-ring width.
Use the steps for ``padx``/``pady``/``ipadx``. ``focus_thickness`` is the
ring width in px -- never set it to 0 on a focusable widget.
"""
xs: int = 4
sm: int = 8
md: int = 16
lg: int = 24
xl: int = 32
xxl: int = 48
focus_thickness: int = 2

View File

@ -42,7 +42,7 @@ def _button_fills(config: LockConfig) -> dict[ButtonVariant, tuple[str, str]]:
variant instead of letting each call site invent its own hex pair. variant instead of letting each call site invent its own hex pair.
""" """
return { return {
"primary": (config.palette.accent, config.palette.on_fill), "primary": (config.accent, config.on_fill),
"secondary": (config.palette.field_bg, config.palette.fg), "secondary": (config.field_bg, config.fg),
"danger": (config.palette.danger, config.palette.on_fill), "danger": (config.danger, config.on_fill),
} }

View File

@ -103,27 +103,25 @@ class LockWindow:
self._closed = False self._closed = False
self._focus_notified = False self._focus_notified = False
self._preempted_pids: set[int] = set() self._preempted_pids: set[int] = set()
surfaces = SurfaceSet(root, config, hooks) self._surfaces = SurfaceSet(root, config, hooks)
enumerator = OutputEnumerator(root) self._enumerator = OutputEnumerator(root)
detector = OutputChangeDetector(root) self._detector = OutputChangeDetector(root)
recovery = RecoveryLoop( self._recovery = RecoveryLoop(
root, root,
RecoveryCollaborators( RecoveryCollaborators(
config=config, config=config,
surfaces=surfaces, surfaces=self._surfaces,
enumerator=enumerator, enumerator=self._enumerator,
detector=detector, detector=self._detector,
hooks=hooks, hooks=hooks,
), ),
) )
# The arming bundle is also where the window reaches its
# collaborators afterwards; it is the one owner of those four.
self._arming = _arming.ArmingCollaborators( self._arming = _arming.ArmingCollaborators(
config=config, config=config,
surfaces=surfaces, surfaces=self._surfaces,
enumerator=enumerator, enumerator=self._enumerator,
detector=detector, detector=self._detector,
recovery=recovery, recovery=self._recovery,
notify_focus_ready=self._notify_focus_ready, notify_focus_ready=self._notify_focus_ready,
log_grab_blocked=self._log_grab_blocked, log_grab_blocked=self._log_grab_blocked,
) )
@ -131,7 +129,7 @@ class LockWindow:
@property @property
def surfaces(self) -> SurfaceSet: def surfaces(self) -> SurfaceSet:
"""The live surface set, for apps that need to fan work out over it.""" """The live surface set, for apps that need to fan work out over it."""
return self._arming.surfaces return self._surfaces
# -- window mechanics ----------------------------------------------------- # -- window mechanics -----------------------------------------------------
@ -181,8 +179,8 @@ class LockWindow:
return return
self._focus_notified = True self._focus_notified = True
with contextlib.suppress(tk.TclError): with contextlib.suppress(tk.TclError):
index = self._arming.surfaces.preferred_focus_index() index = self._surfaces.preferred_focus_index()
self._hooks.on_focus_ready(self._arming.surfaces.focus_surface(index)) self._hooks.on_focus_ready(self._surfaces.focus_surface(index))
# -- lifecycle -------------------------------------------------------- # -- lifecycle --------------------------------------------------------
@ -224,15 +222,15 @@ class LockWindow:
if self._closed: if self._closed:
return return
self._closed = True self._closed = True
self._arming.recovery.stop() self._recovery.stop()
self._arming.detector.stop() self._detector.stop()
self._hooks.on_close() self._hooks.on_close()
self._restore_vt() self._restore_vt()
if self._arbiter is not None: if self._arbiter is not None:
self._arbiter.release() self._arbiter.release()
self._arming.enumerator.close() self._enumerator.close()
with contextlib.suppress(tk.TclError): with contextlib.suppress(tk.TclError):
self._arming.surfaces.destroy_all() self._surfaces.destroy_all()
with contextlib.suppress(tk.TclError): with contextlib.suppress(tk.TclError):
self.root.destroy() self.root.destroy()

View File

@ -1,33 +0,0 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Loading the optional ``python-xlib`` dependency, in one place.
``python-xlib`` is optional: without it, output detection falls back to Tk
``<Configure>`` events plus ``xrandr`` polling. The fallback is the path that
must stay tested, and a module-scope ``try/except ImportError`` would resolve
it once at import time, leaving the ``except`` arm permanently unreachable for
branch coverage. So the modules are loaded on demand, through :mod:`importlib`,
by the two call sites that need them.
"""
from __future__ import annotations
import importlib
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from types import ModuleType
def load_xlib(*names: str) -> tuple[ModuleType, ...] | None:
"""Import the named ``Xlib`` modules, or None if python-xlib is unavailable.
Args:
names: Fully-qualified module names, e.g. ``"Xlib.display"``.
Returns:
The modules in the order asked for, or None on the first ImportError.
"""
try:
return tuple(importlib.import_module(name) for name in names)
except ImportError:
return None

View File

@ -18,14 +18,11 @@ from gatelock._arbiter import (
RANK_SCREEN_LOCKER, RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM, RANK_WAKE_ALARM,
Arbiter, Arbiter,
)
from gatelock._claims import (
Claim, Claim,
_same_file,
_try_lock,
default_runtime_dir, default_runtime_dir,
grab_strength, grab_strength,
) )
from gatelock._claims import _same_file, _try_lock
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterator from collections.abc import Iterator

View File

@ -18,8 +18,8 @@ from gatelock._arbiter import (
RANK_SCREEN_LOCKER, RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM, RANK_WAKE_ALARM,
Arbiter, Arbiter,
Claim,
) )
from gatelock._claims import Claim
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterator from collections.abc import Iterator

View File

@ -18,8 +18,8 @@ from gatelock._arbiter import (
RANK_SCREEN_LOCKER, RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM, RANK_WAKE_ALARM,
Arbiter, Arbiter,
Claim,
) )
from gatelock._claims import Claim
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterator from collections.abc import Iterator

View File

@ -122,7 +122,7 @@ class TestScheduling:
"""No change signal means no full pass.""" """No change signal means no full pass."""
recovery, enumerator, _surfaces = loop recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH enumerator.scan.return_value = BOTH
recovery._parts.detector.take_pending.return_value = False recovery._detector.take_pending.return_value = False
recovery._running = True recovery._running = True
recovery._drain() recovery._drain()
enumerator.scan.assert_not_called() enumerator.scan.assert_not_called()
@ -133,7 +133,7 @@ class TestScheduling:
"""A pending change triggers a full pass.""" """A pending change triggers a full pass."""
recovery, enumerator, _surfaces = loop recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH enumerator.scan.return_value = BOTH
recovery._parts.detector.take_pending.return_value = True recovery._detector.take_pending.return_value = True
recovery._running = True recovery._running = True
recovery._drain() recovery._drain()
enumerator.scan.assert_called_once_with() enumerator.scan.assert_called_once_with()
@ -172,7 +172,7 @@ class TestScheduling:
"""Same for the cheap cadence.""" """Same for the cheap cadence."""
recovery, enumerator, _surfaces = loop recovery, enumerator, _surfaces = loop
enumerator.scan.side_effect = RuntimeError("boom") enumerator.scan.side_effect = RuntimeError("boom")
recovery._parts.detector.take_pending.return_value = True recovery._detector.take_pending.return_value = True
recovery._running = True recovery._running = True
with caplog.at_level(logging.ERROR): with caplog.at_level(logging.ERROR):
recovery._drain() recovery._drain()

View File

@ -7,7 +7,6 @@ from unittest.mock import MagicMock
import pytest import pytest
from gatelock._config import GrabPolicy
from gatelock._outputs import Output, OutputRect, OutputScan from gatelock._outputs import Output, OutputRect, OutputScan
from gatelock._surfaces import ( from gatelock._surfaces import (
SurfaceSet, SurfaceSet,
@ -42,14 +41,9 @@ class TestNeedsBackdropRoot:
[ [
(LockConfig(mode="hard"), True), (LockConfig(mode="hard"), True),
(LockConfig(mode="soft"), False), (LockConfig(mode="soft"), False),
(LockConfig(mode="soft", grab=GrabPolicy(kind="global")), True), (LockConfig(mode="soft", grab="global"), True),
(LockConfig(mode="soft", grab=GrabPolicy(kind="local")), True), (LockConfig(mode="soft", grab="local"), True),
( (LockConfig(mode="hard", overrideredirect=False, grab="none"), False),
LockConfig(
mode="hard", overrideredirect=False, grab=GrabPolicy(kind="none")
),
False,
),
], ],
) )
def test_predicate(self, config: LockConfig, *, expected: bool) -> None: def test_predicate(self, config: LockConfig, *, expected: bool) -> None:

View File

@ -125,7 +125,7 @@ def test_every_variant_draws_text_on_its_own_fill(
fill = button.cget("bg") fill = button.cget("bg")
text_color = button.cget("fg") text_color = button.cget("fg")
expected = config.palette.fg if variant == "secondary" else config.palette.on_fill expected = config.fg if variant == "secondary" else config.on_fill
assert text_color == expected assert text_color == expected
assert fill != text_color assert fill != text_color
@ -137,8 +137,8 @@ def test_every_variant_has_a_visible_focus_ring(
"""Tk's default ring is 1px black -- invisible on this palette.""" """Tk's default ring is 1px black -- invisible on this palette."""
button = make_button(root, config, "Go", lambda: None, ButtonStyle(variant=variant)) button = make_button(root, config, "Go", lambda: None, ButtonStyle(variant=variant))
assert int(button.cget("highlightthickness")) == config.spacing.focus_thickness assert int(button.cget("highlightthickness")) == config.focus_thickness
assert str(button.cget("highlightcolor")) == config.palette.focus_ring assert str(button.cget("highlightcolor")) == config.focus_ring
def test_primary_reads_larger_than_the_other_variants( def test_primary_reads_larger_than_the_other_variants(
@ -168,7 +168,7 @@ def test_the_active_fill_is_lighter_than_the_resting_fill(
"""Hover feedback is a lighter fill, not a glow shadow.""" """Hover feedback is a lighter fill, not a glow shadow."""
button = make_button(root, config, "Go", lambda: None) button = make_button(root, config, "Go", lambda: None)
assert button.cget("activebackground") == _lighten(config.palette.accent) assert button.cget("activebackground") == _lighten(config.accent)
assert button.cget("activebackground") != button.cget("bg") assert button.cget("activebackground") != button.cget("bg")
@ -185,7 +185,7 @@ def test_heading_uses_the_accent_and_returns_the_label(
label = heading(root, config, "Right now") label = heading(root, config, "Right now")
assert label.cget("text") == "Right now" assert label.cget("text") == "Right now"
assert str(label.cget("fg")) == config.palette.accent assert str(label.cget("fg")) == config.accent
assert label.winfo_manager() == "pack" assert label.winfo_manager() == "pack"
@ -193,15 +193,15 @@ def test_row_defaults_to_the_body_foreground(root: tk.Tk, config: LockConfig) ->
"""An uncoloured row is ordinary text, not a status.""" """An uncoloured row is ordinary text, not a status."""
label = row(root, config, "Earned all-time: 3") label = row(root, config, "Earned all-time: 3")
assert str(label.cget("fg")) == config.palette.fg assert str(label.cget("fg")) == config.fg
assert int(label.cget("wraplength")) == DEFAULT_WRAP assert int(label.cget("wraplength")) == DEFAULT_WRAP
def test_row_honours_an_explicit_status_colour(root: tk.Tk, config: LockConfig) -> None: def test_row_honours_an_explicit_status_colour(root: tk.Tk, config: LockConfig) -> None:
"""Status colours are load-bearing, so a caller can set one.""" """Status colours are load-bearing, so a caller can set one."""
label = row(root, config, "LOCKED", RowStyle(color=config.palette.danger)) label = row(root, config, "LOCKED", RowStyle(color=config.danger))
assert str(label.cget("fg")) == config.palette.danger assert str(label.cget("fg")) == config.danger
def test_row_wraps_at_the_width_it_is_given(root: tk.Tk, config: LockConfig) -> None: def test_row_wraps_at_the_width_it_is_given(root: tk.Tk, config: LockConfig) -> None:

View File

@ -6,8 +6,6 @@ from __future__ import annotations
import tkinter as tk import tkinter as tk
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from gatelock._config import GrabPolicy
from gatelock._theme import LockPalette
from gatelock._window import LockConfig from gatelock._window import LockConfig
from gatelock.tests.conftest import make_window from gatelock.tests.conftest import make_window
@ -31,9 +29,7 @@ class TestLockConfigResolution:
def test_explicit_overrides_win_over_mode(self) -> None: def test_explicit_overrides_win_over_mode(self) -> None:
"""Explicit fields override the mode preset (screen-locker demo case).""" """Explicit fields override the mode preset (screen-locker demo case)."""
config = LockConfig( config = LockConfig(mode="soft", overrideredirect=True, grab="local")
mode="soft", overrideredirect=True, grab=GrabPolicy(kind="local")
)
assert config.resolved_overrideredirect() is True assert config.resolved_overrideredirect() is True
assert config.resolved_grab() == "local" assert config.resolved_grab() == "local"
assert config.resolved_disable_vt() is False assert config.resolved_disable_vt() is False
@ -41,9 +37,7 @@ class TestLockConfigResolution:
def test_explicit_false_overrides_hard_mode(self) -> None: def test_explicit_false_overrides_hard_mode(self) -> None:
"""An explicit False/none is respected even under mode="hard".""" """An explicit False/none is respected even under mode="hard"."""
config = LockConfig( config = LockConfig(
mode="hard", mode="hard", overrideredirect=False, grab="none", disable_vt=False
overrideredirect=False,
grab=GrabPolicy(kind="none", disable_vt=False),
) )
assert config.resolved_overrideredirect() is False assert config.resolved_overrideredirect() is False
assert config.resolved_grab() == "none" assert config.resolved_grab() == "none"
@ -92,7 +86,7 @@ class TestSetup:
def test_uses_configured_background(self, mock_root: MagicMock) -> None: def test_uses_configured_background(self, mock_root: MagicMock) -> None:
"""The configured bg color is passed to root.configure.""" """The configured bg color is passed to root.configure."""
window, _hooks = make_window( window, _hooks = make_window(
mock_root, config=LockConfig(mode="soft", palette=LockPalette(bg="#000000")) mock_root, config=LockConfig(mode="soft", bg="#000000")
) )
window.setup() window.setup()
@ -110,7 +104,7 @@ class TestGrabInput:
def test_global_grab_dispatches_to_acquire(self, mock_root: MagicMock) -> None: def test_global_grab_dispatches_to_acquire(self, mock_root: MagicMock) -> None:
"""grab="global" triggers the retry-aware acquisition path.""" """grab="global" triggers the retry-aware acquisition path."""
window, _hooks = make_window( window, _hooks = make_window(
mock_root, config=LockConfig(mode="soft", grab=GrabPolicy(kind="global")) mock_root, config=LockConfig(mode="soft", grab="global")
) )
with patch("gatelock._arming.acquire_global_grab") as mock_acquire: with patch("gatelock._arming.acquire_global_grab") as mock_acquire:
@ -122,7 +116,7 @@ class TestGrabInput:
def test_local_grab_calls_grab_set(self, mock_root: MagicMock) -> None: def test_local_grab_calls_grab_set(self, mock_root: MagicMock) -> None:
"""grab="local" calls grab_set directly, no retry logic.""" """grab="local" calls grab_set directly, no retry logic."""
window, _hooks = make_window( window, _hooks = make_window(
mock_root, config=LockConfig(mode="soft", grab=GrabPolicy(kind="local")) mock_root, config=LockConfig(mode="soft", grab="local")
) )
window.grab_input() window.grab_input()
@ -133,7 +127,7 @@ class TestGrabInput:
"""A TclError from grab_set (e.g. window already gone) is swallowed.""" """A TclError from grab_set (e.g. window already gone) is swallowed."""
mock_root.grab_set.side_effect = tk.TclError("gone") mock_root.grab_set.side_effect = tk.TclError("gone")
window, _hooks = make_window( window, _hooks = make_window(
mock_root, config=LockConfig(mode="soft", grab=GrabPolicy(kind="local")) mock_root, config=LockConfig(mode="soft", grab="local")
) )
window.grab_input() # must not raise window.grab_input() # must not raise
@ -141,7 +135,7 @@ class TestGrabInput:
def test_none_grab_takes_no_grab_action(self, mock_root: MagicMock) -> None: def test_none_grab_takes_no_grab_action(self, mock_root: MagicMock) -> None:
"""grab="none" calls neither grab_set nor grab_set_global.""" """grab="none" calls neither grab_set nor grab_set_global."""
window, _hooks = make_window( window, _hooks = make_window(
mock_root, config=LockConfig(mode="soft", grab=GrabPolicy(kind="none")) mock_root, config=LockConfig(mode="soft", grab="none")
) )
window.grab_input() window.grab_input()

View File

@ -9,7 +9,6 @@ from __future__ import annotations
import tkinter as tk import tkinter as tk
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from gatelock._config import GrabPolicy
from gatelock._window import LockConfig from gatelock._window import LockConfig
from gatelock.tests.conftest import make_window from gatelock.tests.conftest import make_window
@ -42,7 +41,7 @@ class TestAcquireGlobalGrab:
"""grab_retry_ms=0 falls back to a local grab on the first failure.""" """grab_retry_ms=0 falls back to a local grab on the first failure."""
mock_root.grab_set_global.side_effect = tk.TclError("held by another client") mock_root.grab_set_global.side_effect = tk.TclError("held by another client")
window, _hooks = make_window( window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab=GrabPolicy(retry_ms=0)) mock_root, config=LockConfig(mode="hard", grab_retry_ms=0)
) )
window._acquire_global_grab(attempt=1) window._acquire_global_grab(attempt=1)
@ -57,7 +56,7 @@ class TestAcquireGlobalGrab:
mock_root.grab_set_global.side_effect = tk.TclError("held") mock_root.grab_set_global.side_effect = tk.TclError("held")
mock_root.grab_set.side_effect = tk.TclError("also gone") mock_root.grab_set.side_effect = tk.TclError("also gone")
window, _hooks = make_window( window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab=GrabPolicy(retry_ms=0)) mock_root, config=LockConfig(mode="hard", grab_retry_ms=0)
) )
window._acquire_global_grab(attempt=1) # must not raise window._acquire_global_grab(attempt=1) # must not raise
@ -81,7 +80,7 @@ class TestAcquireGlobalGrab:
"""A warning is logged only when attempt is a multiple of grab_log_every.""" """A warning is logged only when attempt is a multiple of grab_log_every."""
mock_root.grab_set_global.side_effect = tk.TclError("held") mock_root.grab_set_global.side_effect = tk.TclError("held")
window, _hooks = make_window( window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab=GrabPolicy(log_every=5)) mock_root, config=LockConfig(mode="hard", grab_log_every=5)
) )
with patch("gatelock._preempt._logger") as mock_logger: with patch("gatelock._preempt._logger") as mock_logger:
@ -96,7 +95,7 @@ class TestAcquireGlobalGrab:
"""An explicit positive grab_retry_ms is used as the reschedule delay.""" """An explicit positive grab_retry_ms is used as the reschedule delay."""
mock_root.grab_set_global.side_effect = tk.TclError("held") mock_root.grab_set_global.side_effect = tk.TclError("held")
window, _hooks = make_window( window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab=GrabPolicy(retry_ms=50)) mock_root, config=LockConfig(mode="hard", grab_retry_ms=50)
) )
window._acquire_global_grab(attempt=1) window._acquire_global_grab(attempt=1)

View File

@ -8,9 +8,8 @@ from unittest.mock import MagicMock, patch
from gatelock._arbiter import ( from gatelock._arbiter import (
RANK_DIET_GUARD, RANK_DIET_GUARD,
RANK_SCREEN_LOCKER, RANK_SCREEN_LOCKER,
Claim,
) )
from gatelock._claims import Claim
from gatelock._config import GrabPolicy
from gatelock._detect import _RandrEventSource from gatelock._detect import _RandrEventSource
from gatelock._outputs import Output, OutputRect from gatelock._outputs import Output, OutputRect
from gatelock._window import LockConfig from gatelock._window import LockConfig
@ -85,10 +84,7 @@ class TestGrabBlockedLogging:
instance_id="t", instance_id="t",
) )
window, _hooks = make_window( window, _hooks = make_window(
mock_root, mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=False)
config=LockConfig(
mode="hard", grab=GrabPolicy(preempt_weaker_holder=False)
),
) )
window._arbiter = arbiter window._arbiter = arbiter
with patch("gatelock._preempt._logger") as logger: with patch("gatelock._preempt._logger") as logger:

View File

@ -15,9 +15,8 @@ from gatelock._arbiter import (
RANK_DIET_GUARD, RANK_DIET_GUARD,
RANK_SCREEN_LOCKER, RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM, RANK_WAKE_ALARM,
Claim,
) )
from gatelock._claims import Claim
from gatelock._config import GrabPolicy
from gatelock._detect import _RandrEventSource from gatelock._detect import _RandrEventSource
from gatelock._outputs import Output, OutputRect from gatelock._outputs import Output, OutputRect
from gatelock._window import LockConfig from gatelock._window import LockConfig
@ -65,8 +64,7 @@ class TestPreemptWeakerHolder:
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075 our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
) )
window, _hooks = make_window( window, _hooks = make_window(
mock_root, mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
) )
window._arbiter = arbiter window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill: with patch("gatelock._preempt.os.kill") as kill:
@ -78,8 +76,7 @@ class TestPreemptWeakerHolder:
our_rank=RANK_DIET_GUARD, holder_rank=RANK_SCREEN_LOCKER, holder_pid=4137 our_rank=RANK_DIET_GUARD, holder_rank=RANK_SCREEN_LOCKER, holder_pid=4137
) )
window, _hooks = make_window( window, _hooks = make_window(
mock_root, mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
) )
window._arbiter = arbiter window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill: with patch("gatelock._preempt.os.kill") as kill:
@ -91,8 +88,7 @@ class TestPreemptWeakerHolder:
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075 our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
) )
window, _hooks = make_window( window, _hooks = make_window(
mock_root, mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
) )
window._arbiter = arbiter window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill: with patch("gatelock._preempt.os.kill") as kill:
@ -105,10 +101,7 @@ class TestPreemptWeakerHolder:
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075 our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
) )
window, _hooks = make_window( window, _hooks = make_window(
mock_root, mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=False)
config=LockConfig(
mode="hard", grab=GrabPolicy(preempt_weaker_holder=False)
),
) )
window._arbiter = arbiter window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill: with patch("gatelock._preempt.os.kill") as kill:
@ -135,8 +128,7 @@ class TestPreemptWeakerHolder:
def test_no_arbiter_means_no_preemption(self, mock_root: MagicMock) -> None: def test_no_arbiter_means_no_preemption(self, mock_root: MagicMock) -> None:
window, _hooks = make_window( window, _hooks = make_window(
mock_root, mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
) )
with patch("gatelock._preempt.os.kill") as kill: with patch("gatelock._preempt.os.kill") as kill:
_preempt.maybe_preempt( _preempt.maybe_preempt(
@ -162,8 +154,7 @@ class TestPreemptWeakerHolder:
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075 our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
) )
window, _hooks = make_window( window, _hooks = make_window(
mock_root, mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
) )
window._arbiter = arbiter window._arbiter = arbiter
with ( with (
@ -180,8 +171,7 @@ class TestPreemptWeakerHolder:
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075 our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
) )
window, _hooks = make_window( window, _hooks = make_window(
mock_root, mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
) )
window._arbiter = arbiter window._arbiter = arbiter
with ( with (

View File

@ -167,8 +167,8 @@ def heading(parent: tk.Misc, config: LockConfig, text: str) -> tk.Label:
parent, parent,
text=text, text=text,
font=config.font("body", bold=True), font=config.font("body", bold=True),
fg=config.palette.accent, fg=config.accent,
bg=config.palette.bg, bg=config.bg,
anchor="w", anchor="w",
) )
label.pack( label.pack(
@ -212,8 +212,8 @@ def row(
parent, parent,
text=text, text=text,
font=config.font(role), font=config.font(role),
fg=color if color is not None else config.palette.fg, fg=color if color is not None else config.fg,
bg=config.palette.bg, bg=config.bg,
anchor="w", anchor="w",
justify="left", justify="left",
wraplength=max(_MIN_WRAP, wrap), wraplength=max(_MIN_WRAP, wrap),

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "gatelock" name = "gatelock"
version = "0.8.0" version = "0.7.3"
description = "Shared per-output lock-window + HMAC log-integrity backend for blocking-overlay apps" description = "Shared per-output lock-window + HMAC log-integrity backend for blocking-overlay apps"
requires-python = ">=3.14" requires-python = ">=3.14"
dependencies = [] # pure stdlib — tkinter is bundled with Python dependencies = [] # pure stdlib — tkinter is bundled with Python
@ -95,40 +95,16 @@ color_output = true
exclude = [".venv/"] exclude = [".venv/"]
[tool.pylint.main] [tool.pylint.main]
# pre-commit runs from the monorepo root (~/src/utils), so the package dir
# goes on the path for `import gatelock` to resolve the same way it does
# under pytest -- otherwise pylint reports import-error for the package's
# own modules.
init-hook = "import sys; sys.path.insert(0, 'gatelock')"
analyse-fallback-blocks = true analyse-fallback-blocks = true
persistent = true persistent = true
jobs = 0 jobs = 0
py-version = "3.14" py-version = "3.14"
ignore = [".venv", "__pycache__"] ignore = [".venv", "__pycache__"]
# Test suites intentionally use patterns (protected-access, fixture-arg
# shadowing) that don't apply to source code; ruff's per-file-ignores carry
# the equivalent exemptions, so tests stay linted -- by ruff. This is the same
# source-only pylint scope wake-alarm / diet-guard / testsAndMisc use. It has
# to be `ignore-paths`, not `ignore = ["tests"]`: `ignore` only matches the
# basename of what pylint is *given*, and pre-commit hands it explicit file
# paths, so a directory name in `ignore` never fires under the hook.
ignore-paths = ["^(.*/)?tests/.*$"]
ignore-patterns = [".*\\.pyi$"] ignore-patterns = [".*\\.pyi$"]
[tool.pylint.messages_control] [tool.pylint.messages_control]
enable = "all" enable = "all"
# Globally disabled checks, matching wake-alarm / diet-guard: each is a disable = []
# stylistic preference that conflicts with deliberate, clearer code.
# Everything else stays at max strictness.
disable = [
# use-implicit-booleaness family (C1803/C1804/C1805): pylint wants
# `not x` / `not s` instead of `x == 0` / `s == ""`. Explicit comparisons
# against 0 and "" state numeric/string intent more clearly than truthiness
# (and are not equivalent when the value may be None), so we keep them.
"use-implicit-booleaness-not-comparison",
"use-implicit-booleaness-not-comparison-to-string",
"use-implicit-booleaness-not-comparison-to-zero",
]
[tool.pylint.design] [tool.pylint.design]
min-public-methods = 0 min-public-methods = 0