diet-guard/diet_guard/_calendar_view.py
Krzysztof kuhy Rudnicki 84bd550331
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
Migrate diet_guard to gatelock v0.2.0 per-output locking
The gate is laid out once per live output instead of once on the primary,
and claims the screen through an Arbiter at RANK_DIET_GUARD so the wake alarm
and the workout locker can both outrank it.

Three kinds of state needed three different answers. The display fields
already fanned out for free -- GateVars holds root-mastered StringVars bound
to labels. The typed-in fields did not: amount, per, meal name and the four
macro cells were bare tk.Entry widgets, so N copies would have been N
independent forms. They are variable-backed now, which is what makes logging
work from whichever screen the user is actually looking at. The description
box and the suggestion list cannot be shared at all -- tk.Text and tk.Listbox
have no variable -- so those genuinely diverge and reads answer from the copy
the user touched.

The History tab is per-surface too: its grid, budget field and edit button
are driven across every monitor, with the budget likewise variable-backed so
the value cannot differ between screens mid-edit.

Laying the gate out on the primary monitor only was considered and rejected:
not having to hunt for the screen the form landed on is the entire point of
per-output locking.

Tests: the suite hung rather than failed on first run -- diet_guard patches
its own `tk`, but LockWindow builds Toplevels through gatelock's, and real
tkinter over a MagicMock root recurses without bound. `_hermetic_gatelock`
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_gatelock_fanout runs on two; each assertion was checked
by cropping the fan-out loops to the first surface and confirming it goes red.

_gatelock_ui and _gatelock_calendar were each split in two to stay under the
500-line limit, and GateVars' typed-in fields moved into a nested
GateEntryVars rather than raising pylint's attribute cap.

470 tests, 100% branch coverage, pre-commit clean, no lint suppressions.
2026-07-25 16:56:13 +02:00

158 lines
5.1 KiB
Python

"""Pure month-grid math and status text for the diet_guard History tab.
Split out of :mod:`._gatelock_calendar` so the calendar math -- month-grid
construction, per-cell styling, and the streak/YTD summary lines -- carries no
Tk widget dependency and is unit-tested directly, with no fake Tk in the
loop. Also keeps :mod:`._gatelock_calendar` (the Tk-facing half) under the
repo's 500-line limit.
"""
from __future__ import annotations
import calendar
from dataclasses import dataclass
from datetime import date
from gatelock import LockConfig
from diet_guard._daystatus import (
DayStatus,
adherence_streak,
logging_streak,
year_to_date_tally,
)
from diet_guard._gatelock_ui import BG, FG
from diet_guard._state import now_local
_COLORS = LockConfig()
# A "not logged" cell renders hollow -- background-colored fill, near-white
# outline -- rather than a pure-black square (safe-design-rules rule 1),
# distinguishing "no data" from "logged and over/under budget" (colored fill).
_NOT_LOGGED_FILL = BG
_NOT_LOGGED_OUTLINE = FG
_STATUS_COLORS = {
DayStatus.GREEN: _COLORS.success,
DayStatus.YELLOW: _COLORS.warning,
DayStatus.RED: _COLORS.danger,
}
_STATUS_TEXT_COLOR = _COLORS.on_fill
_MUTED = _COLORS.muted
@dataclass(frozen=True)
class CalendarCell:
"""One day cell in a rendered month grid.
``day`` is None for a blank cell outside the displayed month. ``status``
is None for a blank cell, a future day (nothing to judge yet), or when no
budget is set (nothing to color by) -- callers render all three the same
neutral way, never as a false "not logged" black cell.
"""
day: int | None
status: DayStatus | None
def _cell_status(
day: date,
status_map_: dict[str, DayStatus] | None,
today: date,
) -> DayStatus | None:
"""Return the status to render for ``day``, or None for nothing to show.
A day after ``today`` has not happened yet, and ``status_map_`` being
None means no budget is set to judge by -- both render neutrally rather
than as a false "not logged" black cell.
"""
if day > today or status_map_ is None:
return None
return status_map_.get(day.isoformat(), DayStatus.NOT_LOGGED)
def build_month_cells(
year: int,
month: int,
status_map_: dict[str, DayStatus] | None,
*,
today: date | None = None,
) -> list[list[CalendarCell]]:
"""Return the month's weeks as a grid of :class:`CalendarCell`.
Mirrors :func:`calendar.monthcalendar`'s shape (a list of weeks, each
seven day-of-month ints with 0 for days outside the month), translated
into cells carrying the status to render.
Args:
year: The displayed year.
month: The displayed month (1-12).
status_map_: Per-day statuses as returned by
:func:`diet_guard._daystatus.status_map`, or None if no budget is
set to classify days by.
today: The reference "today"; defaults to the real current date.
Returns:
A list of weeks, each a list of seven :class:`CalendarCell`.
"""
ref = today if today is not None else now_local().date()
grid: list[list[CalendarCell]] = []
for week in calendar.monthcalendar(year, month):
row: list[CalendarCell] = []
for day_num in week:
if day_num == 0:
row.append(CalendarCell(day=None, status=None))
continue
row.append(
CalendarCell(
day=day_num,
status=_cell_status(date(year, month, day_num), status_map_, ref),
),
)
grid.append(row)
return grid
def cell_style(status: DayStatus | None) -> tuple[str, str, str]:
"""Return ``(bg, fg, highlightbackground)`` for a cell's status."""
if status is None:
return BG, _MUTED, BG
if status is DayStatus.NOT_LOGGED:
return _NOT_LOGGED_FILL, FG, _NOT_LOGGED_OUTLINE
color = _STATUS_COLORS[status]
return color, _STATUS_TEXT_COLOR, color
def _plural(count: int) -> str:
"""Return "day" or "days" for ``count``."""
return "day" if count == 1 else "days"
def streaks_text(
status_map_: dict[str, DayStatus],
*,
today: date | None = None,
) -> str:
"""Render the logging and adherence streak line.
``today`` defaults to the real current date for live UI use; tests pass
it explicitly for deterministic streak boundaries.
"""
logging = logging_streak(status_map_, today=today)
adherence = adherence_streak(status_map_, today=today)
return (
f"Logging streak: {logging} {_plural(logging)} · "
f"Adherence streak: {adherence} {_plural(adherence)}"
)
def ytd_text(status_map_: dict[str, DayStatus], *, today: date | None = None) -> str:
"""Render the year-to-date logged/elapsed/adherent tally line.
``today`` defaults to the real current date for live UI use; tests pass
it explicitly for a deterministic elapsed-day count.
"""
tally = year_to_date_tally(status_map_, today=today)
return (
f"This year: logged {tally.logged_days}/{tally.elapsed_days} days · "
f"{tally.adherent_days} within budget"
)