Compare commits

..

3 Commits

Author SHA1 Message Date
68ec316b28 gatelock 0.8.0: LockConfig as behaviour + GrabPolicy + theme records; pylint at 10
Some checks failed
dependency freshness / dependencies on newest stable (push) Waiting to run
file length / file-length (push) Waiting to run
gatelock pre-commit / pre-commit (push) Waiting to run
gatelock tests / test (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
freedays pre-commit / pre-commit (push) Has been cancelled
freedays tests / test (push) Has been cancelled
LockConfig was one 35-field record: the lock's behaviour, the grab
policy, nine colours, a type scale and a spacing scale, flat. It is
now the seven behavioural knobs plus four nested records --
GrabPolicy(kind, disable_vt, retry_ms, log_every, preempt_weaker_holder),
LockPalette, LockTypography and LockSpacing -- each overridden as a
unit. Breaking for every constructor that passed grab=/disable_vt=/
grab_retry_ms=/preempt_weaker_holder= or a colour, and for every read
of config.<colour>; hence the minor bump. screen-locker, leetcode-guard
and diet-guard follow in their own commits.

The two fail-open guards in the recovery loop carry per-line
suppressions: catching everything is the property they exist for, and
the check stays live for the next careless except. That was the last
finding, so the gate now says 10.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHCbkJWXHjtTUaqvnHRAqA
2026-09-12 19:36:31 +02:00
8128851e0b freedays: pylint --fail-under=10, scoped to source, on pylint 4.0.8
The three import-error findings were the hook not having crdt-sync in
its own venv; it is now pinned there as in pyproject.toml. The one
source finding is the background sync's documented fail-open net, which
must catch everything by design, so it carries the one suppression.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHCbkJWXHjtTUaqvnHRAqA
2026-09-12 19:32:20 +02:00
1723df3885 gatelock: scope pylint to source on 4.0.8 and clear the residue it grades
Same config move as crdt-sync (ignore-paths, init-hook, the three
implicit-booleaness disables the reference repos carry). The gate stays
at 8.0 for now: LockConfig's 35-field record and the two fail-open
guards in the recovery loop are still open.

Everything else pylint had left on source is gone. The optional
python-xlib dependency is loaded through one importlib helper instead
of two function-scope import statements, keeping the "not installed"
arm reachable for branch coverage; RecoveryLoop and LockWindow hold
their collaborator bundles rather than unpacking them into a second
set of attributes; the claim types are imported from _claims, where
they are defined, so _arbiter no longer needs an export list that
mirrored the package's; runtime imports sit above TYPE_CHECKING
blocks; the RandR Protocol stubs say which Xlib call they mirror.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHCbkJWXHjtTUaqvnHRAqA
2026-09-12 19:15:39 +02:00
35 changed files with 408 additions and 244 deletions

View File

@ -101,15 +101,18 @@ repos:
- --disable-error-code=list-item
- repo: https://github.com/pylint-dev/pylint
rev: v3.3.2
rev: v4.0.8
hooks:
- id: pylint
args:
- --rcfile=freedays/pyproject.toml
- --fail-under=8.0
- --fail-under=10
- --jobs=4
additional_dependencies:
- 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
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.
_logger.debug("free-day sync skipped: %s", exc)
return False
except Exception:
except Exception: # pylint: disable=broad-exception-caught
_logger.exception("free-day sync failed unexpectedly")
return False
return True

View File

@ -90,11 +90,22 @@ color_output = true
exclude = [".venv/"]
[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
persistent = true
jobs = 0
py-version = "3.14"
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$"]
[tool.pylint.messages_control]

View File

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

View File

@ -55,9 +55,11 @@ class MyGate:
`LockConfig`'s `mode` preset bundles the common combination ("soft" = topmost
only, typeable, WM-escapable; "hard" = overrideredirect + global grab +
VT-disable). Each axis (`overrideredirect`, `grab`, `disable_vt`,
`grab_retry_ms`) can be set explicitly to reproduce a consumer's exact prior
behavior where it diverges from the preset.
VT-disable). `overrideredirect` and the `grab=GrabPolicy(kind=..., disable_vt=...,
retry_ms=...)` axes can be set explicitly to reproduce a consumer's exact prior
behavior where it diverges from the preset. Colours, type scale and spacing are
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
projects; `DEFAULT_HMAC_KEY_FILE` (`/etc/workout-locker/hmac.key`) is

View File

@ -13,11 +13,9 @@ from gatelock._arbiter import (
RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM,
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._escape import (
EscapeDraft,
@ -56,6 +54,7 @@ from gatelock._surfaces import (
mirror_text_widgets,
needs_backdrop_root,
)
from gatelock._theme import LockPalette, LockSpacing, LockTypography
from gatelock._vt import disable_vt_switching, restore_vt_switching
from gatelock._window import (
LockConfig,
@ -95,7 +94,11 @@ __all__ = [
"EscapeTracker",
"FitResult",
"GateRoot",
"GrabPolicy",
"LockConfig",
"LockPalette",
"LockSpacing",
"LockTypography",
"LockWindow",
"LockWindowHooks",
"Output",

View File

@ -42,7 +42,6 @@ from gatelock._claims import (
Claim,
_try_lock,
default_runtime_dir,
grab_strength,
live_claims,
read_claim_if_held,
)
@ -52,20 +51,6 @@ if TYPE_CHECKING:
_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_SCREEN_LOCKER: Final = 200
RANK_DIET_GUARD: Final = 100

View File

@ -157,7 +157,7 @@ def acquire_global_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
retry_ms = collab.config.grab.retry_ms
try:
root.grab_set_global()
except tk.TclError:
@ -167,7 +167,7 @@ def acquire_global_grab(
root.grab_set()
return
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)
root.after(
effective_retry_ms,

View File

@ -13,38 +13,37 @@ import LockConfig`` keeps working for the modules and tests that already do.
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import Literal
from gatelock import _density
from gatelock._arbiter import RANK_SCREEN_LOCKER
from gatelock._theme import (
LockPalette,
LockSpacing,
LockTypography,
SpaceStep,
TypeRole,
)
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.
class GrabPolicy:
"""How the lock takes and keeps the input grab.
Each field left as ``None`` is derived from ``mode``; an explicit value
always overrides the preset for that one axis.
Each field left as ``None`` is derived from :attr:`LockConfig.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.
kind: 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
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.
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
@ -56,82 +55,55 @@ class LockConfig:
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.
"""
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
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
(``~/src/utils/unified-design-system/tokens.md``) -- the same palette used by
every one of kuhy's apps, Flutter and web included.
palette: Colours; see :class:`gatelock._theme.LockPalette`.
typography: Font family and type scale;
see :class:`gatelock._theme.LockTypography`.
spacing: Spacing scale and focus-ring width;
see :class:`gatelock._theme.LockSpacing`.
"""
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
grab: GrabPolicy = field(default_factory=GrabPolicy)
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
palette: LockPalette = field(default_factory=LockPalette)
typography: LockTypography = field(default_factory=LockTypography)
spacing: LockSpacing = field(default_factory=LockSpacing)
def type_px(self, role: TypeRole = "body") -> int:
"""Return the type-scale size for ``role``, in pixels.
@ -141,14 +113,14 @@ class LockConfig:
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}")))
return _density.scale_type(int(getattr(self.typography, 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}")))
return _density.scale_space(int(getattr(self.spacing, step)))
def font(
self,
@ -171,7 +143,7 @@ class LockConfig:
Args:
role: Type-scale role.
bold: Append Tk's ``"bold"`` weight.
family: Override the font family. Defaults to ``font_family``.
family: Override the font family. Defaults to the typography's.
scale: Multiplier for display-only emphasis (e.g. an oversized
countdown). Kept explicit so outliers are visible rather than
hidden behind a fresh literal.
@ -180,7 +152,7 @@ class LockConfig:
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
name = family if family is not None else self.typography.font_family
return (name, -px, "bold") if bold else (name, -px)
def focus_kwargs(self) -> dict[str, str | int]:
@ -192,9 +164,9 @@ class LockConfig:
black-on-``bg``, which reads as no ring at all.
"""
return {
"highlightcolor": self.focus_ring,
"highlightbackground": self.bg,
"highlightthickness": self.focus_thickness,
"highlightcolor": self.palette.focus_ring,
"highlightbackground": self.palette.bg,
"highlightthickness": self.spacing.focus_thickness,
}
def resolved_overrideredirect(self) -> bool:
@ -205,12 +177,12 @@ class LockConfig:
def resolved_grab(self) -> GrabKind:
"""Return the effective grab strategy."""
if self.grab is not None:
return self.grab
if self.grab.kind is not None:
return self.grab.kind
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
if self.grab.disable_vt is not None:
return self.grab.disable_vt
return self.mode == "hard"

View File

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

View File

@ -31,11 +31,6 @@ import json
import logging
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 (
EscapeDraft,
EscapeHistory,
@ -43,6 +38,10 @@ from gatelock._escape_types import (
_parse_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__)

View File

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

View File

@ -19,7 +19,8 @@ import signal
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from gatelock._arbiter import Arbiter, Claim
from gatelock._arbiter import Arbiter
from gatelock._claims import Claim
from gatelock._config import LockConfig
_logger = logging.getLogger(__name__)
@ -94,7 +95,7 @@ def maybe_preempt(
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:
if not config.grab.preempt_weaker_holder or arbiter is None:
return
if holder.rank >= arbiter.claim.rank:
return

View File

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

View File

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

View File

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

View File

@ -80,13 +80,13 @@ class ScrollableSurface:
"""
self._config = config
self._center_when_fits = center_when_fits
self.container = tk.Frame(parent, bg=config.bg)
self.container = tk.Frame(parent, bg=config.palette.bg)
self.canvas = tk.Canvas(
self.container,
bg=config.bg,
highlightthickness=config.focus_thickness,
highlightcolor=config.focus_ring,
highlightbackground=config.bg,
bg=config.palette.bg,
highlightthickness=config.spacing.focus_thickness,
highlightcolor=config.palette.focus_ring,
highlightbackground=config.palette.bg,
borderwidth=0,
# Tk gives Canvas no key bindings, so it is not a focus stop by
# default and the viewport becomes pointer-only. Opt in.
@ -111,7 +111,7 @@ class ScrollableSurface:
self.canvas.configure(yscrollcommand=self._scrollbar.set)
self.canvas.pack(side="left", fill="both", expand=True)
self.content = tk.Frame(self.canvas, bg=config.bg)
self.content = tk.Frame(self.canvas, bg=config.palette.bg)
# anchor="n": top-anchored, so overflow scrolls instead of shearing
# the header and the submit button off opposite edges.
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_h = target.content.winfo_reqheight()
bar = target.scrollbar.winfo_reqwidth() if target.scrollbar else 0
bar_w = target.scrollbar.winfo_reqwidth() if target.scrollbar else 0
target.canvas.configure(
width=max(1, min(wanted_w, target.canvas.winfo_screenwidth() - bar)),
width=max(1, min(wanted_w, target.canvas.winfo_screenwidth() - bar_w)),
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
# 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:
if _UNMAPPED_VIEWPORT_PX < view_h < wanted_h:
_logger.warning(
"lock content overflows its surface: %dpx of content in a "
"%dpx viewport (%dpx off-screen); it is reachable only by "

View File

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

View File

@ -0,0 +1,93 @@
# 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.
"""
return {
"primary": (config.accent, config.on_fill),
"secondary": (config.field_bg, config.fg),
"danger": (config.danger, config.on_fill),
"primary": (config.palette.accent, config.palette.on_fill),
"secondary": (config.palette.field_bg, config.palette.fg),
"danger": (config.palette.danger, config.palette.on_fill),
}

View File

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

View File

@ -0,0 +1,33 @@
# 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,11 +18,14 @@ from gatelock._arbiter import (
RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM,
Arbiter,
)
from gatelock._claims import (
Claim,
_same_file,
_try_lock,
default_runtime_dir,
grab_strength,
)
from gatelock._claims import _same_file, _try_lock
if TYPE_CHECKING:
from collections.abc import Iterator

View File

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

View File

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

View File

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

View File

@ -7,6 +7,7 @@ from unittest.mock import MagicMock
import pytest
from gatelock._config import GrabPolicy
from gatelock._outputs import Output, OutputRect, OutputScan
from gatelock._surfaces import (
SurfaceSet,
@ -41,9 +42,14 @@ class TestNeedsBackdropRoot:
[
(LockConfig(mode="hard"), True),
(LockConfig(mode="soft"), False),
(LockConfig(mode="soft", grab="global"), True),
(LockConfig(mode="soft", grab="local"), True),
(LockConfig(mode="hard", overrideredirect=False, grab="none"), False),
(LockConfig(mode="soft", grab=GrabPolicy(kind="global")), True),
(LockConfig(mode="soft", grab=GrabPolicy(kind="local")), True),
(
LockConfig(
mode="hard", overrideredirect=False, grab=GrabPolicy(kind="none")
),
False,
),
],
)
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")
text_color = button.cget("fg")
expected = config.fg if variant == "secondary" else config.on_fill
expected = config.palette.fg if variant == "secondary" else config.palette.on_fill
assert text_color == expected
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."""
button = make_button(root, config, "Go", lambda: None, ButtonStyle(variant=variant))
assert int(button.cget("highlightthickness")) == config.focus_thickness
assert str(button.cget("highlightcolor")) == config.focus_ring
assert int(button.cget("highlightthickness")) == config.spacing.focus_thickness
assert str(button.cget("highlightcolor")) == config.palette.focus_ring
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."""
button = make_button(root, config, "Go", lambda: None)
assert button.cget("activebackground") == _lighten(config.accent)
assert button.cget("activebackground") == _lighten(config.palette.accent)
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")
assert label.cget("text") == "Right now"
assert str(label.cget("fg")) == config.accent
assert str(label.cget("fg")) == config.palette.accent
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."""
label = row(root, config, "Earned all-time: 3")
assert str(label.cget("fg")) == config.fg
assert str(label.cget("fg")) == config.palette.fg
assert int(label.cget("wraplength")) == DEFAULT_WRAP
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."""
label = row(root, config, "LOCKED", RowStyle(color=config.danger))
label = row(root, config, "LOCKED", RowStyle(color=config.palette.danger))
assert str(label.cget("fg")) == config.danger
assert str(label.cget("fg")) == config.palette.danger
def test_row_wraps_at_the_width_it_is_given(root: tk.Tk, config: LockConfig) -> None:

View File

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

View File

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

View File

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

View File

@ -15,8 +15,9 @@ from gatelock._arbiter import (
RANK_DIET_GUARD,
RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM,
Claim,
)
from gatelock._claims import Claim
from gatelock._config import GrabPolicy
from gatelock._detect import _RandrEventSource
from gatelock._outputs import Output, OutputRect
from gatelock._window import LockConfig
@ -64,7 +65,8 @@ class TestPreemptWeakerHolder:
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)
mock_root,
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
@ -76,7 +78,8 @@ class TestPreemptWeakerHolder:
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)
mock_root,
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
@ -88,7 +91,8 @@ class TestPreemptWeakerHolder:
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)
mock_root,
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
@ -101,7 +105,10 @@ class TestPreemptWeakerHolder:
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=False)
mock_root,
config=LockConfig(
mode="hard", grab=GrabPolicy(preempt_weaker_holder=False)
),
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
@ -128,7 +135,8 @@ class TestPreemptWeakerHolder:
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)
mock_root,
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
)
with patch("gatelock._preempt.os.kill") as kill:
_preempt.maybe_preempt(
@ -154,7 +162,8 @@ class TestPreemptWeakerHolder:
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)
mock_root,
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
)
window._arbiter = arbiter
with (
@ -171,7 +180,8 @@ class TestPreemptWeakerHolder:
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)
mock_root,
config=LockConfig(mode="hard", grab=GrabPolicy(preempt_weaker_holder=True)),
)
window._arbiter = arbiter
with (

View File

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

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "gatelock"
version = "0.7.3"
version = "0.8.0"
description = "Shared per-output lock-window + HMAC log-integrity backend for blocking-overlay apps"
requires-python = ">=3.14"
dependencies = [] # pure stdlib — tkinter is bundled with Python
@ -95,16 +95,40 @@ color_output = true
exclude = [".venv/"]
[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
persistent = true
jobs = 0
py-version = "3.14"
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$"]
[tool.pylint.messages_control]
enable = "all"
disable = []
# Globally disabled checks, matching wake-alarm / diet-guard: each is a
# 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]
min-public-methods = 0