mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-19 17:24:21 +01:00
Migrate screen_locker to gatelock v0.2.0 per-output locking
The lock now paints one container per live output instead of one window on the primary, and claims the screen through an Arbiter at RANK_SCREEN_LOCKER so the wake alarm can outrank it. The fan-out happens at the widget factory, not the render loop. Painting a screen here is not a pure function -- the ~20 clear_container() flows record workouts, credit weeks and branch on state while they paint -- so re-running a flow per surface would double those side effects. Instead `_label`, `_button_row` and friends build N copies and return a group that mirrors later configure calls to all of them, and a flow body still runs once. Frame groups nest, so `_button(button_row, ...)` reads exactly as it did. The degenerate case carries as much weight as the general one: the status window, the post-sick-day verify window and the relaxed-day prompt have no lock and no surfaces, and share this same factory. They get a group of exactly one frame and behave as they always did. Text boxes are the one thing that cannot be shared. Entries fan out over a single StringVar, but tk.Text has no such variable, so the sick-day description genuinely diverges per monitor; TextGroup.get() returns whichever copy was actually typed into, preserving "answer on any monitor". Tests: the suite hung rather than failed on first run, which is the trap gatelock's own conftest documents -- screen_locker patches its own `tk`, but LockWindow builds Toplevels through gatelock's, and real tkinter over a MagicMock root recurses without bound. `_gatelock_fixtures` closes that and redirects the runtime dir so no test can stand a production locker down. Every other test runs single-output, where fan-out is unobservable, so test_surface_fanout runs on two outputs; each assertion was checked by cropping the group loops to the primary and confirming it goes red. 874 tests, 100% branch coverage, pre-commit clean, no lint suppressions.
This commit is contained in:
parent
323e3cd02a
commit
600d0fd084
@ -98,7 +98,7 @@ repos:
|
||||
- --jobs=4
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.1.1#subdirectory=gatelock
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.2.0#subdirectory=gatelock
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync
|
||||
- mcp
|
||||
- pydantic
|
||||
|
||||
@ -7,7 +7,7 @@ requires-python = ">=3.10"
|
||||
# crdt-sync: shared CRDT merge scheme + GitHub-Contents-API sync transport,
|
||||
# also used by diet_guard; here for phone-workout GitHub sync (Workstream C)
|
||||
dependencies = [
|
||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.1.1#subdirectory=gatelock",
|
||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.2.0#subdirectory=gatelock",
|
||||
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync",
|
||||
]
|
||||
|
||||
|
||||
@ -4,7 +4,7 @@ bandit>=1.7.0
|
||||
codespell>=2.2.0
|
||||
coverage>=7.4.0
|
||||
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync
|
||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.1.1#subdirectory=gatelock
|
||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.2.0#subdirectory=gatelock
|
||||
mcp>=1.9
|
||||
mypy>=1.8.0
|
||||
pre-commit>=3.6.0
|
||||
|
||||
@ -72,7 +72,11 @@ class ManualWorkoutDialogMixin(ManualWorkoutFormWidgetsMixin):
|
||||
the inner form to the viewport so its two columns split the full width.
|
||||
Harmless on StatusWindow, whose container already fills its window.
|
||||
"""
|
||||
outer = tk.Frame(self.container, bg=self._colors.bg)
|
||||
# The scrolling form is built on the primary surface only: it is a
|
||||
# canvas-and-scrollbar viewport sized from one toplevel's geometry,
|
||||
# and mirroring an independently-scrolled copy per monitor would
|
||||
# show two different parts of the same form.
|
||||
outer = tk.Frame(self.container.first, bg=self._colors.bg)
|
||||
outer.pack(fill="both", expand=True, pady=10)
|
||||
canvas = tk.Canvas(outer, bg=self._colors.bg, highlightthickness=0)
|
||||
scrollbar = tk.Scrollbar(outer, orient="vertical", command=canvas.yview)
|
||||
|
||||
@ -12,6 +12,7 @@ from screen_locker._constants import (
|
||||
SICK_COMMITMENT_FORCED_READ_SECONDS,
|
||||
SICK_JUSTIFICATION_MIN_CHARS,
|
||||
)
|
||||
from screen_locker._surface_group import FrameGroup, TextGroup
|
||||
from screen_locker._ui_widgets import disable_paste as _disable_paste
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@ -61,7 +62,7 @@ class SickDialogMixin:
|
||||
|
||||
def _build_justification_form(self, *, had_commitment: bool) -> None:
|
||||
"""Add justification form fields and submit button to the container."""
|
||||
form = tk.Frame(self.container, bg=self._colors.bg)
|
||||
form = self.container.child_frame(bg=self._colors.bg)
|
||||
form.pack(pady=10)
|
||||
|
||||
self._sick_symptom_var = tk.StringVar()
|
||||
@ -96,7 +97,7 @@ class SickDialogMixin:
|
||||
self._commitment_forced_remaining = SICK_COMMITMENT_FORCED_READ_SECONDS
|
||||
self._update_commitment_forced_delay()
|
||||
|
||||
def _add_form_widgets(self, parent: tk.Widget) -> tk.Text:
|
||||
def _add_form_widgets(self, parent: FrameGroup) -> TextGroup:
|
||||
"""Create symptom/onset/severity/text widgets. Returns the text widget."""
|
||||
self._add_label_entry(
|
||||
parent,
|
||||
@ -108,17 +109,17 @@ class SickDialogMixin:
|
||||
label="When did it start? (e.g. last night):",
|
||||
variable=self._sick_onset_var,
|
||||
)
|
||||
sev_row = tk.Frame(parent, bg=self._colors.bg)
|
||||
sev_row = parent.child_frame(bg=self._colors.bg)
|
||||
sev_row.pack(pady=8)
|
||||
tk.Label(
|
||||
sev_row,
|
||||
sev_row.child_widgets(
|
||||
tk.Label,
|
||||
text="Severity (1-10):",
|
||||
font=(self._colors.font_family, 14),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
).pack(side="left", padx=5)
|
||||
tk.Spinbox(
|
||||
sev_row,
|
||||
sev_row.child_widgets(
|
||||
tk.Spinbox,
|
||||
from_=1,
|
||||
to=10,
|
||||
textvariable=self._sick_severity_var,
|
||||
@ -126,25 +127,30 @@ class SickDialogMixin:
|
||||
font=(self._colors.font_family, 14),
|
||||
).pack(side="left", padx=5)
|
||||
|
||||
tk.Label(
|
||||
parent,
|
||||
parent.child_widgets(
|
||||
tk.Label,
|
||||
text=(f"Describe how you feel (min {SICK_JUSTIFICATION_MIN_CHARS} chars):"),
|
||||
font=(self._colors.font_family, 14),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
).pack(pady=8)
|
||||
text_widget = tk.Text(
|
||||
parent,
|
||||
width=60,
|
||||
height=6,
|
||||
font=(self._colors.font_family, 14),
|
||||
bg=self._colors.field_bg,
|
||||
fg=self._colors.fg,
|
||||
insertbackground=self._colors.fg,
|
||||
text_widgets = TextGroup(
|
||||
list(
|
||||
parent.child_widgets(
|
||||
tk.Text,
|
||||
width=60,
|
||||
height=6,
|
||||
font=(self._colors.font_family, 14),
|
||||
bg=self._colors.field_bg,
|
||||
fg=self._colors.fg,
|
||||
insertbackground=self._colors.fg,
|
||||
)
|
||||
)
|
||||
)
|
||||
text_widget.pack(pady=8)
|
||||
_disable_paste(text_widget)
|
||||
return text_widget
|
||||
text_widgets.pack(pady=8)
|
||||
for text_widget in text_widgets:
|
||||
_disable_paste(text_widget)
|
||||
return text_widgets
|
||||
|
||||
def _update_commitment_forced_delay(self) -> None:
|
||||
"""Tick down the forced-read delay then enable the submit button."""
|
||||
|
||||
168
screen_locker/_surface_group.py
Normal file
168
screen_locker/_surface_group.py
Normal file
@ -0,0 +1,168 @@
|
||||
"""Presenting N per-monitor surfaces as if they were one container.
|
||||
|
||||
Since gatelock v0.2.0 the lock builds one window per live output, so every
|
||||
widget the locker paints has to exist once per monitor. The rest of this
|
||||
package is written against a single ``self.container``, and building the
|
||||
screen is not a pure function here -- ``_ui_flows`` records workouts, credits
|
||||
weeks and branches on state while it paints -- so re-running a flow once per
|
||||
surface would double those side effects.
|
||||
|
||||
The fan-out therefore happens at the widget factory instead. A flow body runs
|
||||
exactly once; each widget it asks for is created N times and handed back as a
|
||||
proxy that mirrors later ``configure`` calls to every copy. Nesting works the
|
||||
same way: a frame group can be the parent of another group, so
|
||||
``_button_row()`` still reads like it returns one frame.
|
||||
|
||||
The degenerate case matters as much as the general one. The status window,
|
||||
the post-sick-day verify window and the relaxed-day prompt are ordinary
|
||||
single windows with no lock and no surfaces; they build a group of exactly
|
||||
one frame and every call site below behaves as it always did.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
|
||||
class WidgetGroup:
|
||||
"""One logical widget, mirrored onto every monitor.
|
||||
|
||||
Only the operations the locker actually performs after creation are
|
||||
exposed. Anything reading a value back (``winfo_*``, ``get``) answers
|
||||
from the first copy, since all copies are built identically.
|
||||
"""
|
||||
|
||||
def __init__(self, widgets: list[Any]) -> None:
|
||||
"""Wrap the per-monitor copies of one widget."""
|
||||
self._widgets = widgets
|
||||
|
||||
def __iter__(self) -> Iterator[Any]:
|
||||
"""Iterate the per-monitor copies, for callers that need each one."""
|
||||
return iter(self._widgets)
|
||||
|
||||
@property
|
||||
def first(self) -> Any:
|
||||
"""The primary monitor's copy, for reads that cannot fan out."""
|
||||
return self._widgets[0]
|
||||
|
||||
def configure(self, **kwargs: Any) -> None:
|
||||
"""Apply the same configuration to every copy."""
|
||||
for widget in self._widgets:
|
||||
with contextlib.suppress(tk.TclError):
|
||||
widget.configure(**kwargs)
|
||||
|
||||
# Tk's own alias; several call sites here use the short spelling.
|
||||
config = configure
|
||||
|
||||
def pack(self, **kwargs: Any) -> None:
|
||||
"""Pack every copy with the same options."""
|
||||
for widget in self._widgets:
|
||||
with contextlib.suppress(tk.TclError):
|
||||
widget.pack(**kwargs)
|
||||
|
||||
def pack_forget(self) -> None:
|
||||
"""Unpack every copy."""
|
||||
for widget in self._widgets:
|
||||
with contextlib.suppress(tk.TclError):
|
||||
widget.pack_forget()
|
||||
|
||||
def destroy(self) -> None:
|
||||
"""Destroy every copy."""
|
||||
for widget in self._widgets:
|
||||
with contextlib.suppress(tk.TclError):
|
||||
widget.destroy()
|
||||
|
||||
|
||||
class TextGroup(WidgetGroup):
|
||||
"""A multi-line text box, mirrored onto every monitor.
|
||||
|
||||
Entries can share a ``StringVar`` and so are typed once for all screens.
|
||||
``tk.Text`` has no such variable, so the copies genuinely diverge: the
|
||||
user types into exactly one of them, whichever screen they are looking
|
||||
at. Reading therefore returns the first copy with anything in it, which
|
||||
keeps the "answer on any monitor" property the per-output lock exists
|
||||
for. Falls back to the primary's (empty) content so callers still get a
|
||||
string to validate and reject.
|
||||
"""
|
||||
|
||||
def get(self, start: str, end: str) -> str:
|
||||
"""Return the content of whichever copy was actually typed into."""
|
||||
for widget in self._widgets:
|
||||
with contextlib.suppress(tk.TclError):
|
||||
content = widget.get(start, end)
|
||||
if content.strip():
|
||||
return str(content)
|
||||
return str(self._widgets[0].get(start, end))
|
||||
|
||||
|
||||
class FrameGroup(WidgetGroup):
|
||||
"""A container, mirrored onto every monitor, that can parent more groups.
|
||||
|
||||
This is what makes the incremental widget factory in ``UIWidgetsMixin``
|
||||
work unchanged: ``_button_row()`` returns a ``FrameGroup``, and passing
|
||||
it to ``_button()`` creates one button inside each of its frames.
|
||||
"""
|
||||
|
||||
def __init__(self, widgets: list[Any]) -> None:
|
||||
"""Wrap the per-monitor frames, tracking which output each came from."""
|
||||
super().__init__(widgets)
|
||||
self._outputs: list[str] = []
|
||||
|
||||
@classmethod
|
||||
def single(cls, parent: tk.Misc, **kwargs: Any) -> FrameGroup:
|
||||
"""Build a group of exactly one centred frame, for non-lock windows."""
|
||||
frame = tk.Frame(parent, **kwargs)
|
||||
frame.place(relx=0.5, rely=0.5, anchor="center")
|
||||
return cls([frame])
|
||||
|
||||
@property
|
||||
def surfaces(self) -> list[Any]:
|
||||
"""Every per-monitor frame; empty until the lock builds them."""
|
||||
return list(self._widgets)
|
||||
|
||||
def add(self, frame: Any, output_name: str) -> None:
|
||||
"""Register the frame built for one newly-live output."""
|
||||
self._widgets.append(frame)
|
||||
self._outputs.append(output_name)
|
||||
|
||||
def discard(self, output_name: str) -> None:
|
||||
"""Forget the frame for an output that went dark."""
|
||||
kept = [
|
||||
(frame, name)
|
||||
for frame, name in zip(self._widgets, self._outputs, strict=True)
|
||||
if name != output_name
|
||||
]
|
||||
self._widgets = [frame for frame, _ in kept]
|
||||
self._outputs = [name for _, name in kept]
|
||||
|
||||
def child_frame(self, **kwargs: Any) -> FrameGroup:
|
||||
"""Create one child frame inside every copy."""
|
||||
return FrameGroup([tk.Frame(frame, **kwargs) for frame in self._widgets])
|
||||
|
||||
def child_widgets(self, factory: Any, **kwargs: Any) -> WidgetGroup:
|
||||
"""Create one ``factory(parent, **kwargs)`` widget inside every copy."""
|
||||
return WidgetGroup([factory(frame, **kwargs) for frame in self._widgets])
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Destroy every child of every copy."""
|
||||
for frame in self._widgets:
|
||||
with contextlib.suppress(tk.TclError):
|
||||
for child in frame.winfo_children():
|
||||
child.destroy()
|
||||
|
||||
def winfo_toplevel(self) -> Any:
|
||||
"""The primary monitor's toplevel.
|
||||
|
||||
A dialog that needs *a* window to sit relative to gets the primary
|
||||
one; there is no meaningful "the" toplevel across N monitors.
|
||||
"""
|
||||
return self._widgets[0].winfo_toplevel()
|
||||
|
||||
def winfo_children(self) -> list[Any]:
|
||||
"""Children of the primary copy, for tests and geometry queries."""
|
||||
return list(self._widgets[0].winfo_children())
|
||||
@ -9,6 +9,8 @@ from typing import TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from screen_locker._surface_group import FrameGroup, WidgetGroup
|
||||
|
||||
|
||||
def disable_paste(widget: tk.Widget) -> None:
|
||||
"""Disable paste in a Tk Entry/Text widget.
|
||||
@ -26,9 +28,8 @@ class UIWidgetsMixin:
|
||||
"""Mixin providing low-level widget creation helpers."""
|
||||
|
||||
def clear_container(self) -> None:
|
||||
"""Remove all widgets from the main container."""
|
||||
for widget in self.container.winfo_children():
|
||||
widget.destroy()
|
||||
"""Remove all widgets from the main container, on every monitor."""
|
||||
self.container.clear()
|
||||
|
||||
def _label(
|
||||
self,
|
||||
@ -37,10 +38,10 @@ class UIWidgetsMixin:
|
||||
font_size: int = 36,
|
||||
color: str | None = None,
|
||||
pady: int = 20,
|
||||
) -> tk.Label:
|
||||
"""Create and pack a bold label in the container."""
|
||||
label = tk.Label(
|
||||
self.container,
|
||||
) -> WidgetGroup:
|
||||
"""Create and pack a bold label on every monitor."""
|
||||
label = self.container.child_widgets(
|
||||
tk.Label,
|
||||
text=text,
|
||||
font=(self._colors.font_family, font_size, "bold"),
|
||||
fg=color or self._colors.fg,
|
||||
@ -56,10 +57,10 @@ class UIWidgetsMixin:
|
||||
font_size: int = 18,
|
||||
color: str | None = None,
|
||||
pady: int = 10,
|
||||
) -> tk.Label:
|
||||
"""Create and pack a non-bold text label in the container."""
|
||||
label = tk.Label(
|
||||
self.container,
|
||||
) -> WidgetGroup:
|
||||
"""Create and pack a non-bold text label on every monitor."""
|
||||
label = self.container.child_widgets(
|
||||
tk.Label,
|
||||
text=text,
|
||||
font=(self._colors.font_family, font_size),
|
||||
fg=color or self._colors.fg,
|
||||
@ -88,21 +89,25 @@ class UIWidgetsMixin:
|
||||
|
||||
def _button(
|
||||
self,
|
||||
parent: tk.Widget,
|
||||
parent: FrameGroup,
|
||||
text: str,
|
||||
*,
|
||||
bg: str,
|
||||
command: Callable[[], None],
|
||||
width: int = 10,
|
||||
) -> tk.Button:
|
||||
"""Create a styled button (caller must pack).
|
||||
) -> WidgetGroup:
|
||||
"""Create a styled button on every monitor (caller must pack).
|
||||
|
||||
Every copy gets the *same* ``command``, so pressing the button on
|
||||
whichever screen the user is actually looking at does the one thing
|
||||
once -- the same trick the shared entry variable plays for typing.
|
||||
|
||||
Padding follows the shared 2x horizontal:vertical ratio (rule 22);
|
||||
`relief="flat"` is the one depth technique every button in the app
|
||||
uses now (rule 27), matching what `_heat_skip.py` already did alone.
|
||||
"""
|
||||
return tk.Button(
|
||||
parent,
|
||||
return parent.child_widgets(
|
||||
tk.Button,
|
||||
text=text,
|
||||
font=(self._colors.font_family, 24, "bold"),
|
||||
bg=bg,
|
||||
@ -115,32 +120,37 @@ class UIWidgetsMixin:
|
||||
pady=12,
|
||||
)
|
||||
|
||||
def _button_row(self) -> tk.Frame:
|
||||
"""Create and pack a horizontal button container."""
|
||||
frame = tk.Frame(self.container, bg=self._colors.bg)
|
||||
def _button_row(self) -> FrameGroup:
|
||||
"""Create and pack a horizontal button container on every monitor."""
|
||||
frame = self.container.child_frame(bg=self._colors.bg)
|
||||
frame.pack(pady=20)
|
||||
return frame
|
||||
|
||||
def _add_label_entry(
|
||||
self,
|
||||
parent: tk.Widget,
|
||||
parent: FrameGroup,
|
||||
*,
|
||||
label: str,
|
||||
variable: tk.StringVar,
|
||||
) -> None:
|
||||
"""Add a label + single-line entry pair, with paste disabled."""
|
||||
row = tk.Frame(parent, bg=self._colors.bg)
|
||||
"""Add a label + single-line entry pair on every monitor.
|
||||
|
||||
All copies share one ``variable``, so typing on any screen is the
|
||||
same text everywhere and reading it back needs no idea which monitor
|
||||
the user actually used.
|
||||
"""
|
||||
row = parent.child_frame(bg=self._colors.bg)
|
||||
row.pack(pady=8, fill="x")
|
||||
tk.Label(
|
||||
row,
|
||||
row.child_widgets(
|
||||
tk.Label,
|
||||
text=label,
|
||||
font=(self._colors.font_family, 14),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
anchor="w",
|
||||
).pack(side="top", anchor="w")
|
||||
entry = tk.Entry(
|
||||
row,
|
||||
entries = row.child_widgets(
|
||||
tk.Entry,
|
||||
textvariable=variable,
|
||||
width=50,
|
||||
font=(self._colors.font_family, 14),
|
||||
@ -148,5 +158,6 @@ class UIWidgetsMixin:
|
||||
fg=self._colors.fg,
|
||||
insertbackground=self._colors.fg,
|
||||
)
|
||||
entry.pack(side="top", anchor="w", pady=4)
|
||||
disable_paste(entry)
|
||||
entries.pack(side="top", anchor="w", pady=4)
|
||||
for entry in entries:
|
||||
disable_paste(entry)
|
||||
|
||||
@ -10,13 +10,74 @@ relaxed-day prompt.
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock import RANK_SCREEN_LOCKER, Arbiter, LockWindow
|
||||
|
||||
from screen_locker._surface_group import FrameGroup
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from gatelock import SurfaceInfo
|
||||
|
||||
|
||||
class WindowSetupMixin:
|
||||
"""Mixin providing the screen-locker-specific auxiliary windows."""
|
||||
|
||||
def on_focus_ready(self) -> None:
|
||||
"""No typed-input field in the lock window; nothing to focus."""
|
||||
# Declared because this mixin both reads and *reassigns* it; without the
|
||||
# annotation mypy cannot infer the attribute's type through the mixin.
|
||||
container: FrameGroup
|
||||
|
||||
def _build_lock_window(self) -> LockWindow:
|
||||
"""Claim the screen at this app's rank and build the lock.
|
||||
|
||||
The arbiter is published here and then handed to ``LockWindow``,
|
||||
which owns releasing it on close -- so it is deliberately not kept
|
||||
as an attribute of the locker.
|
||||
"""
|
||||
arbiter = Arbiter(
|
||||
"screen_locker",
|
||||
RANK_SCREEN_LOCKER,
|
||||
grab=self._colors.resolved_grab(),
|
||||
disable_vt=self._colors.resolved_disable_vt(),
|
||||
)
|
||||
arbiter.publish()
|
||||
arbiter.acquire_holder()
|
||||
lock = LockWindow(self.root, self._colors, hooks=self, arbiter=arbiter)
|
||||
lock.setup()
|
||||
return lock
|
||||
|
||||
def _ensure_container(self) -> None:
|
||||
"""Give the non-lock windows a container group of exactly one.
|
||||
|
||||
The verify and relaxed-day windows never build a lock, so nothing
|
||||
called ``build_surface`` and the group is still empty. They are
|
||||
ordinary single windows, and one frame is all they need.
|
||||
"""
|
||||
if not self.container.surfaces:
|
||||
self.container = FrameGroup.single(self.root, bg=self._colors.bg)
|
||||
|
||||
def build_surface(self, parent: tk.Misc, surface: SurfaceInfo) -> None:
|
||||
"""Add one centred container for a newly-live output.
|
||||
|
||||
Only the container is built here, not the screen inside it: which
|
||||
screen is showing depends on flow state the lock knows nothing
|
||||
about, so the caller repaints through the usual flow entry point
|
||||
once the surface exists.
|
||||
"""
|
||||
frame = tk.Frame(parent, bg=self._colors.bg)
|
||||
frame.place(relx=0.5, rely=0.5, anchor="center")
|
||||
self.container.add(frame, surface.output_name)
|
||||
|
||||
def teardown_surface(self, surface: SurfaceInfo) -> None:
|
||||
"""Forget the container for an output that went dark."""
|
||||
self.container.discard(surface.output_name)
|
||||
|
||||
def on_focus_ready(self, surface: SurfaceInfo | None) -> None:
|
||||
"""No typed-input field in the lock window; nothing to focus.
|
||||
|
||||
``surface`` is None when no output is live at all -- the lock is
|
||||
held with nothing to show, which is still a valid state.
|
||||
"""
|
||||
|
||||
def on_callback_error(self) -> None:
|
||||
"""Surfaced via GateRoot's logging already; no extra action yet."""
|
||||
|
||||
@ -12,7 +12,11 @@ import sys
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock import GateRoot, LockConfig, LockWindow
|
||||
from gatelock import (
|
||||
GateRoot,
|
||||
LockConfig,
|
||||
LockWindow,
|
||||
)
|
||||
|
||||
from screen_locker._auto_upgrade import AutoUpgradeMixin
|
||||
from screen_locker._constants import (
|
||||
@ -48,6 +52,7 @@ from screen_locker._runnerup_verification import RunnerUpVerificationMixin
|
||||
from screen_locker._shutdown import ShutdownMixin
|
||||
from screen_locker._shutdown_base import reset_to_base_if_new_day
|
||||
from screen_locker._sick_dialog import SickDialogMixin
|
||||
from screen_locker._surface_group import FrameGroup
|
||||
from screen_locker._temperature import fetch_current_temp_with_status
|
||||
from screen_locker._ui_flows import UIFlowsMixin
|
||||
from screen_locker._ui_flows_relaxed import UIFlowsRelaxedMixin
|
||||
@ -149,17 +154,17 @@ class ScreenLocker(
|
||||
grab="local" if demo_mode else "global",
|
||||
disable_vt=not demo_mode,
|
||||
)
|
||||
# Built before setup(), which calls build_surface per live output.
|
||||
self.container = FrameGroup([])
|
||||
if verify_only:
|
||||
self._setup_verify_window()
|
||||
elif self._relaxed_day_mode:
|
||||
self._setup_relaxed_day_window()
|
||||
else:
|
||||
self._lock = LockWindow(self.root, self._colors, hooks=self)
|
||||
self._lock.setup()
|
||||
self._lock = self._build_lock_window()
|
||||
if demo_mode:
|
||||
self._setup_demo_close_button()
|
||||
self.container = tk.Frame(self.root, bg=self._colors.bg)
|
||||
self.container.place(relx=0.5, rely=0.5, anchor="center")
|
||||
self._ensure_container()
|
||||
self._phone_future: Future[tuple[str, str]] | None = None
|
||||
self._runnerup_future: Future[tuple[str, str]] | None = None
|
||||
self._runnerup_on_failure: Callable[[], None] | None = None
|
||||
|
||||
@ -43,6 +43,7 @@ from screen_locker._status_data import (
|
||||
gather_status,
|
||||
)
|
||||
from screen_locker._status_view_verify import PhoneCheckMixin, _make_bare_verifier
|
||||
from screen_locker._surface_group import FrameGroup
|
||||
from screen_locker._temperature import (
|
||||
fetch_current_temp_with_status,
|
||||
)
|
||||
@ -100,8 +101,13 @@ class StatusWindow(
|
||||
self._temp_result: TemperatureCheck | None = None
|
||||
self._last_snapshot = snapshot
|
||||
self._colors = _STATUS_COLORS
|
||||
self.container = tk.Frame(root, bg=self._colors.bg)
|
||||
self.container.pack(fill="both", expand=True)
|
||||
# A group of one: this window has no lock and no per-output surfaces,
|
||||
# but it shares UIWidgetsMixin's factory with the locker, which now
|
||||
# builds through a group. Filling the window rather than centring, so
|
||||
# this is built here instead of via FrameGroup.single().
|
||||
frame = tk.Frame(root, bg=self._colors.bg)
|
||||
frame.pack(fill="both", expand=True)
|
||||
self.container = FrameGroup([frame])
|
||||
self._start_temperature_check()
|
||||
self.render(snapshot)
|
||||
|
||||
|
||||
76
screen_locker/tests/_gatelock_fixtures.py
Normal file
76
screen_locker/tests/_gatelock_fixtures.py
Normal file
@ -0,0 +1,76 @@
|
||||
"""Keeping gatelock v0.2.0's per-output machinery off the real machine.
|
||||
|
||||
``conftest``'s ``_block_real_tk_and_exit`` patches ``tk`` inside
|
||||
*screen_locker*, which is not enough any more: since v0.2.0 ``LockWindow``
|
||||
builds one real ``tk.Toplevel`` per live output through *gatelock's* own
|
||||
``tk``. Over a MagicMock root that sends real tkinter into unbounded mock
|
||||
recursion, so the suite **hangs** instead of failing -- far harder to
|
||||
diagnose than an error, and it is what this module exists to prevent.
|
||||
|
||||
Re-exported from ``conftest`` rather than defined there so neither file
|
||||
exceeds the repo's 400-line limit.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from gatelock import Output, OutputRect
|
||||
import pytest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
FAKE_OUTPUTS = (
|
||||
Output("DP-0", connected=True, rect=OutputRect(0, 0, 1920, 1080), primary=True),
|
||||
)
|
||||
"""One live output by default, so the Tk-screen fallback (which would call
|
||||
int() on a MagicMock) is never reached."""
|
||||
|
||||
TWO_OUTPUTS = (
|
||||
Output("DP-0", connected=True, rect=OutputRect(0, 0, 3840, 2160), primary=True),
|
||||
Output("HDMI-0", connected=True, rect=OutputRect(3840, 0, 2560, 1440)),
|
||||
)
|
||||
"""The real desk. Opt in with the ``dual_output`` fixture for anything
|
||||
asserting that work fans out across monitors: against ``FAKE_OUTPUTS`` a loop
|
||||
that only ever touched the primary passes every assertion."""
|
||||
|
||||
|
||||
def _make_toplevel(_parent: object = None, **_kwargs: object) -> MagicMock:
|
||||
"""A Toplevel stand-in for gatelock's per-output surfaces."""
|
||||
window = MagicMock()
|
||||
window.winfo_children.return_value = []
|
||||
return window
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _hermetic_gatelock(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> Iterator[None]:
|
||||
"""Block every path from the lock to the real display or machine.
|
||||
|
||||
The runtime dir is redirected as well, so a test cannot reach the real
|
||||
``$XDG_RUNTIME_DIR`` and stand a *production* locker down through the
|
||||
arbiter.
|
||||
"""
|
||||
monkeypatch.setenv("GATELOCK_RUNTIME_DIR", str(tmp_path / "gatelock-runtime"))
|
||||
with (
|
||||
patch("gatelock._surfaces.tk.Toplevel", side_effect=_make_toplevel),
|
||||
patch("gatelock._outputs.RandrBackend.create", return_value=None),
|
||||
patch("gatelock._outputs.scan_xrandr", return_value=FAKE_OUTPUTS),
|
||||
patch("gatelock._detect._RandrEventSource.start", return_value=False),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dual_output(_hermetic_gatelock: None) -> Iterator[None]:
|
||||
"""Re-scan as a two-monitor desk, layered over the single-output default.
|
||||
|
||||
Depends on ``_hermetic_gatelock`` so pytest is obliged to apply it
|
||||
second; the ``scan_xrandr`` patch here has to be the one that wins.
|
||||
"""
|
||||
with patch("gatelock._outputs.scan_xrandr", return_value=TWO_OUTPUTS):
|
||||
yield
|
||||
143
screen_locker/tests/_locker_factories.py
Normal file
143
screen_locker/tests/_locker_factories.py
Normal file
@ -0,0 +1,143 @@
|
||||
"""Constructors for a ``ScreenLocker`` under test.
|
||||
|
||||
Split out of ``conftest`` (and re-exported from it) so neither file
|
||||
exceeds the repo's 400-line limit. Every early-exit path a real start-up
|
||||
would take is patched here, so a test gets a locker that is built but has
|
||||
not run any of its flows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from screen_locker.screen_lock import ScreenLocker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import Literal
|
||||
|
||||
|
||||
def _make_locker(
|
||||
log_file: Path,
|
||||
*,
|
||||
n_filled: int = 0,
|
||||
bonus_applied: bool = False,
|
||||
cfg: tuple | None = (22, 22, 5),
|
||||
):
|
||||
"""Build a minimal locker-like namespace for _status.run_status()."""
|
||||
locker = SimpleNamespace(
|
||||
log_file=log_file,
|
||||
workout_data={},
|
||||
)
|
||||
locker._scan_and_fill_week_runnerup = MagicMock(return_value=n_filled)
|
||||
locker._adjust_shutdown_time_by = MagicMock(return_value=bonus_applied)
|
||||
locker._read_shutdown_config = MagicMock(return_value=cfg)
|
||||
return locker
|
||||
|
||||
|
||||
def create_locker(
|
||||
_mock_tk: MagicMock,
|
||||
tmp_path: Path,
|
||||
*,
|
||||
demo_mode: bool = True,
|
||||
has_logged: bool = False,
|
||||
verify_only: bool = False,
|
||||
is_sick_day_log: bool = False,
|
||||
) -> ScreenLocker:
|
||||
"""Create a ScreenLocker instance with early bird paths disabled."""
|
||||
with (
|
||||
patch.object(Path, "resolve", return_value=tmp_path / "screen_locker"),
|
||||
patch.object(ScreenLocker, "has_logged_today", return_value=has_logged),
|
||||
patch.object(
|
||||
ScreenLocker,
|
||||
"_is_sick_day_today",
|
||||
return_value=is_sick_day_log,
|
||||
),
|
||||
patch.object(ScreenLocker, "_is_early_bird_pending", return_value=False),
|
||||
patch.object(ScreenLocker, "_is_early_bird_time", return_value=False),
|
||||
patch.object(
|
||||
ScreenLocker,
|
||||
"_try_auto_upgrade_early_bird",
|
||||
return_value=False,
|
||||
),
|
||||
patch.object(ScreenLocker, "_start_phone_check"),
|
||||
patch.object(ScreenLocker, "_start_relaxed_day_flow"),
|
||||
patch.object(ScreenLocker, "_start_verify_workout_check"),
|
||||
patch.object(ScreenLocker, "_scan_and_fill_week_runnerup", return_value=0),
|
||||
):
|
||||
return ScreenLocker(
|
||||
demo_mode=demo_mode,
|
||||
verify_only=verify_only,
|
||||
)
|
||||
|
||||
|
||||
def create_locker_relaxed_day(
|
||||
_mock_tk: MagicMock,
|
||||
tmp_path: Path,
|
||||
*,
|
||||
demo_mode: bool = True,
|
||||
has_logged: bool = False,
|
||||
) -> ScreenLocker:
|
||||
"""Create a ScreenLocker in relaxed-day mode (Tue/Wed/Thu).
|
||||
|
||||
``is_relaxed_day`` returns True so ``_relaxed_day_mode`` is set and
|
||||
``_start_relaxed_day_flow`` is called instead of ``_start_phone_check``.
|
||||
The autouse ``_mock_weekly_logic`` fixture is overridden here.
|
||||
"""
|
||||
with (
|
||||
patch.object(Path, "resolve", return_value=tmp_path / "screen_locker"),
|
||||
patch.object(ScreenLocker, "has_logged_today", return_value=has_logged),
|
||||
patch.object(ScreenLocker, "_is_sick_day_today", return_value=False),
|
||||
patch.object(ScreenLocker, "_is_early_bird_pending", return_value=False),
|
||||
patch.object(ScreenLocker, "_is_early_bird_time", return_value=False),
|
||||
patch.object(ScreenLocker, "_try_auto_upgrade_early_bird", return_value=False),
|
||||
patch("screen_locker.screen_lock.is_relaxed_day", return_value=True),
|
||||
patch(
|
||||
"screen_locker.screen_lock.has_weekly_minimum",
|
||||
return_value=False,
|
||||
),
|
||||
patch.object(ScreenLocker, "_start_phone_check"),
|
||||
patch.object(ScreenLocker, "_start_relaxed_day_flow"),
|
||||
patch.object(ScreenLocker, "_start_verify_workout_check"),
|
||||
):
|
||||
return ScreenLocker(demo_mode=demo_mode)
|
||||
|
||||
|
||||
def create_locker_early_bird(
|
||||
_mock_tk: MagicMock,
|
||||
tmp_path: Path,
|
||||
*,
|
||||
state: Literal["none", "log_active", "log_expired"] = "none",
|
||||
has_logged: bool = False,
|
||||
demo_mode: bool = True,
|
||||
) -> ScreenLocker:
|
||||
"""Create a ScreenLocker configured for early bird path testing.
|
||||
|
||||
Args:
|
||||
state: One of:
|
||||
- "none": outside early bird window, no early bird log.
|
||||
- "log_active": early bird log exists, still in window.
|
||||
- "log_expired": early bird log exists, past 8:30 AM.
|
||||
has_logged: Return value for has_logged_today mock.
|
||||
demo_mode: Passed to ScreenLocker constructor.
|
||||
"""
|
||||
is_early_bird_log = state in ("log_active", "log_expired")
|
||||
is_early_bird_time = state == "log_active"
|
||||
with (
|
||||
patch.object(Path, "resolve", return_value=tmp_path / "screen_locker"),
|
||||
patch.object(ScreenLocker, "has_logged_today", return_value=has_logged),
|
||||
patch.object(ScreenLocker, "_is_sick_day_today", return_value=False),
|
||||
patch.object(
|
||||
ScreenLocker, "_is_early_bird_pending", return_value=is_early_bird_log
|
||||
),
|
||||
patch.object(
|
||||
ScreenLocker, "_is_early_bird_time", return_value=is_early_bird_time
|
||||
),
|
||||
patch.object(ScreenLocker, "_try_auto_upgrade_early_bird", return_value=False),
|
||||
patch.object(ScreenLocker, "_start_phone_check"),
|
||||
patch.object(ScreenLocker, "_start_relaxed_day_flow"),
|
||||
patch.object(ScreenLocker, "_start_verify_workout_check"),
|
||||
):
|
||||
return ScreenLocker(demo_mode=demo_mode)
|
||||
@ -13,19 +13,28 @@ from __future__ import annotations
|
||||
from contextlib import ExitStack
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tkinter as tk
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from screen_locker.screen_lock import ScreenLocker
|
||||
from screen_locker.tests._gatelock_fixtures import (
|
||||
FAKE_OUTPUTS,
|
||||
TWO_OUTPUTS,
|
||||
_hermetic_gatelock,
|
||||
dual_output,
|
||||
)
|
||||
from screen_locker.tests._locker_factories import (
|
||||
_make_locker,
|
||||
create_locker,
|
||||
create_locker_early_bird,
|
||||
create_locker_relaxed_day,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator, Iterator
|
||||
from typing import Literal
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# Every module that imports ``tkinter as tk`` and calls it directly. The UI is
|
||||
@ -40,7 +49,19 @@ _TK_MODULES = (
|
||||
"screen_locker._window_setup",
|
||||
"screen_locker.status_view",
|
||||
"screen_locker._heat_skip",
|
||||
"screen_locker._surface_group",
|
||||
)
|
||||
__all__ = [
|
||||
"FAKE_OUTPUTS",
|
||||
"TWO_OUTPUTS",
|
||||
"_hermetic_gatelock",
|
||||
"_make_locker",
|
||||
"create_locker",
|
||||
"create_locker_early_bird",
|
||||
"create_locker_relaxed_day",
|
||||
"dual_output",
|
||||
]
|
||||
|
||||
_VT_SHUTIL = "gatelock._vt.shutil"
|
||||
_VT_SUBPROCESS = "gatelock._vt.subprocess"
|
||||
|
||||
@ -274,127 +295,3 @@ def _mock_sys_exit(mock_sys_exit: MagicMock) -> MagicMock:
|
||||
def temp_log_file(tmp_path: Path) -> Path:
|
||||
"""Create a temporary log file path."""
|
||||
return tmp_path / "workout_log.json"
|
||||
|
||||
|
||||
def _make_locker(
|
||||
log_file: Path,
|
||||
*,
|
||||
n_filled: int = 0,
|
||||
bonus_applied: bool = False,
|
||||
cfg: tuple | None = (22, 22, 5),
|
||||
):
|
||||
"""Build a minimal locker-like namespace for _status.run_status()."""
|
||||
locker = SimpleNamespace(
|
||||
log_file=log_file,
|
||||
workout_data={},
|
||||
)
|
||||
locker._scan_and_fill_week_runnerup = MagicMock(return_value=n_filled)
|
||||
locker._adjust_shutdown_time_by = MagicMock(return_value=bonus_applied)
|
||||
locker._read_shutdown_config = MagicMock(return_value=cfg)
|
||||
return locker
|
||||
|
||||
|
||||
def create_locker(
|
||||
_mock_tk: MagicMock,
|
||||
tmp_path: Path,
|
||||
*,
|
||||
demo_mode: bool = True,
|
||||
has_logged: bool = False,
|
||||
verify_only: bool = False,
|
||||
is_sick_day_log: bool = False,
|
||||
) -> ScreenLocker:
|
||||
"""Create a ScreenLocker instance with early bird paths disabled."""
|
||||
with (
|
||||
patch.object(Path, "resolve", return_value=tmp_path / "screen_locker"),
|
||||
patch.object(ScreenLocker, "has_logged_today", return_value=has_logged),
|
||||
patch.object(
|
||||
ScreenLocker,
|
||||
"_is_sick_day_today",
|
||||
return_value=is_sick_day_log,
|
||||
),
|
||||
patch.object(ScreenLocker, "_is_early_bird_pending", return_value=False),
|
||||
patch.object(ScreenLocker, "_is_early_bird_time", return_value=False),
|
||||
patch.object(
|
||||
ScreenLocker,
|
||||
"_try_auto_upgrade_early_bird",
|
||||
return_value=False,
|
||||
),
|
||||
patch.object(ScreenLocker, "_start_phone_check"),
|
||||
patch.object(ScreenLocker, "_start_relaxed_day_flow"),
|
||||
patch.object(ScreenLocker, "_start_verify_workout_check"),
|
||||
patch.object(ScreenLocker, "_scan_and_fill_week_runnerup", return_value=0),
|
||||
):
|
||||
return ScreenLocker(
|
||||
demo_mode=demo_mode,
|
||||
verify_only=verify_only,
|
||||
)
|
||||
|
||||
|
||||
def create_locker_relaxed_day(
|
||||
_mock_tk: MagicMock,
|
||||
tmp_path: Path,
|
||||
*,
|
||||
demo_mode: bool = True,
|
||||
has_logged: bool = False,
|
||||
) -> ScreenLocker:
|
||||
"""Create a ScreenLocker in relaxed-day mode (Tue/Wed/Thu).
|
||||
|
||||
``is_relaxed_day`` returns True so ``_relaxed_day_mode`` is set and
|
||||
``_start_relaxed_day_flow`` is called instead of ``_start_phone_check``.
|
||||
The autouse ``_mock_weekly_logic`` fixture is overridden here.
|
||||
"""
|
||||
with (
|
||||
patch.object(Path, "resolve", return_value=tmp_path / "screen_locker"),
|
||||
patch.object(ScreenLocker, "has_logged_today", return_value=has_logged),
|
||||
patch.object(ScreenLocker, "_is_sick_day_today", return_value=False),
|
||||
patch.object(ScreenLocker, "_is_early_bird_pending", return_value=False),
|
||||
patch.object(ScreenLocker, "_is_early_bird_time", return_value=False),
|
||||
patch.object(ScreenLocker, "_try_auto_upgrade_early_bird", return_value=False),
|
||||
patch("screen_locker.screen_lock.is_relaxed_day", return_value=True),
|
||||
patch(
|
||||
"screen_locker.screen_lock.has_weekly_minimum",
|
||||
return_value=False,
|
||||
),
|
||||
patch.object(ScreenLocker, "_start_phone_check"),
|
||||
patch.object(ScreenLocker, "_start_relaxed_day_flow"),
|
||||
patch.object(ScreenLocker, "_start_verify_workout_check"),
|
||||
):
|
||||
return ScreenLocker(demo_mode=demo_mode)
|
||||
|
||||
|
||||
def create_locker_early_bird(
|
||||
_mock_tk: MagicMock,
|
||||
tmp_path: Path,
|
||||
*,
|
||||
state: Literal["none", "log_active", "log_expired"] = "none",
|
||||
has_logged: bool = False,
|
||||
demo_mode: bool = True,
|
||||
) -> ScreenLocker:
|
||||
"""Create a ScreenLocker configured for early bird path testing.
|
||||
|
||||
Args:
|
||||
state: One of:
|
||||
- "none": outside early bird window, no early bird log.
|
||||
- "log_active": early bird log exists, still in window.
|
||||
- "log_expired": early bird log exists, past 8:30 AM.
|
||||
has_logged: Return value for has_logged_today mock.
|
||||
demo_mode: Passed to ScreenLocker constructor.
|
||||
"""
|
||||
is_early_bird_log = state in ("log_active", "log_expired")
|
||||
is_early_bird_time = state == "log_active"
|
||||
with (
|
||||
patch.object(Path, "resolve", return_value=tmp_path / "screen_locker"),
|
||||
patch.object(ScreenLocker, "has_logged_today", return_value=has_logged),
|
||||
patch.object(ScreenLocker, "_is_sick_day_today", return_value=False),
|
||||
patch.object(
|
||||
ScreenLocker, "_is_early_bird_pending", return_value=is_early_bird_log
|
||||
),
|
||||
patch.object(
|
||||
ScreenLocker, "_is_early_bird_time", return_value=is_early_bird_time
|
||||
),
|
||||
patch.object(ScreenLocker, "_try_auto_upgrade_early_bird", return_value=False),
|
||||
patch.object(ScreenLocker, "_start_phone_check"),
|
||||
patch.object(ScreenLocker, "_start_relaxed_day_flow"),
|
||||
patch.object(ScreenLocker, "_start_verify_workout_check"),
|
||||
):
|
||||
return ScreenLocker(demo_mode=demo_mode)
|
||||
|
||||
@ -241,7 +241,7 @@ class TestShowSickJustification:
|
||||
assert hasattr(locker, "_sick_submit_button")
|
||||
# Submit button starts enabled (no commitment).
|
||||
# config(state="disabled") only called for commitment path.
|
||||
for call in locker._sick_submit_button.config.call_args_list:
|
||||
for call in locker._sick_submit_button.first.configure.call_args_list:
|
||||
assert call.kwargs.get("state") != "disabled"
|
||||
|
||||
def test_renders_form_with_commitment_disables_submit(
|
||||
@ -257,7 +257,7 @@ class TestShowSickJustification:
|
||||
# Submit button was disabled and forced-delay started.
|
||||
states = [
|
||||
call.kwargs.get("state")
|
||||
for call in locker._sick_submit_button.config.call_args_list
|
||||
for call in locker._sick_submit_button.first.configure.call_args_list
|
||||
]
|
||||
assert "disabled" in states
|
||||
|
||||
|
||||
197
screen_locker/tests/test_surface_fanout.py
Normal file
197
screen_locker/tests/test_surface_fanout.py
Normal file
@ -0,0 +1,197 @@
|
||||
"""Per-output fan-out: the point of the gatelock v0.2.0 migration.
|
||||
|
||||
Every other test in this suite runs against the single-output default, where
|
||||
"built on every monitor" and "built on the primary and nowhere else" are
|
||||
indistinguishable. These run on a two-monitor desk, so a loop that only ever
|
||||
touched ``surfaces[0]`` fails here and nowhere else.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from screen_locker._surface_group import FrameGroup, TextGroup, WidgetGroup
|
||||
from screen_locker.tests.conftest import TWO_OUTPUTS, create_locker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("dual_output")
|
||||
class TestLockerFansOut:
|
||||
"""The locker's container group, on two live outputs."""
|
||||
|
||||
def test_one_container_per_output(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""The premise the rest of this class rests on."""
|
||||
del mock_sys_exit
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
|
||||
assert len(locker.container.surfaces) == len(TWO_OUTPUTS)
|
||||
|
||||
def test_a_label_is_built_on_every_monitor(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""One ``_label`` call paints both screens, not just the primary."""
|
||||
del mock_sys_exit
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
mock_tk.Label.reset_mock()
|
||||
|
||||
locker._label("Great job!")
|
||||
|
||||
assert mock_tk.Label.call_count == len(TWO_OUTPUTS)
|
||||
|
||||
def test_a_button_is_built_on_every_monitor(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""Buttons fan out through the row group they are parented to."""
|
||||
del mock_sys_exit
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
row = locker._button_row()
|
||||
mock_tk.Button.reset_mock()
|
||||
|
||||
locker._button(row, "OK", bg=locker._colors.accent, command=lambda: None)
|
||||
|
||||
assert mock_tk.Button.call_count == len(TWO_OUTPUTS)
|
||||
|
||||
def test_clearing_clears_every_monitor(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""A screen change wipes both surfaces, not just the primary."""
|
||||
del mock_sys_exit
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
# conftest's tk mock hands out one shared Frame, so identity cannot
|
||||
# tell the surfaces apart here -- call counts can. Two surfaces means
|
||||
# two sweeps; a loop cropped to the primary would make it one.
|
||||
child = MagicMock()
|
||||
for frame in locker.container.surfaces:
|
||||
frame.winfo_children.reset_mock()
|
||||
frame.winfo_children.return_value = [child]
|
||||
|
||||
locker.clear_container()
|
||||
|
||||
surface = locker.container.surfaces[0]
|
||||
assert surface.winfo_children.call_count == len(TWO_OUTPUTS)
|
||||
assert child.destroy.call_count == len(TWO_OUTPUTS)
|
||||
|
||||
def test_a_dark_output_drops_only_its_own_container(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""Teardown is by output name, so the surviving monitor keeps painting."""
|
||||
del mock_sys_exit
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
survivor = locker.container.surfaces[1]
|
||||
|
||||
locker.teardown_surface(MagicMock(output_name=TWO_OUTPUTS[0].name))
|
||||
|
||||
assert locker.container.surfaces == [survivor]
|
||||
|
||||
|
||||
class TestGroupsInIsolation:
|
||||
"""The group primitives, without a locker around them."""
|
||||
|
||||
def test_configure_reaches_a_dead_copy_without_raising(self) -> None:
|
||||
"""A monitor that vanished mid-update must not break the others."""
|
||||
dead, alive = MagicMock(), MagicMock()
|
||||
dead.configure.side_effect = tk.TclError("bad window path name")
|
||||
|
||||
WidgetGroup([dead, alive]).configure(text="hi")
|
||||
|
||||
alive.configure.assert_called_once_with(text="hi")
|
||||
|
||||
def test_pack_and_destroy_survive_a_dead_copy(self) -> None:
|
||||
"""Same tolerance for the other fan-out operations."""
|
||||
dead, alive = MagicMock(), MagicMock()
|
||||
dead.pack.side_effect = tk.TclError("gone")
|
||||
dead.destroy.side_effect = tk.TclError("gone")
|
||||
dead.pack_forget.side_effect = tk.TclError("gone")
|
||||
group = WidgetGroup([dead, alive])
|
||||
|
||||
group.pack(pady=2)
|
||||
group.pack_forget()
|
||||
group.destroy()
|
||||
|
||||
alive.pack.assert_called_once_with(pady=2)
|
||||
alive.pack_forget.assert_called_once_with()
|
||||
alive.destroy.assert_called_once_with()
|
||||
|
||||
def test_clear_survives_a_dead_copy(self) -> None:
|
||||
"""A frame whose window died is skipped, the live one is emptied."""
|
||||
dead, alive = MagicMock(), MagicMock()
|
||||
dead.winfo_children.side_effect = tk.TclError("gone")
|
||||
child = MagicMock()
|
||||
alive.winfo_children.return_value = [child]
|
||||
|
||||
FrameGroup([dead, alive]).clear()
|
||||
|
||||
child.destroy.assert_called_once_with()
|
||||
|
||||
def test_text_reads_whichever_copy_was_typed_into(self) -> None:
|
||||
"""Text boxes cannot share a variable, so the non-empty one wins."""
|
||||
untouched, typed = MagicMock(), MagicMock()
|
||||
untouched.get.return_value = " "
|
||||
typed.get.return_value = "I have a migraine"
|
||||
|
||||
group = TextGroup([untouched, typed])
|
||||
|
||||
assert group.get("1.0", "end") == "I have a migraine"
|
||||
|
||||
def test_text_falls_back_to_the_primary_when_all_blank(self) -> None:
|
||||
"""An untouched form still yields a string for validation to reject."""
|
||||
first, second = MagicMock(), MagicMock()
|
||||
first.get.return_value = ""
|
||||
second.get.return_value = ""
|
||||
|
||||
assert TextGroup([first, second]).get("1.0", "end") == ""
|
||||
|
||||
def test_text_skips_a_dead_copy(self) -> None:
|
||||
"""A destroyed monitor's box is stepped over, not fatal."""
|
||||
dead, typed = MagicMock(), MagicMock()
|
||||
dead.get.side_effect = tk.TclError("gone")
|
||||
typed.get.return_value = "fever since 3am"
|
||||
|
||||
assert TextGroup([dead, typed]).get("1.0", "end") == "fever since 3am"
|
||||
|
||||
def test_single_builds_a_group_of_one(self) -> None:
|
||||
"""The non-lock windows' degenerate case."""
|
||||
parent = MagicMock()
|
||||
|
||||
group = FrameGroup.single(parent, bg="#000000")
|
||||
|
||||
assert len(group.surfaces) == 1
|
||||
group.first.place.assert_called_once()
|
||||
|
||||
def test_discard_is_a_no_op_for_an_unknown_output(self) -> None:
|
||||
"""Tearing down an output that was never built changes nothing."""
|
||||
group = FrameGroup([])
|
||||
frame = MagicMock()
|
||||
group.add(frame, "DP-0")
|
||||
|
||||
group.discard("HDMI-9")
|
||||
|
||||
assert group.surfaces == [frame]
|
||||
|
||||
def test_child_frame_and_widgets_nest(self) -> None:
|
||||
"""A group can parent another group, which is what button rows need."""
|
||||
group = FrameGroup([MagicMock(), MagicMock()])
|
||||
|
||||
row = group.child_frame(bg="#000000")
|
||||
labels = row.child_widgets(lambda _parent, **_kw: MagicMock(), text="hi")
|
||||
|
||||
assert len(row.surfaces) == 2
|
||||
assert len(list(labels)) == 2
|
||||
|
||||
def test_winfo_helpers_answer_from_the_primary(self) -> None:
|
||||
"""Reads that cannot fan out use the primary monitor's copy."""
|
||||
first, second = MagicMock(), MagicMock()
|
||||
child = MagicMock()
|
||||
first.winfo_children.return_value = [child]
|
||||
group = FrameGroup([first, second])
|
||||
|
||||
assert group.winfo_children() == [child]
|
||||
assert group.winfo_toplevel() is first.winfo_toplevel.return_value
|
||||
@ -26,7 +26,7 @@ class TestUITransitions:
|
||||
# Set up mock children
|
||||
mock_child1 = MagicMock()
|
||||
mock_child2 = MagicMock()
|
||||
locker.container.winfo_children.return_value = [
|
||||
locker.container.first.winfo_children.return_value = [
|
||||
mock_child1,
|
||||
mock_child2,
|
||||
]
|
||||
|
||||
@ -338,4 +338,4 @@ class TestShowVerifyRetry:
|
||||
locker._show_verify_retry("No workout found")
|
||||
|
||||
# Verify container was cleared and buttons were packed
|
||||
locker.container.winfo_children.return_value = []
|
||||
locker.container.first.winfo_children.return_value = []
|
||||
|
||||
Loading…
Reference in New Issue
Block a user