diff --git a/docs/superpowers/contracts/game-rec-auto-2026-11-22.json b/docs/superpowers/contracts/game-rec-auto-2026-11-22.json new file mode 100644 index 00000000..aedd72a1 --- /dev/null +++ b/docs/superpowers/contracts/game-rec-auto-2026-11-22.json @@ -0,0 +1,16 @@ +{ + "title": "game-rec: automatic game recording watcher in linux_configuration/gaming", + "objective": "Launching a game starts a 3-track recording (screen, game audio, mic) without a keypress; a relaunch within 30 s continues the same recording; the recording stops 30 s after the final quit; the i3 hotkey and i3blocks indicator control and show it.", + "acceptance_criteria": [ + "features/setup_game_rec.sh exits 0 on a fresh guest and leaves game-rec-auto.service active with ExecStart on gaming/game_rec_watch.sh.", + "A game scope appearing starts a recording; game-rec status reports recording with pid and auto ids.", + "Quitting and relaunching within 30 s resumes the same recording instead of starting a new one.", + "A systemd daemon-reload while a game runs does not drop the live scope or stop the recording.", + "The hotkey start names every spelling of the game when it is not yet in --list-application-audio." + ], + "out_of_scope": [ + "python_pkg/app_icons/ and other unrelated dirty files.", + "Uploading or post-processing recordings." + ], + "verifier": "bats linux_configuration/tests/test_game_rec*.bats (47 passed), pytest test_game_rec_scopes.py + test_game_rec_dbus.py (18 passed); vmbox guest gamerec setup exit 0 with unit active; host deploy at 22:46 recording with NRestarts=0." +} diff --git a/docs/superpowers/evidence/game-rec-auto-2026-11-22.json b/docs/superpowers/evidence/game-rec-auto-2026-11-22.json new file mode 100644 index 00000000..8f3f4588 --- /dev/null +++ b/docs/superpowers/evidence/game-rec-auto-2026-11-22.json @@ -0,0 +1,51 @@ +{ + "intent": "game-rec records games automatically: a systemd user watcher starts a 3-track gpu-screen-recorder recording when a game scope appears, keeps it through a 30 s relaunch grace, and stops it after a final quit; i3 hotkey and an i3blocks indicator drive and show it.", + "scope": [ + "linux_configuration/gaming/ (game_rec.sh, game_rec_lib.sh, game_rec_watch.sh, game_rec_scopes.py, game_rec_dbus.py, README.md)", + "linux_configuration/features/setup_game_rec.sh and features/systemd/game-rec-auto.service", + "linux_configuration/i3/config, linux_configuration/i3blocks/config and i3blocks/game_rec.sh", + "linux_configuration/tests/ (conftest.py, game_rec_helpers.bash, test_game_rec*.bats, test_game_rec_*.py)", + "Non-goals: python_pkg/app_icons/ and other dirty files" + ], + "changes": [ + "Moved game-rec scripts from linux_configuration/scripts/ to linux_configuration/gaming/ and redeployed the live watcher from there", + "Watcher tracks game scopes over D-Bus, keeps a live scope across systemd daemon-reload, and resumes the same recording when a game relaunches within 30 s", + "Hotkey start names every spelling of the game when it is not yet in --list-application-audio", + "setup_game_rec.sh installs dependencies and enables game-rec-auto.service" + ], + "verification": [ + { + "command": "~/.claude/scripts/capped.sh timeout 55 bats linux_configuration/tests/test_game_rec*.bats", + "result": "pass", + "evidence": "47/47 passed; red->green: 'game not in --list-application-audio yet: hotkey start names every spelling'" + }, + { + "command": "~/.claude/scripts/capped.sh timeout 55 python -m pytest -c pyproject.toml --rootdir . -o addopts= -p no:xdist -q linux_configuration/tests/test_game_rec_scopes.py linux_configuration/tests/test_game_rec_dbus.py", + "result": "pass", + "evidence": "18/18 passed; red->green: test_daemon_reload_of_live_scope_is_not_removed[unit-removed|state]" + }, + { + "command": "vmbox guest gamerec: bash linux_configuration/features/setup_game_rec.sh (pacman shimmed)", + "result": "pass", + "evidence": "exit 0, game-rec-auto.service active, ExecStart /bin/bash .../gaming/game_rec_watch.sh, game-rec status idle" + }, + { + "command": "host deploy 22:46: systemctl --user show game-rec-auto.service; game-rec status", + "result": "pass", + "evidence": "ExecStart on gaming/, NRestarts=0, status recording pid=1498936 auto=2708450" + }, + { + "command": "live play test with Oh Deer, journalctl --user -u game-rec-auto.service", + "result": "pass", + "evidence": "3-track recording, app audio track max -12.8 dB; quit and relaunch within 30 s grace resumed the same recording (22:18:22 gone/grace, 22:18:29 resume)" + } + ], + "risks": [ + "Not yet observed live: the stop 30 s after a final quit", + "Not yet observed live: a daemon-reload during a game with the new keep-live-scope fix" + ], + "rollback": [ + "Revert this commit", + "systemctl --user disable --now game-rec-auto.service" + ] +} diff --git a/linux_configuration/features/setup_game_rec.sh b/linux_configuration/features/setup_game_rec.sh new file mode 100755 index 00000000..41d1e0b0 --- /dev/null +++ b/linux_configuration/features/setup_game_rec.sh @@ -0,0 +1,70 @@ +#!/bin/bash + +# ============================================================================ +# Install game-rec (gaming/game_rec.sh): pacman deps, the ~/.local/bin/game-rec +# symlink, the i3blocks indicator symlink, the $mod+Shift+g hotkey in the +# live i3 config, and the game-rec-auto user service (gaming/game_rec_watch.sh, +# enabled at login, restarted here; recordings live in their own scopes, so a +# restart never stops one). Idempotent. It never reloads i3 or restarts +# i3blocks (a game may be running): it prints what to run instead. +# ============================================================================ + +set -euo pipefail + +SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +readonly REPO_DIR="${SCRIPT_DIR%/*}" +readonly PACKAGES=(gpu-screen-recorder xdotool xorg-xrandr util-linux coreutils procps-ng + python-jeepney systemd) +# Single-quoted on purpose: i3 passes $HOME through to sh -c. +# shellcheck disable=SC2016 +readonly HOTKEY='bindsym $mod+Shift+g exec --no-startup-id $HOME/.local/bin/game-rec toggle' +readonly I3_CONFIG="$HOME/.config/i3/config" +readonly UNIT=game-rec-auto.service +readonly UNIT_DIR="$HOME/.config/systemd/user" + +install_packages() { + local pkg + local -a missing=() + for pkg in "${PACKAGES[@]}"; do + pacman -Q "$pkg" >/dev/null 2>&1 || missing+=("$pkg") + done + ((${#missing[@]} == 0)) || sudo pacman -S --needed --noconfirm "${missing[@]}" +} + +link() { + mkdir -p "${2%/*}" + ln -sfn "$1" "$2" +} + +add_hotkey() { + if [[ ! -f $I3_CONFIG ]]; then + printf 'skip hotkey: %s not found\n' "$I3_CONFIG" + return 0 + fi + grep -qF -- "$HOTKEY" "$I3_CONFIG" && return 0 + printf '\n# game recorder (linux_configuration/gaming/game_rec.sh)\n%s\n' \ + "$HOTKEY" >>"$I3_CONFIG" +} + +install_unit() { + mkdir -p "$UNIT_DIR" + sed "s|@GAME_REC_DIR@|$REPO_DIR/gaming|" "$REPO_DIR/features/systemd/$UNIT" \ + >"$UNIT_DIR/$UNIT" + systemctl --user daemon-reload + systemctl --user enable "$UNIT" >/dev/null + systemctl --user restart "$UNIT" +} + +main() { + install_packages + chmod +x "$REPO_DIR/gaming/game_rec.sh" "$REPO_DIR/gaming/game_rec_watch.sh" \ + "$REPO_DIR/i3blocks/game_rec.sh" + link "$REPO_DIR/gaming/game_rec.sh" "$HOME/.local/bin/game-rec" + link "$REPO_DIR/i3blocks/game_rec.sh" "$HOME/.config/i3blocks/game_rec.sh" + add_hotkey + install_unit + printf 'game-rec installed. To activate (not done here):\n' + printf ' i3-msg restart (re-reads the hotkey, restarts i3bar + i3blocks)\n' +} + +main "$@" diff --git a/linux_configuration/features/systemd/game-rec-auto.service b/linux_configuration/features/systemd/game-rec-auto.service new file mode 100644 index 00000000..9f83645c --- /dev/null +++ b/linux_configuration/features/systemd/game-rec-auto.service @@ -0,0 +1,21 @@ +[Unit] +Description=Record every Steam game with game-rec, start to exit +After=graphical-session.target +PartOf=graphical-session.target +# A broken helper (exit 1 on every start) shows as a failed unit, not a loop. +StartLimitIntervalSec=300 +StartLimitBurst=5 + +[Service] +Type=simple +Environment=DISPLAY=:0 +# The login's cookie; i3 may not have exported XAUTHORITY to systemd yet. +Environment=XAUTHORITY=%h/.Xauthority +# Recordings run in their own transient scopes (systemd-run --scope), so a +# stop or restart here never kills one. +ExecStart=/bin/bash @GAME_REC_DIR@/game_rec_watch.sh +Restart=on-failure +RestartSec=3s + +[Install] +WantedBy=graphical-session.target diff --git a/linux_configuration/gaming/README.md b/linux_configuration/gaming/README.md index 7edbf9cd..5be8b01d 100644 --- a/linux_configuration/gaming/README.md +++ b/linux_configuration/gaming/README.md @@ -62,3 +62,30 @@ To stop: close the Steam window or `pkill -u player2 -f steam`. | ------ | ---------- | ----------- | | DP-0 | 3840×2160 | kuhy (main) | | HDMI-0 | 2560×1440 | player2 | + +## game-rec (record every Steam game) + +`game_rec.sh` records the game's monitor with gpu-screen-recorder: mic, game +and desktop audio as three tracks. `$mod+Shift+g` toggles it. The +`game-rec-auto` user service runs `game_rec_watch.sh`, which starts a +recording when a Steam game scope appears and stops it 30 s after the game +exits. `game_rec_scopes.py` feeds the watcher those scope events from +systemd's D-Bus signals. + +Helpers (setup_game_rec.sh installs neither; each sits next to its caller's +resolved path): `game_rec.sh` sources `game_rec_lib.sh` (state files, game +and monitor detection, app-audio matching), and `game_rec_scopes.py` imports +`game_rec_dbus.py` (the jeepney bus, match rules, the "is this unit still +live" query). + +Install or update (links `~/.local/bin/game-rec`, renders and restarts the +unit; a running recording survives the restart): + +```bash +~/src/testsAndMisc/linux_configuration/features/setup_game_rec.sh +``` + +Tests: `linux_configuration/tests/test_game_rec*.bats`, +`linux_configuration/tests/test_game_rec_scopes.py` and +`test_game_rec_dbus.py` (fake bus and connection shared via +`test_game_rec_fakes.py`, which holds no tests). diff --git a/linux_configuration/gaming/game_rec.sh b/linux_configuration/gaming/game_rec.sh new file mode 100755 index 00000000..540bf0ac --- /dev/null +++ b/linux_configuration/gaming/game_rec.sh @@ -0,0 +1,239 @@ +#!/bin/bash +# ============================================================================ +# game-rec start|stop|toggle|status|auto [on|off]: NVENC recording +# (gpu-screen-recorder) of the monitor the Steam game is on (window class +# steam_app_, else the focused window, else DP-2) with three opus +# tracks in order: mic, the game only (the --list-application-audio entry that +# matches the exe or Steam dir name, ignoring case, spaces, punctuation and +# .exe), everything. The game comes from the Steam reaper's NUL-split /proc +# argv (paths with spaces). +# State: $XDG_RUNTIME_DIR/game-rec.pid = recorder pid + output path. stop and +# status act only on a pid whose cmdline is gpu-screen-recorder with that +# exact `-o `; anything else (e.g. a systemd unit's recorder) is never +# signalled and its pidfile is stale. stop = SIGINT (finalises the file). +# Never deletes recordings. Refreshes the i3blocks block (signal 12) on +# start/stop and, via the detached `_watch` helper, when the recorder dies. +# +# Auto mode (gaming/game_rec_watch.sh, the game-rec-auto user service): +# `start --auto APPID` records that AppID's game, `stop --auto APPID` stops a +# recording only if it is marked auto for that AppID, `adopt APPID` marks the +# running recording auto. The mark is $XDG_RUNTIME_DIR/game-rec.auto (pid, +# output, AppID); it counts only while pid + output match the pidfile, so a +# manual (hotkey) recording is never stopped by the watcher. `auto off` +# pauses new auto starts until `auto on` or the next login. +# Overrides: GAME_REC_{DIR,MONITOR,FPS,MIN_FREE_GB,PROC_ROOT,START_GRACE, +# STOP_TIMEOUT,BAR_SIGNAL (0 = off),PKILL}. +# State-file, detection and app-audio helpers: gaming/game_rec_lib.sh. +# ============================================================================ + +set -euo pipefail + +readonly SELF="${BASH_SOURCE[0]}" +SELF_DIR=$(dirname -- "$(readlink -f -- "$SELF")") +readonly SELF_DIR +readonly REC_DIR="${GAME_REC_DIR:-$HOME/Videos/recordings}" +readonly FPS="${GAME_REC_FPS:-60}" +readonly MIN_FREE_GB="${GAME_REC_MIN_FREE_GB:-20}" +readonly START_GRACE="${GAME_REC_START_GRACE:-1}" +readonly STOP_TIMEOUT="${GAME_REC_STOP_TIMEOUT:-15}" +readonly BAR_SIGNAL="${GAME_REC_BAR_SIGNAL:-12}" +readonly PKILL="${GAME_REC_PKILL:-pkill}" + +# State files, game/monitor detection, app-audio matching; sets STATE_DIR, +# PIDFILE, GSR and the REC_*/GAME_* globals. +# shellcheck source=game_rec_lib.sh +source "$SELF_DIR/game_rec_lib.sh" + +readonly AUTO_OFF="$STATE_DIR/game-rec.auto-off" +readonly LOG="$STATE_DIR/game-rec.log" + +MARK_APPID='' + +# auto_marked: the current recording (read_pidfile first) carries an auto +# mark; sets MARK_APPID. +auto_marked() { + local pid='' out='' appid='' + MARK_APPID='' + [[ -r $AUTO_MARK ]] || return 1 + { read -r pid && read -r out && read -r appid; } <"$AUTO_MARK" || true + [[ $pid == "$REC_PID" && $out == "$REC_OUT" && $appid =~ ^[0-9]+$ ]] || return 1 + MARK_APPID=$appid +} + +# write_mark APPID: mark the current recording auto (atomic replace). +write_mark() { + printf '%s\n%s\n%s\n' "$REC_PID" "$REC_OUT" "$1" >"$AUTO_MARK.$$" + mv -f "$AUTO_MARK.$$" "$AUTO_MARK" +} + +usage() { + printf 'Usage: %s start|stop|toggle|status|auto [on|off]\n' "${SELF##*/}" +} + +die() { + printf 'game-rec: %s\n' "$1" >&2 + exit 1 +} + +require_tools() { + local tool + for tool in "$GSR" xdotool xrandr setsid tail timeout df; do + command -v "$tool" >/dev/null 2>&1 || + die "$tool missing: run linux_configuration/features/setup_game_rec.sh" + done +} + +refresh_bar() { + ((BAR_SIGNAL > 0)) || return 0 + "$PKILL" "-RTMIN+$BAR_SIGNAL" -x i3blocks >/dev/null 2>&1 || true +} + +check_free_space() { + local -a lines + mapfile -t lines < <(df --output=avail -B1 -- "$REC_DIR") + local avail=${lines[1]:-} + avail=${avail// /} + [[ $avail =~ ^[0-9]+$ ]] || die "cannot read free space of $REC_DIR" + if ((avail < MIN_FREE_GB * 1024 * 1024 * 1024)); then + printf 'game-rec: refusing, %d GB free in %s, need %d GB\n' \ + $((avail / 1024 / 1024 / 1024)) "$REC_DIR" "$MIN_FREE_GB" >&2 + return 1 + fi +} + +# spawn_recorder MONITOR APP OUT [APPID]: start gpu-screen-recorder, write the +# pidfile (and the auto mark), and succeed if it is still up after the grace. +spawn_recorder() { + local monitor=$1 app=$2 out=$3 auto=${4:-} pid + local -a args=(-w "$monitor" -f "$FPS" -c mkv -k hevc -q high -ac opus -a default_input) + [[ -z $app ]] || args+=(-a "app:$app") + args+=(-a default_output -o "$out") + # setsid execs (no fork) here, so $! is the recorder's own pid; env resets + # SIGINT, which bash leaves ignored for background jobs. + setsid env --default-signal=INT "$GSR" "${args[@]}" "$LOG" 2>&1 & + pid=$! + printf '%s\n%s\n' "$pid" "$out" >"$PIDFILE" + REC_PID=$pid REC_OUT=$out + [[ -z $auto ]] || write_mark "$auto" + sleep "$START_GRACE" + kill -0 "$pid" 2>/dev/null && return 0 + clear_state + tail -n 5 "$LOG" >&2 || true + return 1 +} + +# cmd_start [APPID]: with APPID it is an auto start for that Steam game. +cmd_start() { + local auto=${1:-} monitor=${GAME_REC_MONITOR:-} app='' guessed='' slug=desktop stamp out + recording && die "already recording: $REC_OUT" + clear_state + mkdir -p "$REC_DIR" "$STATE_DIR" + check_free_space || return 1 + detect_game "$auto" + [[ -n $monitor ]] || monitor=$(detect_monitor "$auto") + if [[ -n $GAME_EXE ]]; then + slug=$(slugify "$GAME_EXE") + app=$(match_app_audio "$GAME_EXE" "$GAME_DIR") + # No stream yet: an auto start runs while the game is still loading, + # and a hotkey start may come right after launch. + if [[ -z $app ]]; then + app=$(app_candidates) + guessed=1 + fi + elif [[ -n $auto ]]; then + slug="steam-$auto" + fi + printf -v stamp '%(%Y%m%d-%H%M%S)T' -1 + out="$REC_DIR/${slug:-game}-$stamp.mkv" + [[ ! -e $out ]] || out="$REC_DIR/${slug:-game}-$stamp-$$.mkv" + if ! spawn_recorder "$monitor" "$app" "$out" "$auto"; then + # Guessed names are unproven: a recording without the game track + # beats no recording. + [[ -n $guessed ]] || die "recorder exited at once (log: $LOG)" + printf 'game-rec: recorder refused app:%s, retrying without it\n' "$app" >&2 + spawn_recorder "$monitor" '' "$out" "$auto" || + die "recorder exited at once (log: $LOG)" + fi + setsid "$BASH" "$SELF" _watch "$REC_PID" /dev/null 2>&1 & + refresh_bar + printf '%s\n' "$out" +} + +# cmd_stop [APPID]: with APPID, stop only an auto recording of that game. +cmd_stop() { + read_pidfile || die 'not recording' + if ! owns "$REC_PID" "$REC_OUT"; then + clear_state + refresh_bar + die 'stale pidfile removed, nothing signalled' + fi + if [[ -n ${1:-} ]] && ! { auto_marked && [[ $MARK_APPID == "$1" ]]; }; then + die "not an auto recording of $1, left running" + fi + kill -INT "$REC_PID" + # Still finalising after the timeout: keep the pidfile, _watch clears it. + timeout "$STOP_TIMEOUT" tail --pid="$REC_PID" -f /dev/null || + die "recorder $REC_PID still finalising $REC_OUT" + clear_state + refresh_bar + printf '%s\n' "$REC_OUT" +} + +# cmd_adopt APPID: mark the running recording auto, so it stops with the game. +cmd_adopt() { + [[ $1 =~ ^[0-9]+$ ]] || die "bad AppID: $1" + recording || die 'not recording' + write_mark "$1" + printf 'adopted %s for %s\n' "$REC_OUT" "$1" +} + +cmd_status() { + recording || { printf 'idle\n' && return 1; } + if auto_marked; then + printf 'recording pid=%s %s auto=%s\n' "$REC_PID" "$REC_OUT" "$MARK_APPID" + else + printf 'recording pid=%s %s\n' "$REC_PID" "$REC_OUT" + fi +} + +cmd_auto() { + case ${1:-} in + on) rm -f "$AUTO_OFF" ;; + off) mkdir -p "$STATE_DIR" && : >"$AUTO_OFF" ;; + '') if [[ -e $AUTO_OFF ]]; then printf 'off\n'; else printf 'on\n'; fi ;; + *) usage >&2 && exit 2 ;; + esac +} + +# _watch PID: wait for the recorder to exit, then clear its pidfile and mark. +cmd_watch() { + tail --pid="$1" -f /dev/null 2>/dev/null || true + if read_pidfile && [[ $REC_PID == "$1" ]]; then + clear_state + fi + refresh_bar +} + +# auto_arg FLAG APPID: the AppID after --auto, or nothing without the flag. +auto_arg() { + [[ -n ${1:-} ]] || return 0 + [[ $1 == --auto && ${2:-} =~ ^[0-9]+$ ]] || die 'usage: --auto APPID' + printf '%s\n' "$2" +} + +main() { + local appid + case ${1:-} in + start) appid=$(auto_arg "${2:-}" "${3:-}") && require_tools && cmd_start "$appid" ;; + stop) appid=$(auto_arg "${2:-}" "${3:-}") && cmd_stop "$appid" ;; + toggle) if recording; then cmd_stop; else require_tools && cmd_start; fi ;; + status) cmd_status ;; + auto) cmd_auto "${2:-}" ;; + adopt) cmd_adopt "${2:?appid}" ;; + _watch) cmd_watch "${2:?pid}" ;; + -h | --help) usage ;; + *) usage >&2 && exit 2 ;; + esac +} + +main "$@" diff --git a/linux_configuration/gaming/game_rec_dbus.py b/linux_configuration/gaming/game_rec_dbus.py new file mode 100755 index 00000000..c3a7cf8c --- /dev/null +++ b/linux_configuration/gaming/game_rec_dbus.py @@ -0,0 +1,177 @@ +#!/usr/bin/python3 +"""systemd D-Bus plumbing for ``game_rec_scopes.py``. + +The small :class:`Bus` interface the scope watcher talks to, its jeepney +implementation (:class:`JeepneyBus`), the match rules, and :func:`unit_live`, +which asks systemd whether a unit still runs. Imported from the script's own +directory; no test opens a real bus (they pass a fake :class:`Bus`/``Conn``). +""" + +from __future__ import annotations + +from collections import deque +from typing import TYPE_CHECKING, Any, Protocol + +from jeepney import DBusAddress, HeaderFields, MatchRule, new_method_call +from jeepney.bus_messages import message_bus +from jeepney.wrappers import DBusErrorResponse, unwrap_msg + +if TYPE_CHECKING: + from jeepney import Message + from jeepney.io.common import FilterHandle + +LIVE_STATES = frozenset({"active", "reloading"}) + +SYSTEMD = "org.freedesktop.systemd1" +MANAGER_PATH = "/org/freedesktop/systemd1" +MANAGER_IFACE = "org.freedesktop.systemd1.Manager" +UNIT_IFACE = "org.freedesktop.systemd1.Unit" +PROPS_IFACE = "org.freedesktop.DBus.Properties" + +Signal = tuple[str, str, str, tuple[Any, ...]] + + +class Bus(Protocol): + """The four bus operations the watcher needs (jeepney or a test fake).""" + + def call( + self, + path: str, + interface: str, + method: str, + signature: str | None = None, + body: tuple[Any, ...] = (), + ) -> tuple[Any, ...]: + """Call a systemd method and return the reply body.""" + + def add_match(self, rule: MatchRule) -> None: + """Ask the bus daemon to route signals matching ``rule`` to us.""" + + def remove_match(self, rule: MatchRule) -> None: + """Undo :meth:`add_match`.""" + + def discard_pending(self, path: str) -> None: + """Drop queued PropertiesChanged of ``path`` (older than a Get reply).""" + + def next_signal(self) -> Signal: + """Block until the next signal: (path, interface, member, body).""" + + +class Conn(Protocol): + """The parts of jeepney's blocking DBusConnection that are used here.""" + + def filter(self, rule: MatchRule, *, queue: deque[Message]) -> FilterHandle: + """Queue incoming messages that match ``rule``.""" + + def send_and_get_reply(self, message: Message) -> Message: + """Send a method call and block for its reply.""" + + def recv_messages(self) -> None: + """Block for one message and run it through the filters.""" + + +def manager_rule() -> MatchRule: + """Match systemd's Manager signals (UnitNew, UnitRemoved, jobs).""" + return MatchRule( + type="signal", sender=SYSTEMD, interface=MANAGER_IFACE, path=MANAGER_PATH + ) + + +def props_rule(path: str) -> MatchRule: + """Match PropertiesChanged of one unit's Unit interface.""" + rule = MatchRule( + type="signal", + sender=SYSTEMD, + interface=PROPS_IFACE, + member="PropertiesChanged", + path=path, + ) + rule.add_arg_condition(0, UNIT_IFACE) + return rule + + +class JeepneyBus: + """:class:`Bus` over a jeepney blocking connection.""" + + def __init__(self, conn: Conn) -> None: + """Queue every incoming signal, including those that arrive mid-call.""" + self._conn = conn + self._signals: deque[Message] = deque() + self._filter = conn.filter(MatchRule(type="signal"), queue=self._signals) + + def call( + self, + path: str, + interface: str, + method: str, + signature: str | None = None, + body: tuple[Any, ...] = (), + ) -> tuple[Any, ...]: + """Call a systemd method; raises DBusErrorResponse on an error reply.""" + addr = DBusAddress(path, bus_name=SYSTEMD, interface=interface) + reply = self._conn.send_and_get_reply( + new_method_call(addr, method, signature, body) + ) + result: tuple[Any, ...] = unwrap_msg(reply) + return result + + def add_match(self, rule: MatchRule) -> None: + """AddMatch on the bus daemon.""" + unwrap_msg(self._conn.send_and_get_reply(message_bus.AddMatch(rule))) + + def remove_match(self, rule: MatchRule) -> None: + """RemoveMatch on the bus daemon.""" + unwrap_msg(self._conn.send_and_get_reply(message_bus.RemoveMatch(rule))) + + def discard_pending(self, path: str) -> None: + """Drop queued PropertiesChanged of ``path``. + + Everything queued when a reply arrives was sent before it (one + connection keeps order), so after a Get these are stale. + """ + kept = [ + msg + for msg in self._signals + if not ( + msg.header.fields.get(HeaderFields.path) == path + and msg.header.fields.get(HeaderFields.member) == "PropertiesChanged" + ) + ] + self._signals.clear() + self._signals.extend(kept) + + def next_signal(self) -> Signal: + """Block in recv until a signal is queued, then decode its header. + + The local filter queues signals only; replies and errors are dropped. + """ + while not self._signals: + self._conn.recv_messages() + msg = self._signals.popleft() + fields = msg.header.fields + return ( + fields.get(HeaderFields.path, ""), + fields.get(HeaderFields.interface, ""), + fields.get(HeaderFields.member, ""), + msg.body, + ) + + +def unit_live(bus: Bus, name: str, path: str) -> bool: + """Return whether systemd still has ``name`` loaded and live. + + systemd answers only after a running daemon-reload has finished, so the + reply is the state after any replayed signals. + """ + try: + (unit_path,) = bus.call(MANAGER_PATH, MANAGER_IFACE, "GetUnit", "s", (name,)) + ((_sig, active),) = bus.call( + str(unit_path), PROPS_IFACE, "Get", "ss", (UNIT_IFACE, "ActiveState") + ) + except DBusErrorResponse: + # NoSuchUnit: unloaded, so really gone. + return False + # Changes queued before the reply are older than it, as in + # game_rec_scopes._follow. + bus.discard_pending(path) + return str(active) in LIVE_STATES diff --git a/linux_configuration/gaming/game_rec_lib.sh b/linux_configuration/gaming/game_rec_lib.sh new file mode 100755 index 00000000..915e4fc3 --- /dev/null +++ b/linux_configuration/gaming/game_rec_lib.sh @@ -0,0 +1,172 @@ +#!/bin/bash +# ============================================================================ +# game_rec_lib.sh: what game_rec.sh knows without touching the recorder. +# Sourced (never run) by game_rec.sh from its resolved dir. +# - state files: the pidfile (recorder pid + output path), its removal +# with the auto mark (game_rec.sh reads and writes the mark itself), and +# the ownership rule that stops game-rec from ever signalling a +# gpu-screen-recorder it did not start; +# - game detection from the Steam reaper's NUL-split /proc argv; +# - the game's monitor (xdotool window centre -> xrandr monitor); +# - app-audio matching (--list-application-audio name, or the guessed names +# while the game has no stream yet) and the output-file slug. +# Owns the globals below; game_rec.sh reads them after each call. +# ============================================================================ + +readonly GSR=gpu-screen-recorder +readonly DEFAULT_MONITOR=DP-2 +readonly PROC_ROOT="${GAME_REC_PROC_ROOT:-/proc}" +readonly STATE_DIR="${XDG_RUNTIME_DIR:-/run/user/$UID}" +readonly PIDFILE="$STATE_DIR/game-rec.pid" +readonly AUTO_MARK="$STATE_DIR/game-rec.auto" + +REC_PID='' REC_OUT='' GAME_APPID='' GAME_EXE='' GAME_DIR='' + +read_pidfile() { + REC_PID='' REC_OUT='' + [[ -r $PIDFILE ]] || return 1 + { read -r REC_PID && read -r REC_OUT; } <"$PIDFILE" || true + [[ $REC_PID =~ ^[0-9]+$ && -n $REC_OUT ]] +} + +# owns PID OUT: PID is a live gpu-screen-recorder writing exactly OUT. +owns() { + local arg prev='' is_gsr=0 writes_out=0 + local -a argv=() + [[ $1 =~ ^[0-9]+$ ]] || return 1 + mapfile -d '' argv 2>/dev/null <"/proc/$1/cmdline" || return 1 + for arg in "${argv[@]}"; do + [[ ${arg##*/} == "$GSR" ]] && is_gsr=1 + [[ $prev == -o && $arg == "$2" ]] && writes_out=1 + prev=$arg + done + ((is_gsr && writes_out)) +} + +recording() { + read_pidfile && owns "$REC_PID" "$REC_OUT" +} + +clear_state() { + rm -f "$PIDFILE" "$AUTO_MARK" +} + +# detect_game [APPID]: sets GAME_APPID and GAME_EXE (basename) from the Steam +# reaper, if any; with APPID only that game's reaper counts. +detect_game() { + local want=${1:-} comm_file comm arg appid exe dir + local -a argv + for comm_file in "$PROC_ROOT"/[0-9]*/comm; do + read -r comm 2>/dev/null <"$comm_file" || continue + [[ $comm == reaper ]] || continue + mapfile -d '' argv 2>/dev/null <"${comm_file%/comm}/cmdline" || continue + [[ ${argv[1]:-} == SteamLaunch ]] || continue + appid='' exe='' dir='' + for arg in "${argv[@]}"; do + [[ $arg == AppId=* ]] && appid=${arg#AppId=} + if [[ ${arg,,} == *.exe ]]; then + exe=${arg##*/} + # steamapps/common//...: PipeWire often names the + # game after it instead of the exe (Oh Deer -> "OhDeer"). + [[ $arg == */steamapps/common/*/* ]] && dir=${arg#*/steamapps/common/} dir=${dir%%/*} + fi + done + [[ -z $want || $appid == "$want" ]] || continue + [[ -n $exe ]] && GAME_APPID=$appid GAME_EXE=$exe GAME_DIR=$dir + done + [[ -z $want ]] || GAME_APPID=$want + return 0 +} + +# monitor_at X Y: the xrandr monitor containing that point. +monitor_at() { + local line name mw mh mx my + local re='^ *[0-9]+: +[+*]*([^ ]+) +([0-9]+)/[0-9]+x([0-9]+)/[0-9]+\+([0-9]+)\+([0-9]+)' + while IFS= read -r line; do + [[ $line =~ $re ]] || continue + name=${BASH_REMATCH[1]} mw=${BASH_REMATCH[2]} mh=${BASH_REMATCH[3]} + mx=${BASH_REMATCH[4]} my=${BASH_REMATCH[5]} + if (($1 >= mx && $1 < mx + mw && $2 >= my && $2 < my + mh)); then + printf '%s\n' "$name" + return 0 + fi + done < <(xrandr --listmonitors 2>/dev/null) + return 1 +} + +# monitor_of_window WIN: the monitor holding the window's centre. +monitor_of_window() { + local key value + local -A g=() + [[ -n $1 ]] || return 1 + while IFS='=' read -r key value; do g[$key]=$value; done \ + < <(xdotool getwindowgeometry --shell "$1" 2>/dev/null) + [[ -n ${g[X]:-} && -n ${g[Y]:-} && -n ${g[WIDTH]:-} && -n ${g[HEIGHT]:-} ]] || return 1 + monitor_at $((g[X] + g[WIDTH] / 2)) $((g[Y] + g[HEIGHT] / 2)) +} + +# detect_monitor [auto]: an auto start runs while the game is still loading, +# when the focused window is Steam's, so it skips that fallback. +detect_monitor() { + local win + if [[ -n $GAME_APPID ]]; then + win=$(xdotool search --onlyvisible --class "^steam_app_${GAME_APPID}\$" 2>/dev/null | + head -n 1) || win='' + monitor_of_window "$win" && return 0 + fi + if [[ -n $GAME_EXE && -z ${1:-} ]]; then + win=$(xdotool getactivewindow 2>/dev/null) || win='' + monitor_of_window "$win" && return 0 + fi + printf '%s\n' "$DEFAULT_MONITOR" +} + +# app_key NAME: NAME lowercased, minus a .exe suffix and every non-alphanumeric +# ("Oh Deer", "OhDeer.exe" and "ohdeer" all give "ohdeer"). +app_key() { + local s=${1,,} + s=${s%.exe} + printf '%s\n' "${s//[^a-z0-9]/}" +} + +# match_app_audio NAME...: the --list-application-audio entry whose app_key +# equals any NAME's (the exe basename, the Steam game dir), in its spelling. +match_app_audio() { + local app name key + local -A want=() + for name in "$@"; do + [[ -n $name ]] || continue + key=$(app_key "$name") + [[ -z $key ]] || want[$key]=1 + done + ((${#want[@]})) || return 0 + while IFS= read -r app; do + key=$(app_key "$app") + [[ -n $key && -n ${want[$key]:-} ]] && printf '%s\n' "$app" && return 0 + done < <(timeout 5 "$GSR" --list-application-audio 2>/dev/null) + return 0 +} + +# app_candidates: before the game opens audio its PipeWire name is unknown, so +# name every spelling it may use (exe, exe minus .exe, Steam dir), merged into +# one track; gpu-screen-recorder links app: (any case) when the stream +# appears. Prints `A|app:B|app:C` (the caller adds the first `app:`). +app_candidates() { + local name joined='' + local -A seen=() + for name in "$GAME_EXE" "${GAME_EXE%.[eE][xX][eE]}" "$GAME_DIR"; do + [[ -n $name && -z ${seen[${name,,}]:-} ]] || continue + seen[${name,,}]=1 + joined+="${joined:+|app:}$name" + done + printf '%s\n' "$joined" +} + +slugify() { + local s=${1,,} + s=${s%.exe} + s=${s//[^a-z0-9]/-} + while [[ $s == *--* ]]; do s=${s//--/-}; done + s=${s#-} + printf '%s\n' "${s%-}" +} diff --git a/linux_configuration/gaming/game_rec_scopes.py b/linux_configuration/gaming/game_rec_scopes.py new file mode 100755 index 00000000..81fb7e56 --- /dev/null +++ b/linux_configuration/gaming/game_rec_scopes.py @@ -0,0 +1,191 @@ +#!/usr/bin/python3 +"""Print Steam game scopes of the systemd user manager as they come and go. + +Steam runs each game in a transient user scope ``app-steam-app-.scope``. +This helper prints one line per change on stdout (flushed) for +``game_rec_watch.sh``: ``new `` once a scope is active, ``removed `` +once it is inactive/failed or unloaded, and a single ``sync`` after the scopes +that already ran at startup. + +Event-driven, zero polling: one D-Bus connection blocks in recv. systemd only +broadcasts UnitNew/UnitRemoved while some client has called Manager.Subscribe, +so this one does (on the same connection, before listing, so no scope falls in +between). ActiveState comes from PropertiesChanged, matched per Steam scope +only. A UnitNew alone proves nothing: ``systemctl status `` loads a +stub unit and fires one, so a scope counts only once its ActiveState is live. +A ``systemctl --user daemon-reload`` replays UnitRemoved / ActiveState changes +for scopes that never stopped, so systemd is asked before any ``removed``. +It never uses BecomeMonitor/eavesdropping (a long-lived ``busctl monitor`` +once exhausted the dbus-broker quota). The bus plumbing lives in +``game_rec_dbus.py``. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from functools import partial +import sys +from typing import TYPE_CHECKING, TextIO + +from game_rec_dbus import ( + LIVE_STATES, + MANAGER_IFACE, + MANAGER_PATH, + PROPS_IFACE, + UNIT_IFACE, + JeepneyBus, + manager_rule, + props_rule, + unit_live, +) +from jeepney.io.blocking import open_dbus_connection +from jeepney.wrappers import DBusErrorResponse + +if TYPE_CHECKING: + from collections.abc import Callable + + from game_rec_dbus import Bus, Signal + +PREFIX = "app-steam-app" +SUFFIX = ".scope" +# Only these end a scope; activating/deactivating are on the way. +GONE_STATES = frozenset({"inactive", "failed"}) +# ListUnitsByPatterns rows: (name, description, load, active, sub, following, +# object path, job id, job type, job path). +_ROW_NAME, _ROW_ACTIVE, _ROW_PATH = 0, 3, 6 + + +def _never_live(_name: str, _path: str) -> bool: + return False + + +@dataclass +class ScopeTracker: + """Steam scopes seen so far, so each prints ``new``/``removed`` once. + + ``still_live(name, path)`` is asked before a ``removed``: True means the + signal was a reload replay and the scope still runs. + """ + + names: dict[str, str] = field(default_factory=dict) + live: set[str] = field(default_factory=set) + still_live: Callable[[str, str], bool] = _never_live + + @staticmethod + def wanted(name: str) -> bool: + """Return whether ``name`` looks like a Steam game scope.""" + return name.startswith(PREFIX) and name.endswith(SUFFIX) + + def track(self, name: str, path: str) -> bool: + """Start following ``path``; False if unwanted or already followed.""" + if not self.wanted(name) or path in self.names: + return False + self.names[path] = name + return True + + def state(self, path: str, active_state: str) -> str | None: + """Record a new ActiveState; return the line to print, if any.""" + name = self.names.get(path) + if name is None: + return None + if active_state in LIVE_STATES: + if name in self.live: + return None + self.live.add(name) + return f"new {name}" + if active_state not in GONE_STATES or name not in self.live: + return None + if self.still_live(name, path): + return None + self.live.discard(name) + return f"removed {name}" + + def forget(self, path: str) -> tuple[bool, str | None]: + """Stop following ``path``: (was followed, line to print). + + A live scope that systemd still runs stays followed: after a reload + it keeps its object path and match rule, so its real exit still counts. + """ + name = self.names.get(path) + if name is None: + return False, None + if name in self.live and self.still_live(name, path): + return False, None + del self.names[path] + if name not in self.live: + return True, None + self.live.discard(name) + return True, f"removed {name}" + + +def _emit(out: TextIO, line: str | None) -> None: + if line is not None: + out.write(line + "\n") + out.flush() + + +def _follow( + bus: Bus, tracker: ScopeTracker, name: str, path: str, active: str | None +) -> str | None: + """Follow a newly seen unit; return its first line, if any.""" + if not tracker.track(name, path): + return None + bus.add_match(props_rule(path)) + if active is None: + try: + ((_sig, active),) = bus.call( + path, PROPS_IFACE, "Get", "ss", (UNIT_IFACE, "ActiveState") + ) + except DBusErrorResponse: + # Gone already (or a status-query stub): wait for UnitRemoved. + return None + # Changes queued while the Get was in flight predate its answer: + # replaying them printed a false removed/new pair in vmbox. + bus.discard_pending(path) + return tracker.state(path, str(active)) + + +def _handle(bus: Bus, tracker: ScopeTracker, sig: Signal) -> str | None: + path, interface, member, body = sig + if interface == MANAGER_IFACE and member == "UnitNew": + return _follow(bus, tracker, body[0], body[1], None) + if interface == MANAGER_IFACE and member == "UnitRemoved": + followed, line = tracker.forget(body[1]) + if followed: + bus.remove_match(props_rule(body[1])) + return line + if interface == PROPS_IFACE and member == "PropertiesChanged": + iface, changed = body[0], body[1] + if iface == UNIT_IFACE and "ActiveState" in changed: + return tracker.state(path, str(changed["ActiveState"][1])) + return None + + +def run(bus: Bus, out: TextIO) -> None: + """Subscribe, print the running scopes and ``sync``, then follow changes.""" + tracker = ScopeTracker(still_live=partial(unit_live, bus)) + bus.add_match(manager_rule()) + bus.call(MANAGER_PATH, MANAGER_IFACE, "Subscribe") + (rows,) = bus.call( + MANAGER_PATH, MANAGER_IFACE, "ListUnitsByPatterns", "asas", ([], [PREFIX + "*"]) + ) + for row in rows: + _emit( + out, _follow(bus, tracker, row[_ROW_NAME], row[_ROW_PATH], row[_ROW_ACTIVE]) + ) + _emit(out, "sync") + while True: + _emit(out, _handle(bus, tracker, bus.next_signal())) + + +def main() -> int: + """Run on the session (user) bus until the reader goes away.""" + try: + run(JeepneyBus(open_dbus_connection(bus="SESSION")), sys.stdout) + except BrokenPipeError: + return 0 + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/linux_configuration/gaming/game_rec_watch.sh b/linux_configuration/gaming/game_rec_watch.sh new file mode 100755 index 00000000..8e527f0e --- /dev/null +++ b/linux_configuration/gaming/game_rec_watch.sh @@ -0,0 +1,226 @@ +#!/bin/bash +# ============================================================================ +# game-rec auto watcher (the game-rec-auto user service): record every Steam +# game automatically. +# +# Events come from game_rec_scopes.py, one line each: `new `, +# `removed ` for Steam's app-steam-app-.scope units, and +# one `sync` after the scopes already running at startup. Zero polling: the +# loop blocks in `read`; the 30 s exit grace is the `read -t` timeout, so +# nothing wakes while no game starts or stops, and only bash builtins run per +# event until there is something to do. +# +# - new scope, nothing recording, `game-rec auto` on: `game-rec start --auto +# `, inside its own transient scope (systemd-run --scope), so a +# watcher restart never kills the recording. +# - last scope of that AppID gone: after GRACE s `game-rec stop --auto ` +# (SIGINT, finalises the file). A scope of the same AppID within the grace +# keeps the same recording. game-rec refuses to stop anything not marked +# auto, so manual (hotkey) recordings are never stopped. +# - sync: a recording already running while a game runs is adopted (marked +# auto for that game); an auto recording whose game is gone gets the grace. +# - `auto off` blocks new starts only; a running auto recording still stops +# with its game. A different game during the grace is started after the +# stop. +# - The event stream ending (helper died) exits 1; systemd restarts us. +# Overrides: GAME_REC_AUTO_GRACE (s), GAME_REC_EVENTS (read this file or FIFO +# instead of running the helper), GAME_REC_BIN (game_rec.sh to call). +# ============================================================================ + +set -euo pipefail + +SELF_DIR=$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")") +readonly SELF_DIR +readonly GAME_REC="${GAME_REC_BIN:-$SELF_DIR/game_rec.sh}" +readonly HELPER="$SELF_DIR/game_rec_scopes.py" +readonly GRACE="${GAME_REC_AUTO_GRACE:-30}" +readonly EVENTS="${GAME_REC_EVENTS:-}" +readonly AUTO_OFF="${XDG_RUNTIME_DIR:-/run/user/$UID}/game-rec.auto-off" +readonly SCOPE_RE='^app-steam-app([0-9]+)-[0-9]+\.scope$' +readonly AUTO_RE=' auto=([0-9]+)$' + +declare -A LIVE=() # unit -> AppID, for every live Steam scope +declare -A DEADLINE=() # AppID -> epoch second its grace ends +SYNCED=0 +REC_STATUS='' # last `game-rec status` line ('' = not recording) + +log() { + printf '%s\n' "$*" +} + +game_rec() { + "$BASH" "$GAME_REC" "$@" +} + +# refresh_status: REC_STATUS = `game-rec status`, '' when idle. +refresh_status() { + REC_STATUS=$(game_rec status 2>/dev/null) || REC_STATUS='' +} + +# app_live APPID: some live scope belongs to APPID. +app_live() { + local unit + for unit in "${!LIVE[@]}"; do + [[ ${LIVE[$unit]} == "$1" ]] && return 0 + done + return 1 +} + +maybe_start() { + local appid=$1 + if [[ -e $AUTO_OFF ]]; then + log "off $appid" + return 0 + fi + refresh_status + if [[ -n $REC_STATUS ]]; then + log "busy $appid" + return 0 + fi + if systemd-run --user --scope --collect --quiet -- \ + "$BASH" "$GAME_REC" start --auto "$appid" >/dev/null; then + log "start $appid" + else + log "start failed $appid" + fi +} + +on_new() { + local unit=$1 appid + if [[ ! $unit =~ $SCOPE_RE ]]; then + log "ignore $unit" + return 0 + fi + appid=${BASH_REMATCH[1]} + LIVE[$unit]=$appid + if [[ -n ${DEADLINE[$appid]:-} ]]; then + unset "DEADLINE[$appid]" + log "resume $appid" + return 0 + fi + ((SYNCED)) || return 0 + app_live_others "$unit" "$appid" || maybe_start "$appid" +} + +# app_live_others UNIT APPID: APPID has a live scope other than UNIT. +app_live_others() { + local other + for other in "${!LIVE[@]}"; do + [[ $other != "$1" && ${LIVE[$other]} == "$2" ]] && return 0 + done + return 1 +} + +# grace_if_auto APPID: start the grace if the recording is auto for APPID. +grace_if_auto() { + refresh_status + [[ $REC_STATUS =~ $AUTO_RE && ${BASH_REMATCH[1]} == "$1" ]] || return 0 + DEADLINE[$1]=$((EPOCHSECONDS + GRACE)) + log "grace $1" +} + +on_removed() { + local unit=$1 appid + if [[ ! $unit =~ $SCOPE_RE ]]; then + log "ignore $unit" + return 0 + fi + appid=${LIVE[$unit]:-} + [[ -n $appid ]] || return 0 + unset "LIVE[$unit]" + app_live "$appid" && return 0 + log "gone $appid" + grace_if_auto "$appid" +} + +on_sync() { + local unit appid + SYNCED=1 + log sync + refresh_status + [[ -n $REC_STATUS ]] || return 0 + if [[ $REC_STATUS =~ $AUTO_RE ]]; then + appid=${BASH_REMATCH[1]} + app_live "$appid" || grace_if_auto "$appid" + return 0 + fi + for unit in "${!LIVE[@]}"; do + appid=${LIVE[$unit]} + game_rec adopt "$appid" >/dev/null && log "adopt $appid" + return 0 + done +} + +# expire: stop every recording whose grace has ended, then start a game that +# is still running (a different AppID that came up during the grace). +expire() { + local appid unit + for appid in "${!DEADLINE[@]}"; do + ((DEADLINE[$appid] <= EPOCHSECONDS)) || continue + unset "DEADLINE[$appid]" + if game_rec stop --auto "$appid" >/dev/null; then + log "stop $appid" + else + log "stop skipped $appid" + fi + for unit in "${!LIVE[@]}"; do + maybe_start "${LIVE[$unit]}" + break + done + done +} + +# next_wait: WAIT = seconds until the earliest grace ends ('' = none). +next_wait() { + local appid + WAIT='' + for appid in "${!DEADLINE[@]}"; do + if [[ -z $WAIT ]] || ((DEADLINE[$appid] - EPOCHSECONDS < WAIT)); then + WAIT=$((DEADLINE[$appid] - EPOCHSECONDS)) + fi + done +} + +handle() { + local verb=${1%% *} arg=${1#* } + case $verb in + new) on_new "$arg" ;; + removed) on_removed "$arg" ;; + sync) on_sync ;; + *) log "ignore $1" ;; + esac +} + +watch_events() { + local fd=$1 line rc WAIT + while :; do + next_wait + if [[ -z $WAIT ]]; then + IFS= read -r line <&"$fd" || return 1 + handle "$line" + elif ((WAIT <= 0)); then + expire + elif IFS= read -r -t "$WAIT" line <&"$fd"; then + handle "$line" + else + rc=$? + ((rc > 128)) || return 1 + expire + fi + done +} + +main() { + local fd + if [[ -n $EVENTS ]]; then + exec {fd}<"$EVENTS" + else + exec {fd}< <(exec /usr/bin/python3 "$HELPER") + fi + if ! watch_events "$fd"; then + log 'event stream ended' + exit 1 + fi +} + +main "$@" diff --git a/linux_configuration/i3/config b/linux_configuration/i3/config index b644cbfe..d4f0d1b3 100644 --- a/linux_configuration/i3/config +++ b/linux_configuration/i3/config @@ -107,6 +107,11 @@ bindsym $mod+Return exec terminator bindsym $mod+c exec --no-startup-id /home/kuhy/src/testsAndMisc/linux_configuration/zsh/calc-popup.sh for_window [window_role="calc"] floating enable, border pixel 3, resize set 820 px 220 px, move position center +# game recorder (gaming/game_rec.sh, linked by features/setup_game_rec.sh): +# toggles a gpu-screen-recorder capture of the Steam game's monitor; the +# i3blocks game_rec block shows a red dot while it runs. +bindsym $mod+Shift+g exec --no-startup-id $HOME/.local/bin/game-rec toggle + # kill focused window bindsym $mod+Shift+q kill diff --git a/linux_configuration/i3blocks/config b/linux_configuration/i3blocks/config index 2b28627b..de22077e 100644 --- a/linux_configuration/i3blocks/config +++ b/linux_configuration/i3blocks/config @@ -79,6 +79,14 @@ interval=60 markup=pango +# Red dot while game-rec records. signal=12: game-rec sends `pkill -RTMIN+12 +# -x i3blocks` on start/stop/recorder exit; no polling at all. +[game_rec] +command=~/.config/i3blocks/game_rec.sh +interval=once +signal=12 + + [time] command=~/.config/i3blocks/time.sh interval=persist diff --git a/linux_configuration/i3blocks/game_rec.sh b/linux_configuration/i3blocks/game_rec.sh new file mode 100755 index 00000000..fafafc7a --- /dev/null +++ b/linux_configuration/i3blocks/game_rec.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# ============================================================================ +# game-rec indicator for i3blocks: one red dot while a game-rec recording +# runs, nothing (block hidden) otherwise. No text: the dot is the whole cue +# (shape + red). i3bar has no tooltips, so there is none. +# +# Signal-driven, zero forks: the block is `interval=once` + `signal=12` in the +# i3blocks config; gaming/game_rec.sh sends `pkill -RTMIN+12 -x i3blocks` on +# start, stop and when the recorder exits. Only builtins run here: the +# pidfile is read with `read` and the pid checked against /proc//cmdline +# (gpu-screen-recorder writing the pidfile's output path), the same ownership +# rule game_rec.sh uses, so a stale pidfile or a reused pid shows nothing. +# ============================================================================ + +set -euo pipefail + +readonly PIDFILE="${XDG_RUNTIME_DIR:-/run/user/$UID}/game-rec.pid" +readonly DOT='●' +readonly RED='#FF5555' + +emit() { + # full_text, short_text, color: the three lines i3blocks reads. + printf '%s\n%s\n%s\n' "$1" "$1" "$2" +} + +recording() { + local pid='' out='' arg prev='' is_gsr=0 writes_out=0 + local -a argv=() + [[ -r $PIDFILE ]] || return 1 + { read -r pid && read -r out; } <"$PIDFILE" || true + [[ $pid =~ ^[0-9]+$ && -n $out ]] || return 1 + mapfile -d '' argv 2>/dev/null <"/proc/$pid/cmdline" || return 1 + for arg in "${argv[@]}"; do + [[ ${arg##*/} == gpu-screen-recorder ]] && is_gsr=1 + [[ $prev == -o && $arg == "$out" ]] && writes_out=1 + prev=$arg + done + ((is_gsr && writes_out)) +} + +if recording; then + emit "$DOT" "$RED" +else + emit '' '' +fi diff --git a/linux_configuration/tests/conftest.py b/linux_configuration/tests/conftest.py index f94d95e3..3c40d798 100644 --- a/linux_configuration/tests/conftest.py +++ b/linux_configuration/tests/conftest.py @@ -26,6 +26,7 @@ _SCRIPT_DIRS = ( _REPO_ROOT / "linux_configuration" / "utils", # fast_count _REPO_ROOT / "linux_configuration" / "features", # monitor_layout _REPO_ROOT / "linux_configuration" / "fixes", # g29_shifter_capture + _REPO_ROOT / "linux_configuration" / "gaming", # game_rec_scopes _REPO_ROOT / "linux_configuration" / "misc" diff --git a/linux_configuration/tests/game_rec_helpers.bash b/linux_configuration/tests/game_rec_helpers.bash new file mode 100644 index 00000000..171a3c34 --- /dev/null +++ b/linux_configuration/tests/game_rec_helpers.bash @@ -0,0 +1,181 @@ +# Shared bats fixtures for gaming/game_rec.sh and i3blocks/game_rec.sh. +# +# Every external program the recorder touches is a stub on PATH that records +# what it was asked: gpu-screen-recorder (argv, one element per line, and the +# signals it got), xdotool, xrandr, df and pkill. Game detection reads a fake +# /proc tree (GAME_REC_PROC_ROOT), so the tests never see kuhy's real reaper, +# game window or live recording. The stub outputs copy the real formats +# captured on 2026-11-22 (xrandr --listmonitors, xdotool --shell, reaper argv). + +REPO_DIR="$(cd "$BATS_TEST_DIRNAME/.." && pwd)" +SCRIPT="$REPO_DIR/gaming/game_rec.sh" +RAT_EXE='/home/kuhy/.local/share/Steam/steamapps/common/rat game/Rat Game.exe' + +setup_stubs() { + STUB_DIR="$BATS_TEST_TMPDIR/stub" + local bin="$BATS_TEST_TMPDIR/bin" + mkdir -p "$STUB_DIR" "$bin" "$BATS_TEST_TMPDIR/run" "$BATS_TEST_TMPDIR/proc" + export STUB_DIR + export XDG_RUNTIME_DIR="$BATS_TEST_TMPDIR/run" + export GAME_REC_DIR="$BATS_TEST_TMPDIR/videos" + export GAME_REC_PROC_ROOT="$BATS_TEST_TMPDIR/proc" + export GAME_REC_START_GRACE=0 GAME_REC_STOP_TIMEOUT=5 + # Absolute path: a watcher that outlives the test finds no pkill at all + # instead of falling back to the real one. + export GAME_REC_PKILL="$bin/pkill" + export PATH="$bin:$PATH" + unset GAME_REC_MONITOR GAME_REC_FPS GAME_REC_MIN_FREE_GB GAME_REC_EVENTS + unset GAME_REC_AUTO_GRACE GAME_REC_BIN + + cat >"$bin/gpu-screen-recorder" <<'EOF' +#!/bin/bash +set -euo pipefail +if [[ ${1:-} == --list-application-audio ]]; then + cat "$STUB_DIR/apps" + exit 0 +fi +printf '%s\n' "$@" >"$STUB_DIR/argv.$$" +printf '%s\n' "$$" >>"$STUB_DIR/gsr_pids" +# GSR_STUB_REJECT_APP=1: die at once on any app: source (an unknown app name). +if [[ -n ${GSR_STUB_REJECT_APP:-} && " $* " == *' app:'* ]]; then + exit 1 +fi +child=0 +on_signal() { + printf '%s\n' "$1" >>"$STUB_DIR/signals.$$" + kill "$child" 2>/dev/null || true + exit 0 +} +trap 'on_signal INT' INT +trap 'on_signal TERM' TERM +sleep 300 & +child=$! +wait "$child" +EOF + cat >"$bin/xdotool" <<'EOF' +#!/bin/bash +set -euo pipefail +printf '%s\n' "$*" >>"$STUB_DIR/xdotool_calls" +case $1 in +search) [[ -s $STUB_DIR/game_win ]] && cat "$STUB_DIR/game_win" || exit 1 ;; +getactivewindow) [[ -s $STUB_DIR/active_win ]] && cat "$STUB_DIR/active_win" || exit 1 ;; +getwindowgeometry) cat "$STUB_DIR/geom.$3" ;; +esac +EOF + cat >"$bin/xrandr" <<'EOF' +#!/bin/bash +printf 'Monitors: 2\n' +printf ' 0: +*DP-2 3840/620x2160/340+0+0 DP-2\n' +printf ' 1: +HDMI-0 2560/698x1440/393+3840+0 HDMI-0\n' +EOF + cat >"$bin/df" <<'EOF' +#!/bin/bash +printf '%s\n' "$*" >>"$STUB_DIR/df_calls" +printf ' Avail\n%s\n' "$(cat "$STUB_DIR/df_avail")" +EOF + cat >"$bin/pkill" <<'EOF' +#!/bin/bash +printf '%s\n' "$*" >>"$STUB_DIR/pkill_calls" +EOF + # systemd-run --user --scope ... -- CMD: record the options, run CMD in place. + cat >"$bin/systemd-run" <<'EOF' +#!/bin/bash +opts=() +while (($#)) && [[ $1 != -- ]]; do opts+=("$1") && shift; done +printf '%s\n' "${opts[*]}" >>"$STUB_DIR/systemd_run_calls" +shift +exec "$@" +EOF + chmod +x "$bin"/* + printf '%s\n' vesktop 'Rat Game.exe' >"$STUB_DIR/apps" + printf '%s\n' $((500 * 1024 * 1024 * 1024)) >"$STUB_DIR/df_avail" + : >"$STUB_DIR/gsr_pids" +} + +# Kill every stub recorder and decoy this test started (never anything else). +teardown_stubs() { + local pid + while read -r pid; do + kill -TERM "$pid" 2>/dev/null || true + done <"$STUB_DIR/gsr_pids" +} + +# make_reaper PID APPID EXE: a Steam reaper as /proc shows it (NUL-split argv). +make_reaper() { + local dir="$GAME_REC_PROC_ROOT/$1" + mkdir -p "$dir" + printf 'reaper\n' >"$dir/comm" + printf '%s\0' /home/kuhy/.local/share/Steam/steamrt64/reaper SteamLaunch \ + "AppId=$2" -- \ + /home/kuhy/.local/share/Steam/steamapps/common/SteamLinuxRuntime_4/_v2-entry-point \ + --verb=waitforexitandrun -- \ + '/home/kuhy/.local/share/Steam/steamapps/common/Proton - Experimental/proton' \ + waitforexitandrun "$3" >"$dir/cmdline" +} + +# The launch client also carries "reaper SteamLaunch" in its argv; it must +# never count as the game. +make_launch_client() { + local dir="$GAME_REC_PROC_ROOT/$1" + mkdir -p "$dir" + printf 'steam-runtime-l\n' >"$dir/comm" + printf '%s\0' steam-runtime-launch-client -- /bin/sh -c \ + "reaper SteamLaunch AppId=99 -- $RAT_EXE" >"$dir/cmdline" +} + +# set_geom ID X Y W H: what `xdotool getwindowgeometry --shell ID` prints. +set_geom() { + printf 'WINDOW=%s\nX=%s\nY=%s\nWIDTH=%s\nHEIGHT=%s\nSCREEN=0\n' "$@" \ + >"$STUB_DIR/geom.$1" +} +set_game_window() { + set_geom "$@" + printf '%s\n' "$1" >"$STUB_DIR/game_win" +} +set_active_window() { + set_geom "$@" + printf '%s\n' "$1" >"$STUB_DIR/active_win" +} + +# fd 3 closed: bats would otherwise wait for the detached recorder/watcher. +run_script() { + bash "$SCRIPT" "$@" 3>&- +} +rec() { + run run_script "$@" +} + +# Wait (max 5 s) until the Nth stub recorder has written its argv. +wait_for_recorder() { + local n=${1:-1} _ + for _ in {1..50}; do + (($(wc -l <"$STUB_DIR/gsr_pids") >= n)) && return 0 + sleep 0.1 + done + return 1 +} + +last_pid() { tail -n 1 "$STUB_DIR/gsr_pids"; } +last_argv() { cat "$STUB_DIR/argv.$(last_pid)"; } + +# expected_argv MONITOR FPS [APP]: the exact argv minus the trailing path. +expected_argv() { + printf '%s\n' -w "$1" -f "$2" -c mkv -k hevc -q high -ac opus -a default_input + [[ -z ${3:-} ]] || printf '%s\n' -a "app:$3" + printf '%s\n' -a default_output -o +} + +# assert_argv MONITOR FPS SLUG [APP] +assert_argv() { + local argv want n + wait_for_recorder + argv=$(last_argv) + want=$(expected_argv "$1" "$2" "${4:-}") + n=$(wc -l <<<"$want") + [[ $(head -n "$n" <<<"$argv") == "$want" ]] || { + printf 'argv:\n%s\nwant:\n%s\n' "$argv" "$want" >&2 + return 1 + } + [[ $(wc -l <<<"$argv") -eq $((n + 1)) ]] + [[ $(tail -n 1 <<<"$argv") =~ ^$GAME_REC_DIR/$3-[0-9]{8}-[0-9]{6}\.mkv$ ]] +} diff --git a/linux_configuration/tests/test_game_rec.bats b/linux_configuration/tests/test_game_rec.bats new file mode 100755 index 00000000..affaf6e9 --- /dev/null +++ b/linux_configuration/tests/test_game_rec.bats @@ -0,0 +1,114 @@ +#!/usr/bin/env bats +# game_rec.sh start: which monitor, which audio tracks, which file name. +# Every program it calls is a stub (game_rec_helpers.bash); nothing records. + +load game_rec_helpers + +setup() { + setup_stubs + make_launch_client 4044265 +} + +teardown() { + teardown_stubs +} + +@test "game on DP-2: exact argv, mic + game + desktop tracks in order" { + make_reaper 4044284 3347910 "$RAT_EXE" + set_game_window 109051905 0 0 3840 2160 + rec start + [ "$status" -eq 0 ] + assert_argv DP-2 60 rat-game 'Rat Game.exe' + grep -qxF 'search --onlyvisible --class ^steam_app_3347910$' "$STUB_DIR/xdotool_calls" +} + +@test "game window on HDMI-0 records HDMI-0" { + make_reaper 4044284 3347910 "$RAT_EXE" + set_game_window 77 3940 100 1280 720 + rec start + [ "$status" -eq 0 ] + assert_argv HDMI-0 60 rat-game 'Rat Game.exe' +} + +@test "no game window: the focused window's monitor is used" { + make_reaper 4044284 3347910 "$RAT_EXE" + set_active_window 88 3840 0 2560 1440 + rec start + [ "$status" -eq 0 ] + assert_argv HDMI-0 60 rat-game 'Rat Game.exe' +} + +@test "no window found at all: DP-2" { + make_reaper 4044284 3347910 "$RAT_EXE" + rec start + [ "$status" -eq 0 ] + assert_argv DP-2 60 rat-game 'Rat Game.exe' +} + +@test "no Steam game (launch client only): DP-2, no game track" { + set_active_window 88 3840 0 2560 1440 + rec start + [ "$status" -eq 0 ] + assert_argv DP-2 60 desktop +} + +@test "game not in --list-application-audio yet: hotkey start names every spelling" { + make_reaper 4044284 3347910 "$RAT_EXE" + set_game_window 109051905 0 0 3840 2160 + printf 'vesktop\n' >"$STUB_DIR/apps" + rec start + [ "$status" -eq 0 ] + assert_argv DP-2 60 rat-game 'Rat Game.exe|app:Rat Game' +} + +@test "hotkey start retries without the guessed game track if the recorder rejects it" { + make_reaper 4044284 3347910 "$RAT_EXE" + printf 'vesktop\n' >"$STUB_DIR/apps" + export GSR_STUB_REJECT_APP=1 GAME_REC_START_GRACE=0.5 + rec start + [ "$status" -eq 0 ] + wait_for_recorder 2 + assert_argv DP-2 60 rat-game + rec status + [[ $output != *' auto='* ]] +} + +@test "app-audio name matches case-insensitively, list spelling wins" { + make_reaper 4044284 3347910 "$RAT_EXE" + set_game_window 109051905 0 0 3840 2160 + printf 'vesktop\nrat game.EXE\n' >"$STUB_DIR/apps" + rec start + [ "$status" -eq 0 ] + assert_argv DP-2 60 rat-game 'rat game.EXE' +} + +@test "GAME_REC_MONITOR and GAME_REC_FPS override detection" { + make_reaper 4044284 3347910 "$RAT_EXE" + set_game_window 109051905 0 0 3840 2160 + GAME_REC_MONITOR=HDMI-0 GAME_REC_FPS=30 rec start + [ "$status" -eq 0 ] + assert_argv HDMI-0 30 rat-game 'Rat Game.exe' +} + +@test "output goes under GAME_REC_DIR, created on demand" { + rec start + [ "$status" -eq 0 ] + [ -d "$GAME_REC_DIR" ] + grep -qx -- "--output=avail -B1 -- $GAME_REC_DIR" "$STUB_DIR/df_calls" +} + +@test "app-audio ignores spaces, punctuation and .exe (Oh Deer lists as OhDeer)" { + make_reaper 4044284 2708450 '/home/kuhy/.local/share/Steam/steamapps/common/Oh Deer/OhDeer.exe' + printf 'vesktop\nOhDeer\n' >"$STUB_DIR/apps" + rec start + [ "$status" -eq 0 ] + assert_argv DP-2 60 ohdeer OhDeer +} + +@test "app-audio also matches the game's Steam directory name" { + make_reaper 4044284 99 '/home/kuhy/.local/share/Steam/steamapps/common/Some Game/Bin/Win64/SG-Win64-Shipping.exe' + printf 'vesktop\nsome_game\n' >"$STUB_DIR/apps" + rec start + [ "$status" -eq 0 ] + assert_argv DP-2 60 sg-win64-shipping some_game +} diff --git a/linux_configuration/tests/test_game_rec_auto.bats b/linux_configuration/tests/test_game_rec_auto.bats new file mode 100755 index 00000000..e823e34f --- /dev/null +++ b/linux_configuration/tests/test_game_rec_auto.bats @@ -0,0 +1,274 @@ +#!/usr/bin/env bats +# game_rec_watch.sh: start a recording when a Steam game scope appears, stop +# it 30 s (here GAME_REC_AUTO_GRACE) after the last scope of that AppID goes, +# never touch a manual recording, adopt the one running at startup. +# The D-Bus side is a FIFO fed with the lines game_rec_scopes.py prints +# (format checked against the live helper on 2026-11-22: `new app-steam- +# app2708450-1226153.scope`, then `sync`); the recorder, xdotool +# and systemd-run are the stubs from game_rec_helpers.bash. + +load game_rec_helpers + +WATCH="$REPO_DIR/gaming/game_rec_watch.sh" +BLOCK="$REPO_DIR/i3blocks/game_rec.sh" +RAT_SCOPE=app-steam-app3347910-325827.scope +RAT_SCOPE2=app-steam-app3347910-400100.scope + +setup() { + setup_stubs + PIDFILE="$XDG_RUNTIME_DIR/game-rec.pid" + WATCH_LOG="$BATS_TEST_TMPDIR/watch.log" + WATCH_PID='' + make_reaper 4044284 3347910 "$RAT_EXE" + set_game_window 109051905 0 0 3840 2160 +} + +teardown() { + stop_watcher + teardown_stubs +} + +# start_watcher GRACE: run the watcher on a fresh FIFO; fd 4 feeds it. +start_watcher() { + local fifo="$BATS_TEST_TMPDIR/events.$RANDOM" + mkfifo "$fifo" + GAME_REC_EVENTS="$fifo" GAME_REC_AUTO_GRACE="${1:-1}" \ + bash "$WATCH" >"$WATCH_LOG" 2>&1 3>&- & + WATCH_PID=$! + # Read-write open never blocks, even if the watcher died at once. + exec 4<>"$fifo" +} + +stop_watcher() { + exec 4>&- + [[ -z $WATCH_PID ]] || kill "$WATCH_PID" 2>/dev/null || true + [[ -z $WATCH_PID ]] || wait "$WATCH_PID" 2>/dev/null || true + WATCH_PID='' +} + +feed() { + printf '%s\n' "$@" >&4 +} + +# wait_log LINE [N]: wait (max 5 s) until LINE is in the watcher log N times. +wait_log() { + local n=${2:-1} _ + for _ in {1..50}; do + (($(grep -cxF -- "$1" "$WATCH_LOG" 2>/dev/null) >= n)) && return 0 + sleep 0.1 + done + printf 'no "%s" x%s in watcher log:\n' "$1" "$n" >&2 + cat "$WATCH_LOG" >&2 + return 1 +} + +recorders() { wc -l <"$STUB_DIR/gsr_pids"; } + +@test "a new Steam scope starts an auto recording in its own scope" { + start_watcher 1 + feed sync "new $RAT_SCOPE" + wait_log 'start 3347910' + assert_argv DP-2 60 rat-game 'Rat Game.exe' + grep -q -- '--user --scope' "$STUB_DIR/systemd_run_calls" + rec status + [ "$status" -eq 0 ] + [[ $output == *' auto=3347910' ]] + run bash "$BLOCK" + [ "$output" = $'●\n●\n#FF5555' ] + grep -qxF -- '-RTMIN+12 -x i3blocks' "$STUB_DIR/pkill_calls" +} + +@test "auto start adds the game track before the game opens audio" { + printf 'vesktop\n' >"$STUB_DIR/apps" + start_watcher 1 + feed sync "new $RAT_SCOPE" + wait_log 'start 3347910' + assert_argv DP-2 60 rat-game 'Rat Game.exe|app:Rat Game' +} + +@test "auto start ignores the focused window and names a reaperless game by AppID" { + rm "$STUB_DIR/game_win" + set_active_window 88 3840 0 2560 1440 + start_watcher 1 + feed sync 'new app-steam-app123-1.scope' + wait_log 'start 123' + assert_argv DP-2 60 steam-123 +} + +@test "stop after grace: SIGINT, pidfile and auto mark cleared, bar refreshed" { + start_watcher 2 + feed sync "new $RAT_SCOPE" + wait_log 'start 3347910' + wait_for_recorder + pid=$(last_pid) + feed "removed $RAT_SCOPE" + wait_log 'grace 3347910' + sleep 1 + kill -0 "$pid" + [ ! -e "$STUB_DIR/signals.$pid" ] + wait_log 'stop 3347910' + [ "$(cat "$STUB_DIR/signals.$pid")" = INT ] + [ ! -e "$PIDFILE" ] + [ ! -e "$XDG_RUNTIME_DIR/game-rec.auto" ] + [ "$(wc -l <"$STUB_DIR/pkill_calls")" -ge 2 ] +} + +@test "relaunch within grace keeps the same recording and file" { + start_watcher 2 + feed sync "new $RAT_SCOPE" + wait_log 'start 3347910' + wait_for_recorder + pid=$(last_pid) + out=$(sed -n 2p "$PIDFILE") + feed "removed $RAT_SCOPE" + wait_log 'grace 3347910' + feed "new $RAT_SCOPE2" + wait_log 'resume 3347910' + sleep 3 + kill -0 "$pid" + [ ! -e "$STUB_DIR/signals.$pid" ] + [ "$(recorders)" -eq 1 ] + [ "$(sed -n 2p "$PIDFILE")" = "$out" ] + run ! grep -qx 'stop 3347910' "$WATCH_LOG" +} + +@test "two scopes of one game: grace starts only when the last one goes" { + start_watcher 1 + feed sync "new $RAT_SCOPE" "new $RAT_SCOPE2" + wait_log 'start 3347910' + wait_for_recorder + pid=$(last_pid) + feed "removed $RAT_SCOPE" + sleep 2 + kill -0 "$pid" + run ! grep -qx 'grace 3347910' "$WATCH_LOG" + feed "removed $RAT_SCOPE2" + wait_log 'stop 3347910' + [ "$(cat "$STUB_DIR/signals.$pid")" = INT ] +} + +@test "a manual recording is never stopped or doubled" { + start_watcher 1 + feed sync + wait_log sync + rec start + [ "$status" -eq 0 ] + wait_for_recorder + pid=$(last_pid) + feed "new $RAT_SCOPE" + wait_log 'busy 3347910' + feed "removed $RAT_SCOPE" + wait_log 'gone 3347910' + sleep 2 + kill -0 "$pid" + [ ! -e "$STUB_DIR/signals.$pid" ] + [ "$(recorders)" -eq 1 ] + rec stop --auto 3347910 + [ "$status" -ne 0 ] + kill -0 "$pid" + [ ! -e "$STUB_DIR/signals.$pid" ] + rec status + [[ $output != *auto* ]] +} + +@test "adopts the recording running at startup, then stops it after the game" { + rec start + wait_for_recorder + pid=$(last_pid) + start_watcher 1 + feed "new $RAT_SCOPE" sync + wait_log 'adopt 3347910' + rec status + [[ $output == *' auto=3347910' ]] + [ "$(recorders)" -eq 1 ] + feed "removed $RAT_SCOPE" + wait_log 'stop 3347910' + [ "$(cat "$STUB_DIR/signals.$pid")" = INT ] + [ ! -e "$PIDFILE" ] +} + +@test "no adoption without a live game scope" { + rec start + wait_for_recorder + start_watcher 1 + feed sync + wait_log sync + rec status + [[ $output != *auto* ]] +} + +@test "auto off pauses starts across watcher restarts; auto on resumes" { + rec auto off + [ "$status" -eq 0 ] + rec auto + [ "$output" = off ] + start_watcher 1 + feed sync "new $RAT_SCOPE" + wait_log 'off 3347910' + stop_watcher + start_watcher 1 + feed sync "new $RAT_SCOPE" + wait_log 'off 3347910' 2 + [ "$(recorders)" -eq 0 ] + rec auto on + [ "$status" -eq 0 ] + rec auto + [ "$output" = on ] + feed "removed $RAT_SCOPE" "new $RAT_SCOPE2" + wait_log 'start 3347910' + wait_for_recorder +} + +@test "auto off still stops the auto recording that is already running" { + start_watcher 1 + feed sync "new $RAT_SCOPE" + wait_log 'start 3347910' + wait_for_recorder + pid=$(last_pid) + rec auto off + feed "removed $RAT_SCOPE" + wait_log 'stop 3347910' + [ "$(cat "$STUB_DIR/signals.$pid")" = INT ] +} + +@test "unrelated scopes are ignored" { + start_watcher 1 + feed sync 'new app-firefox-12.scope' 'new app-steam-appx-1.scope' \ + 'new run-u5.scope' 'removed app-firefox-12.scope' 'bogus line' + wait_log 'ignore app-steam-appx-1.scope' + wait_log 'ignore bogus line' + [ "$(recorders)" -eq 0 ] + [ ! -e "$STUB_DIR/systemd_run_calls" ] +} + +@test "the watcher exits non-zero when the event stream ends" { + start_watcher 1 + feed sync + wait_log sync + exec 4>&- + rc=0 + wait "$WATCH_PID" || rc=$? + WATCH_PID='' + [ "$rc" -ne 0 ] +} + +@test "auto start before audio names every spelling the game may use" { + make_reaper 4044285 2708450 '/home/kuhy/.local/share/Steam/steamapps/common/Oh Deer/OhDeer.exe' + printf 'vesktop\n' >"$STUB_DIR/apps" + start_watcher 1 + feed sync 'new app-steam-app2708450-1226153.scope' + wait_log 'start 2708450' + assert_argv DP-2 60 ohdeer 'OhDeer.exe|app:OhDeer|app:Oh Deer' +} + +@test "auto start retries without the game track if the recorder rejects it" { + printf 'vesktop\n' >"$STUB_DIR/apps" + export GSR_STUB_REJECT_APP=1 GAME_REC_START_GRACE=0.5 + start_watcher 1 + feed sync "new $RAT_SCOPE" + wait_log 'start 3347910' + wait_for_recorder 2 + assert_argv DP-2 60 rat-game + rec status + [[ $output == *' auto=3347910' ]] +} diff --git a/linux_configuration/tests/test_game_rec_dbus.py b/linux_configuration/tests/test_game_rec_dbus.py new file mode 100644 index 00000000..c0f3a3ac --- /dev/null +++ b/linux_configuration/tests/test_game_rec_dbus.py @@ -0,0 +1,81 @@ +"""Tests for linux_configuration/gaming/game_rec_dbus.py (jeepney plumbing). + +``FakeConn`` (tests/test_game_rec_fakes.py) stands in for jeepney's blocking +connection; no test opens a real bus. +""" + +from __future__ import annotations + +import game_rec_dbus as grd +from jeepney import DBusAddress, HeaderFields, new_method_return, new_signal + +from tests.test_game_rec_fakes import FOX_PATH, RAT, RAT_PATH, FakeConn + + +class TestJeepneyBus: + """``JeepneyBus`` maps the small bus interface onto jeepney calls.""" + + def test_call_targets_systemd_and_unwraps(self) -> None: + conn = FakeConn([]) + bus = grd.JeepneyBus(conn) + assert bus.call(grd.MANAGER_PATH, grd.MANAGER_IFACE, "Subscribe") == ("ok",) + fields = conn.sent[0].header.fields + assert fields[HeaderFields.destination] == grd.SYSTEMD + assert fields[HeaderFields.member] == "Subscribe" + + def test_matches_go_to_the_bus_daemon(self) -> None: + conn = FakeConn([]) + bus = grd.JeepneyBus(conn) + rule = grd.props_rule(RAT_PATH) + bus.add_match(rule) + bus.remove_match(rule) + members = [m.header.fields[HeaderFields.member] for m in conn.sent] + assert members == ["AddMatch", "RemoveMatch"] + assert conn.sent[0].body == (rule.serialise(),) + + def test_next_signal_skips_non_signals(self) -> None: + sig = new_signal( + DBusAddress(grd.MANAGER_PATH, interface=grd.MANAGER_IFACE), + "UnitNew", + "so", + (RAT, RAT_PATH), + ) + reply = new_method_return( + new_signal(DBusAddress("/x", interface="org.example.I"), "m") + ) + conn = FakeConn([reply, sig]) + bus = grd.JeepneyBus(conn) + assert bus.next_signal() == ( + grd.MANAGER_PATH, + grd.MANAGER_IFACE, + "UnitNew", + (RAT, RAT_PATH), + ) + + +class TestJeepneyDiscard: + """``JeepneyBus.discard_pending`` drops only that unit's queued changes.""" + + def test_drops_only_matching_properties_changed(self) -> None: + conn = FakeConn([]) + bus = grd.JeepneyBus(conn) + props = DBusAddress(RAT_PATH, interface=grd.PROPS_IFACE) + stale = new_signal( + props, "PropertiesChanged", "sa{sv}as", (grd.UNIT_IFACE, {}, []) + ) + other = new_signal( + DBusAddress(FOX_PATH, interface=grd.PROPS_IFACE), + "PropertiesChanged", + "sa{sv}as", + (grd.UNIT_IFACE, {}, []), + ) + new = new_signal( + DBusAddress(grd.MANAGER_PATH, interface=grd.MANAGER_IFACE), + "UnitNew", + "so", + (RAT, RAT_PATH), + ) + queue = conn.queues[0][1] + queue.extend([stale, other, new]) + bus.discard_pending(RAT_PATH) + assert list(queue) == [other, new] diff --git a/linux_configuration/tests/test_game_rec_fakes.py b/linux_configuration/tests/test_game_rec_fakes.py new file mode 100644 index 00000000..4acffc7e --- /dev/null +++ b/linux_configuration/tests/test_game_rec_fakes.py @@ -0,0 +1,162 @@ +"""Shared fakes for the game-rec D-Bus tests; this module holds no tests. + +Named ``test_*`` only because the name-tests-test hook allows nothing else +under ``tests/`` besides conftest. ``FakeBus`` replays systemd signals in the +shapes jeepney decodes them to, per the org.freedesktop.systemd1 D-Bus API; +``FakeConn`` is just enough of jeepney's blocking connection for +``JeepneyBus``. Neither opens a real bus. +""" + +from __future__ import annotations + +from collections import deque +from typing import TYPE_CHECKING, Any + +import game_rec_dbus as grd +from jeepney import DBusAddress, new_method_return, new_signal +from jeepney.wrappers import DBusErrorResponse, new_error + +if TYPE_CHECKING: + from jeepney import MatchRule, Message + +RAT = "app-steam-app3347910-325827.scope" +RAT_PATH = "/org/freedesktop/systemd1/unit/app_2dsteam_2dapp3347910_2d325827_2escope" +FOX = "app-firefox-12.scope" +FOX_PATH = "/org/freedesktop/systemd1/unit/app_2dfirefox_2d12_2escope" + + +class EndError(Exception): + """Raised by the fake bus when its scripted signals run out.""" + + +def list_row(name: str, path: str, active: str) -> tuple[Any, ...]: + return (name, "", "loaded", active, "running", "", path, 0, "", "/") + + +class FakeBus: + """Scripted bus: canned replies per method, signals as plain tuples.""" + + def __init__( + self, + listed: list[tuple[Any, ...]] | None = None, + states: dict[str, str | None] | None = None, + signals: list[tuple[str, str, str, tuple[Any, ...]]] | None = None, + before_get: list[tuple[str, str, str, tuple[Any, ...]]] | None = None, + reload: list[tuple[str, str, str, tuple[Any, ...]]] | None = None, + ) -> None: + self.listed = listed or [] + # Loaded units (name -> path), what GetUnit answers. Delivered signals + # update it and ``states``, so a Get after an event sees its result. + self.units = {row[0]: row[6] for row in self.listed} + # Delivered before ``signals`` but never applied: a daemon-reload + # replays unit signals while systemd's real state stays the same. + self.reload = deque(reload or []) + # Signals that reach the connection while a Get is in flight, so the + # Get reply is newer than them. + self.before_get = before_get or [] + self.pending: deque[tuple[str, str, str, tuple[Any, ...]]] = deque() + self.states = states or {} + self.signals = deque(signals or []) + self.calls: list[str] = [] + self.matches: list[str] = [] + + def call( + self, + path: str, + interface: str, + method: str, + signature: str | None = None, + body: tuple[Any, ...] = (), + ) -> tuple[Any, ...]: + del interface, signature + self.calls.append(method) + if method == "ListUnitsByPatterns": + assert body == ([], ["app-steam-app*"]) + return (self.listed,) + if method == "GetUnit": + if body[0] not in self.units: + raise DBusErrorResponse(error_msg()) + return (self.units[body[0]],) + if method == "Get": + state = self.states.get(path) + self.pending.extend(self.before_get) + if state is None: + raise DBusErrorResponse(error_msg()) + return (("s", state),) + return () + + def add_match(self, rule: MatchRule) -> None: + self.matches.append("+" + rule.serialise()) + + def remove_match(self, rule: MatchRule) -> None: + self.matches.append("-" + rule.serialise()) + + def discard_pending(self, path: str) -> None: + self.pending = deque( + sig + for sig in self.pending + if not (sig[0] == path and sig[2] == "PropertiesChanged") + ) + + def next_signal(self) -> tuple[str, str, str, tuple[Any, ...]]: + if self.pending: + return self.pending.popleft() + if self.reload: + return self.reload.popleft() + if not self.signals: + raise EndError + sig = self.signals.popleft() + self._apply(sig) + return sig + + def _apply(self, sig: tuple[str, str, str, tuple[Any, ...]]) -> None: + path, _iface, member, body = sig + if member == "UnitNew": + self.units[body[0]] = body[1] + elif member == "UnitRemoved": + self.units.pop(body[0], None) + elif member == "PropertiesChanged" and "ActiveState" in body[1]: + self.states[path] = body[1]["ActiveState"][1] + + +def error_msg() -> Message: + call = new_signal(DBusAddress("/x", interface="org.example.I"), "m") + call.header.serial = 1 + return new_error(call, "org.freedesktop.DBus.Error.UnknownObject") + + +def unit_new(name: str, path: str) -> tuple[str, str, str, tuple[Any, ...]]: + return (grd.MANAGER_PATH, grd.MANAGER_IFACE, "UnitNew", (name, path)) + + +def unit_removed(name: str, path: str) -> tuple[str, str, str, tuple[Any, ...]]: + return (grd.MANAGER_PATH, grd.MANAGER_IFACE, "UnitRemoved", (name, path)) + + +def state_change(path: str, state: str) -> tuple[str, str, str, tuple[Any, ...]]: + changed = {"ActiveState": ("s", state), "SubState": ("s", "running")} + return (path, grd.PROPS_IFACE, "PropertiesChanged", (grd.UNIT_IFACE, changed, [])) + + +class FakeConn: + """Just enough of jeepney's blocking DBusConnection for ``JeepneyBus``.""" + + def __init__(self, incoming: list[Message]) -> None: + self.incoming = deque(incoming) + self.sent: list[Message] = [] + self.queues: list[tuple[MatchRule, deque[Message]]] = [] + + def filter(self, rule: MatchRule, *, queue: deque[Message]) -> object: + self.queues.append((rule, queue)) + return object() + + def send_and_get_reply(self, msg: Message) -> Message: + self.sent.append(msg) + msg.header.serial = len(self.sent) + return new_method_return(msg, "s", ("ok",)) + + def recv_messages(self) -> None: + msg = self.incoming.popleft() + for rule, queue in self.queues: + if rule.matches(msg): + queue.append(msg) diff --git a/linux_configuration/tests/test_game_rec_scopes.py b/linux_configuration/tests/test_game_rec_scopes.py new file mode 100644 index 00000000..52638f43 --- /dev/null +++ b/linux_configuration/tests/test_game_rec_scopes.py @@ -0,0 +1,195 @@ +"""Tests for linux_configuration/gaming/game_rec_scopes.py (Steam scope events). + +A fake bus (tests/test_game_rec_fakes.py) replays systemd signals; no test +opens a real bus. On 2026-11-22 the live helper printed +`new app-steam-app2708450-1226153.scope` then `sync`, the line format +game_rec_watch.sh reads. +""" + +from __future__ import annotations + +import io +from typing import Any + +import game_rec_dbus as grd +import game_rec_scopes as grs +import pytest + +from tests.test_game_rec_fakes import ( + FOX, + FOX_PATH, + RAT, + RAT_PATH, + EndError, + FakeBus, + FakeConn, + list_row, + state_change, + unit_new, + unit_removed, +) + + +def _run(bus: FakeBus) -> list[str]: + out = io.StringIO() + with pytest.raises(EndError): + grs.run(bus, out) + return out.getvalue().splitlines() + + +class TestRun: + """``run`` turns systemd's unit signals into new/removed/sync lines.""" + + def test_subscribes_before_listing(self) -> None: + bus = FakeBus() + assert _run(bus) == ["sync"] + assert bus.calls[:2] == ["Subscribe", "ListUnitsByPatterns"] + first = bus.matches[0] + assert first.startswith("+") + assert "type='signal'" in first + assert "sender='org.freedesktop.systemd1'" in first + + def test_lists_running_scopes_before_sync(self) -> None: + bus = FakeBus(listed=[list_row(RAT, RAT_PATH, "active")]) + assert _run(bus) == [f"new {RAT}", "sync"] + assert any(RAT_PATH in m and "PropertiesChanged" in m for m in bus.matches) + + def test_new_scope_waits_for_active(self) -> None: + bus = FakeBus( + states={RAT_PATH: "inactive"}, + signals=[unit_new(RAT, RAT_PATH), state_change(RAT_PATH, "active")], + ) + assert _run(bus) == ["sync", f"new {RAT}"] + + def test_already_active_scope_is_new_at_once(self) -> None: + bus = FakeBus(states={RAT_PATH: "active"}, signals=[unit_new(RAT, RAT_PATH)]) + assert _run(bus) == ["sync", f"new {RAT}"] + + def test_inactive_then_unloaded_is_removed_once(self) -> None: + bus = FakeBus( + states={RAT_PATH: "active"}, + signals=[ + unit_new(RAT, RAT_PATH), + state_change(RAT_PATH, "active"), + state_change(RAT_PATH, "failed"), + unit_removed(RAT, RAT_PATH), + ], + ) + assert _run(bus) == ["sync", f"new {RAT}", f"removed {RAT}"] + assert bus.matches[-1].startswith("-") + assert RAT_PATH in bus.matches[-1] + + def test_unloaded_while_active_is_removed(self) -> None: + bus = FakeBus( + states={RAT_PATH: "active"}, + signals=[unit_new(RAT, RAT_PATH), unit_removed(RAT, RAT_PATH)], + ) + assert _run(bus) == ["sync", f"new {RAT}", f"removed {RAT}"] + + def test_status_query_stub_never_reports(self) -> None: + # `systemctl --user status ` loads a stub: UnitNew, Get fails. + bus = FakeBus(signals=[unit_new(RAT, RAT_PATH), unit_removed(RAT, RAT_PATH)]) + assert _run(bus) == ["sync"] + + def test_duplicate_unit_new_is_ignored(self) -> None: + bus = FakeBus( + states={RAT_PATH: "active"}, + signals=[unit_new(RAT, RAT_PATH), unit_new(RAT, RAT_PATH)], + ) + assert _run(bus) == ["sync", f"new {RAT}"] + assert bus.calls.count("Get") == 1 + + def test_stale_states_queued_before_get_are_dropped(self) -> None: + # vmbox 2026-11-22: Get said active, then the queued inactive and + # activating changes printed a false removed/new pair. + bus = FakeBus( + states={RAT_PATH: "active"}, + before_get=[ + state_change(RAT_PATH, "inactive"), + state_change(RAT_PATH, "activating"), + unit_new(FOX, FOX_PATH), + ], + signals=[unit_new(RAT, RAT_PATH)], + ) + assert _run(bus) == ["sync", f"new {RAT}"] + + def test_transitional_states_are_not_removal(self) -> None: + bus = FakeBus( + states={RAT_PATH: "active"}, + signals=[ + unit_new(RAT, RAT_PATH), + state_change(RAT_PATH, "deactivating"), + state_change(RAT_PATH, "inactive"), + ], + ) + assert _run(bus) == ["sync", f"new {RAT}", f"removed {RAT}"] + bus = FakeBus( + states={RAT_PATH: "active"}, + signals=[unit_new(RAT, RAT_PATH), state_change(RAT_PATH, "activating")], + ) + assert _run(bus) == ["sync", f"new {RAT}"] + + @pytest.mark.parametrize( + "replayed", + [ + pytest.param( + [unit_removed(RAT, RAT_PATH), unit_new(RAT, RAT_PATH)], + id="unit-removed", + ), + pytest.param( + [state_change(RAT_PATH, "inactive"), state_change(RAT_PATH, "active")], + id="state", + ), + ], + ) + def test_daemon_reload_of_live_scope_is_not_removed( + self, replayed: list[tuple[str, str, str, tuple[Any, ...]]] + ) -> None: + # Journal 2026-11-22: a user daemon-reload printed "gone 2708450", + # "grace", then "resume"; a reload past the 30 s grace stops the + # recording of a game that never exited. The real exit still counts. + bus = FakeBus( + listed=[list_row(RAT, RAT_PATH, "active")], + states={RAT_PATH: "active"}, + reload=replayed, + signals=[state_change(RAT_PATH, "inactive"), unit_removed(RAT, RAT_PATH)], + ) + assert _run(bus) == [f"new {RAT}", "sync", f"removed {RAT}"] + + def test_other_units_and_signals_are_ignored(self) -> None: + bus = FakeBus( + states={FOX_PATH: "active"}, + signals=[ + unit_new(FOX, FOX_PATH), + unit_new("app-steam-app1-2.service", "/u/s"), + state_change(FOX_PATH, "active"), + (grd.MANAGER_PATH, grd.MANAGER_IFACE, "JobNew", (1, "/j", FOX)), + ( + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + "NameAcquired", + (":1.5",), + ), + ( + RAT_PATH, + grd.PROPS_IFACE, + "PropertiesChanged", + ("other.iface", {}, []), + ), + unit_removed(FOX, FOX_PATH), + ], + ) + assert _run(bus) == ["sync"] + assert bus.calls.count("Get") == 0 + + +class TestMain: + """``main`` exits quietly when the watcher closes the pipe.""" + + def test_broken_pipe_is_a_clean_exit(self, monkeypatch: pytest.MonkeyPatch) -> None: + def boom(*_args: object) -> None: + raise BrokenPipeError + + monkeypatch.setattr(grs, "open_dbus_connection", lambda **_kw: FakeConn([])) + monkeypatch.setattr(grs, "run", boom) + assert grs.main() == 0 diff --git a/linux_configuration/tests/test_game_rec_setup.bats b/linux_configuration/tests/test_game_rec_setup.bats new file mode 100755 index 00000000..d38818ec --- /dev/null +++ b/linux_configuration/tests/test_game_rec_setup.bats @@ -0,0 +1,82 @@ +#!/usr/bin/env bats +# game_rec wiring: the i3 hotkey, the i3blocks block, and setup_game_rec.sh +# (run against a scratch HOME with stub pacman/sudo; it never reloads i3). +# The $mod / $HOME in single quotes are literal i3 config text, never expanded. +# shellcheck disable=SC2016 + +REPO_DIR="$(cd "$BATS_TEST_DIRNAME/.." && pwd)" +SETUP="$REPO_DIR/features/setup_game_rec.sh" +readonly HOTKEY='bindsym $mod+Shift+g exec --no-startup-id $HOME/.local/bin/game-rec toggle' + +setup() { + export HOME="$BATS_TEST_TMPDIR/home" + mkdir -p "$HOME/.config/i3" "$BATS_TEST_TMPDIR/bin" + printf 'set $mod Mod4\nbindsym $mod+d exec dmenu_run\n' >"$HOME/.config/i3/config" + cat >"$BATS_TEST_TMPDIR/bin/pacman" <<'EOF' +#!/bin/bash +[[ $1 == -Q && " ${MISSING_PKGS:-} " == *" $2 "* ]] && exit 1 +exit 0 +EOF + cat >"$BATS_TEST_TMPDIR/bin/sudo" <<'EOF' +#!/bin/bash +printf '%s\n' "$*" >>"$HOME/sudo_calls" +EOF + cat >"$BATS_TEST_TMPDIR/bin/i3-msg" <<'EOF' +#!/bin/bash +printf '%s\n' "$*" >>"$HOME/i3msg_calls" +EOF + # Never the real user manager: kuhy's watcher may be live. + cat >"$BATS_TEST_TMPDIR/bin/systemctl" <<'EOF' +#!/bin/bash +printf '%s\n' "$*" >>"$HOME/systemctl_calls" +EOF + chmod +x "$BATS_TEST_TMPDIR/bin"/* + export PATH="$BATS_TEST_TMPDIR/bin:$PATH" +} + +@test "repo i3 config binds \$mod+Shift+g to game-rec toggle, once" { + [ "$(grep -cF "$HOTKEY" "$REPO_DIR/i3/config")" -eq 1 ] + [ "$(grep -cE '^\s*bindsym \$mod\+Shift\+g ' "$REPO_DIR/i3/config")" -eq 1 ] +} + +@test "i3blocks config: game_rec block is signal-driven, no polling" { + block=$(sed -n '/^\[game_rec\]$/,/^$/p' "$REPO_DIR/i3blocks/config") + grep -qx 'command=~/.config/i3blocks/game_rec.sh' <<<"$block" + grep -qx 'interval=once' <<<"$block" + grep -qx 'signal=12' <<<"$block" + [ "$(grep -cx 'signal=12' "$REPO_DIR/i3blocks/config")" -eq 1 ] +} + +@test "setup links game-rec and the block, adds the hotkey once, no reload" { + run bash "$SETUP" + [ "$status" -eq 0 ] + run bash "$SETUP" + [ "$status" -eq 0 ] + [ "$(readlink "$HOME/.local/bin/game-rec")" = "$REPO_DIR/gaming/game_rec.sh" ] + [ "$(readlink "$HOME/.config/i3blocks/game_rec.sh")" = "$REPO_DIR/i3blocks/game_rec.sh" ] + [ "$(grep -cF "$HOTKEY" "$HOME/.config/i3/config")" -eq 1 ] + [ ! -e "$HOME/sudo_calls" ] + [ ! -e "$HOME/i3msg_calls" ] +} + +@test "setup installs only the missing packages" { + MISSING_PKGS='xdotool' run bash "$SETUP" + [ "$status" -eq 0 ] + [ "$(cat "$HOME/sudo_calls")" = 'pacman -S --needed --noconfirm xdotool' ] +} + +@test "setup installs and enables the auto watcher unit at login" { + run bash "$SETUP" + [ "$status" -eq 0 ] + unit="$HOME/.config/systemd/user/game-rec-auto.service" + grep -qx "ExecStart=/bin/bash $REPO_DIR/gaming/game_rec_watch.sh" "$unit" + grep -qx 'WantedBy=graphical-session.target' "$unit" + run ! grep -q '@GAME_REC_DIR@' "$unit" + [ "$(cat "$HOME/systemctl_calls")" = $'--user daemon-reload\n--user enable game-rec-auto.service\n--user restart game-rec-auto.service' ] +} + +@test "the setup package list includes jeepney for the D-Bus helper" { + MISSING_PKGS='python-jeepney' run bash "$SETUP" + [ "$status" -eq 0 ] + [ "$(cat "$HOME/sudo_calls")" = 'pacman -S --needed --noconfirm python-jeepney' ] +} diff --git a/linux_configuration/tests/test_game_rec_state.bats b/linux_configuration/tests/test_game_rec_state.bats new file mode 100755 index 00000000..70f3f9b9 --- /dev/null +++ b/linux_configuration/tests/test_game_rec_state.bats @@ -0,0 +1,172 @@ +#!/usr/bin/env bats +# game_rec.sh state: pidfile start/stop/stale, the free-space refusal, the +# bar refresh, and the rule that stop only ever signals its own recorder. + +load game_rec_helpers + +BLOCK="$REPO_DIR/i3blocks/game_rec.sh" + +setup() { + setup_stubs + PIDFILE="$XDG_RUNTIME_DIR/game-rec.pid" +} + +teardown() { + teardown_stubs +} + +# A stub recorder this script did NOT start (stands in for game-rec.service). +spawn_decoy() { + "$BATS_TEST_TMPDIR/bin/gpu-screen-recorder" -o "$BATS_TEST_TMPDIR/other.mkv" \ + /dev/null 2>&1 3>&- & + wait_for_recorder 1 + DECOY=$(last_pid) +} + +@test "start writes the recorder's pid and output; status reports it" { + rec start + [ "$status" -eq 0 ] + wait_for_recorder + [ "$(sed -n 1p "$PIDFILE")" = "$(last_pid)" ] + [ "$(sed -n 2p "$PIDFILE")" = "$(tail -n 1 <<<"$(last_argv)")" ] + rec status + [ "$status" -eq 0 ] + [[ $output == *"$(sed -n 2p "$PIDFILE")"* ]] +} + +@test "second start refuses while recording; one recorder only" { + rec start + wait_for_recorder + rec start + [ "$status" -ne 0 ] + [ "$(wc -l <"$STUB_DIR/gsr_pids")" -eq 1 ] +} + +@test "stop sends SIGINT to its own recorder and clears the pidfile" { + rec start + wait_for_recorder + pid=$(last_pid) + rec stop + [ "$status" -eq 0 ] + [ "$(cat "$STUB_DIR/signals.$pid")" = INT ] + run kill -0 "$pid" + [ "$status" -ne 0 ] + [ ! -e "$PIDFILE" ] + rec status + [ "$status" -ne 0 ] +} + +@test "a stale pidfile (dead pid) does not block start" { + sleep 0 & + dead=$! + wait "$dead" + printf '%s\n%s\n' "$dead" "$GAME_REC_DIR/old.mkv" >"$PIDFILE" + rec status + [ "$status" -ne 0 ] + rec start + [ "$status" -eq 0 ] + wait_for_recorder + [ "$(sed -n 1p "$PIDFILE")" = "$(last_pid)" ] +} + +@test "stop never signals a recorder that is not its own" { + spawn_decoy + printf '%s\n%s\n' "$DECOY" "$GAME_REC_DIR/mine.mkv" >"$PIDFILE" + rec stop + [ "$status" -ne 0 ] + kill -0 "$DECOY" + [ ! -e "$STUB_DIR/signals.$DECOY" ] + [ ! -e "$PIDFILE" ] + rec status + [ "$status" -ne 0 ] +} + +@test "start ignores a foreign recorder and stop leaves it running" { + spawn_decoy + rec start + [ "$status" -eq 0 ] + wait_for_recorder 2 + rec stop + [ "$status" -eq 0 ] + kill -0 "$DECOY" + [ ! -e "$STUB_DIR/signals.$DECOY" ] +} + +@test "stop with nothing recording signals nothing" { + spawn_decoy + rec stop + [ "$status" -ne 0 ] + kill -0 "$DECOY" + [ ! -e "$STUB_DIR/signals.$DECOY" ] +} + +@test "refuses to start with less than 20 GB free" { + printf '%s\n' $((20 * 1024 * 1024 * 1024 - 1)) >"$STUB_DIR/df_avail" + rec start + [ "$status" -ne 0 ] + [[ $output == *refusing* ]] + [ ! -s "$STUB_DIR/gsr_pids" ] + [ ! -e "$PIDFILE" ] +} + +@test "exactly 20 GB free is enough" { + printf '%s\n' $((20 * 1024 * 1024 * 1024)) >"$STUB_DIR/df_avail" + rec start + [ "$status" -eq 0 ] +} + +@test "toggle starts, then stops" { + rec toggle + [ "$status" -eq 0 ] + wait_for_recorder + pid=$(last_pid) + rec toggle + [ "$status" -eq 0 ] + [ "$(cat "$STUB_DIR/signals.$pid")" = INT ] + [ ! -e "$PIDFILE" ] +} + +@test "start and stop refresh the bar with RTMIN+12" { + rec start + wait_for_recorder + [ "$(cat "$STUB_DIR/pkill_calls")" = "-RTMIN+12 -x i3blocks" ] + rec stop + [ "$(wc -l <"$STUB_DIR/pkill_calls")" -ge 2 ] + [ "$(sort -u "$STUB_DIR/pkill_calls")" = "-RTMIN+12 -x i3blocks" ] +} + +@test "a recorder that dies on its own clears the pidfile" { + rec start + wait_for_recorder + kill -TERM "$(last_pid)" + for _ in {1..40}; do + [ -e "$PIDFILE" ] || break + sleep 0.1 + done + [ ! -e "$PIDFILE" ] +} + +@test "bar block: hidden idle, red dot while recording, hidden when stale" { + run bash "$BLOCK" + [ "$status" -eq 0 ] + [ -z "${output//$'\n'/}" ] + rec start + wait_for_recorder + run bash "$BLOCK" + [ "$output" = $'●\n●\n#FF5555' ] + kill -TERM "$(last_pid)" + printf '999999999\n%s\n' "$GAME_REC_DIR/x.mkv" >"$PIDFILE" + run bash "$BLOCK" + [ -z "${output//$'\n'/}" ] +} + +@test "through the ~/.local/bin/game-rec symlink it still finds its lib" { + mkdir -p "$BATS_TEST_TMPDIR/link" + ln -s "$SCRIPT" "$BATS_TEST_TMPDIR/link/game-rec" + run "$BATS_TEST_TMPDIR/link/game-rec" --help + [ "$status" -eq 0 ] + [ "$output" = 'Usage: game-rec start|stop|toggle|status|auto [on|off]' ] + run "$BATS_TEST_TMPDIR/link/game-rec" status + [ "$status" -eq 1 ] + [ "$output" = idle ] +}