steam-backlog-enforcer/steam_backlog_enforcer/_attribution_labels.py
Krzysztof kuhy Rudnicki 1faf211767 Show which games make up the gaming budget, and bill osu!lazer
The budget tab answered "how much did I play" but not "what did I play":
playtime_state.json and playtime_history.json each stored one aggregate
seconds figure per gaming day, so the 14-day chart was a row of featureless
bars. Separately, qualifying_pids had exactly two sources — the SteamAppId
env var and a hardcoded 16-launcher frozenset — so osu!lazer, which sets no
SteamAppId and matches no launcher name, was never billed at all.

qualifying_pids now returns pid -> attribution key instead of a bare pid set.
The app id was already in hand and thrown away on its first line; it now
survives into PlaytimeState.per_game, alongside a user-editable
counted_processes list in config.json seeded with osu!lazer.

Two things the parts/whole relationship forces:

  - per_game only ever sums to AT MOST seconds, never equals it. backdate
    refunds the idle grace on every engaged-to-paused edge, and
    _state_or_recover synthesises a full budget with no breakdown. The
    refund is debited from last_credited_key, and the remainder is rendered
    as "Unattributed" rather than stored — one path then covers legacy days,
    focus-probe failures and drift alike.

  - counted_processes is kept apart from LAUNCHER_PROCESS_NAMES. That
    frozenset is also the total-block kill list, and it routes through
    kill_and_uninstall_launchers, which pacman -R's the owning package.
    Counted entries are killed on total block, never uninstalled.

Both storage formats stay at schema 1: load_state already filters to
dataclass fields, so a record without per_game migrates for free, and the
history reader has to accept both a bare float and an object regardless, so
a version bump would distinguish nothing.

Chart segments use the shared design system's categorical ramp (--cat-1..6),
capped at six games plus "Other" because a seventh distinguishable hue does
not exist under simulated CVD. The red over-budget fill is gone: colour now
encodes which game, and the dashed budget line alone says over or under.

Snapshot persistence moves to _snapshot.py to keep config.py under the
250-line cap. Three modules bound config paths at import time, which
bypasses the conftest redirect — they now reach them through the module.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MKFzwzwRU1JD7SFLHtQBsz
2026-08-29 18:32:03 +02:00

93 lines
2.8 KiB
Python

"""Turning attribution keys into names a human recognises.
Keys are stable (``app:475150``); labels are not (Steam renames games, and a
user can retitle a ``counted_processes`` entry). So keys are what get stored in
state and history, and this module resolves them for display.
Steam names come from ``appmanifest_<id>.acf`` rather than ``snapshot.json``:
a game that is *running* is by definition installed, so its manifest exists and
is a few hundred bytes, whereas the snapshot is ~11 MB and would be read on
every three-second tick and every five-second UI poll.
"""
from __future__ import annotations
import contextlib
import re
from typing import TYPE_CHECKING, Final
from steam_backlog_enforcer import _steam_state
from steam_backlog_enforcer._counted_procs import labels_by_key, load_counted_processes
if TYPE_CHECKING:
from collections.abc import Iterable
_APP_PREFIX: Final = "app:"
_PROC_PREFIX: Final = "proc:"
_LAUNCHER_PREFIX: Final = "launcher:"
# Same pattern game_uninstall.get_installed_games() uses on the same files.
_NAME_RE: Final = re.compile(r'"name"\s+"([^"]+)"')
# Manifest names never change while a game runs, and the daemon is long-lived.
_app_names: dict[int, str] = {}
def _steam_name(app_id: int) -> str | None:
"""Return *app_id*'s name from its appmanifest, or ``None``.
Args:
app_id: Steam application id.
Returns:
The manifest's ``name`` field, or ``None`` if unreadable.
"""
cached = _app_names.get(app_id)
if cached is not None:
return cached
manifest = _steam_state.STEAMAPPS_PATH / f"appmanifest_{app_id}.acf"
with contextlib.suppress(OSError):
match = _NAME_RE.search(manifest.read_text(encoding="utf-8"))
if match:
name = match.group(1)
_app_names[app_id] = name
return name
return None
def label_for(key: str) -> str:
"""Return a display name for an attribution *key*.
Falls back to the key itself, which is ugly but never wrong — an
unresolvable game is still better identified by ``app:475150`` than by a
blank row.
Args:
key: An ``app:``/``proc:``/``launcher:`` attribution key.
Returns:
The display label.
"""
if key.startswith(_APP_PREFIX):
raw = key[len(_APP_PREFIX) :]
if raw.isdigit():
return _steam_name(int(raw)) or key
return key
if key.startswith(_PROC_PREFIX):
return labels_by_key(load_counted_processes()).get(key, key)
if key.startswith(_LAUNCHER_PREFIX):
return key[len(_LAUNCHER_PREFIX) :]
return key
def labels_for(keys: Iterable[str]) -> dict[str, str]:
"""Resolve every key in *keys* to its label.
Args:
keys: Any iterable of attribution keys.
Returns:
Mapping of key to display label.
"""
return {key: label_for(key) for key in keys}