"""Linux window capture (framegen/window_x11.py): picking a window, the ffmpeg command and pipe, and the source's behaviour (unchanged grabs left out, resize, minimise, close), all with a fake X server and a fake ffmpeg.""" import io import os import pathlib import sys import numpy as np import pytest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from framegen import window_x11 as wx from framegen.window_x11 import Rect, XWindow WINS = [XWindow(10, "Voidrunner -- top-down arena shooter", "voidrunner", 500, 1280, 720), XWindow(11, "Voidrunner launcher", "voidrunner", 499, 400, 300), XWindow(12, "~ : bash - Konsole", "konsole", 77, 1920, 1008)] def test_pick_by_title_takes_the_biggest_match(): assert wx.pick("voidrunner", WINS).xid == 10 assert wx.pick("KONSOLE", WINS).xid == 12 assert wx.pick("nothing like it", WINS) is None def test_pick_by_xid_class_and_alternatives(): assert wx.pick("xid:11", WINS).xid == 11 assert wx.pick("hwnd:0xc", WINS).xid == 12 assert wx.pick("class:konsole", WINS).xid == 12 assert wx.pick("xid:99|class:voidrunner", WINS).xid == 10 assert wx.pick("xid:notanumber", WINS) is None def test_pick_by_pid_includes_processes_it_started(): family = lambda pid: {pid, 500} if pid == 400 else {pid} # 400 is a launch script that started 500 assert wx.pick("pid:500", WINS, family).xid == 10 assert wx.pick("pid:400", WINS, family).xid == 10 assert wx.pick("pid:1", WINS, family) is None def test_pid_family_reads_proc(tmp_path): for pid, ppid, comm in ((100, 1, "sh"), (101, 100, "game (x86) :)"), (102, 101, "helper"), (200, 1, "other")): (tmp_path / str(pid)).mkdir() (tmp_path / str(pid) / "stat").write_text(f"{pid} ({comm}) S {ppid} 0 0 0") (tmp_path / "self").mkdir() assert wx.pid_family(100, str(tmp_path)) == {100, 101, 102} assert wx.pid_family(200, str(tmp_path)) == {200} assert wx.pid_family(5, "/nonexistent-proc") == {5} def test_wayland_reads_xwayland_windows_and_says_why_without_xwayland(): assert wx.session_problem({"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":0", "WAYLAND_DISPLAY": "wayland-0"}) is None assert "XWayland" in wx.session_problem({"XDG_SESSION_TYPE": "wayland", "WAYLAND_DISPLAY": "wayland-0"}) assert "DISPLAY" in wx.session_problem({}) assert wx.session_problem({"XDG_SESSION_TYPE": "x11", "DISPLAY": ":0"}) is None def test_grab_command_names_the_window_and_pipes_raw_bgr(): a = wx.grab_argv("ffmpeg", ":0", 0x2E00007, 60) assert a[a.index("-window_id") + 1] == str(0x2E00007) assert a[a.index("-f") + 1] == "x11grab" and a[a.index("-i") + 1] == ":0" assert a[a.index("-pix_fmt") + 1] == "bgr24" and a[-1] == "-" assert a.index("-window_id") < a.index("-i") # input options come before the input class FakeProc: def __init__(self, data: bytes, chunk: int = 7): self.stdout, self.stderr, self._chunk = io.BytesIO(data), io.BytesIO(b"note\nlast line\n"), chunk raw = self.stdout.readinto self.stdout.readinto = lambda view: raw(view[: self._chunk]) # short reads, as a pipe gives self.stdout.fileno = lambda: -1 self.killed = False def poll(self): return 0 def kill(self): self.killed = True def wait(self, timeout=None): return 0 def test_ffmpeg_grab_reads_whole_frames_from_short_reads(): frames = [np.full((4, 6, 3), v, np.uint8) for v in (1, 2)] proc = FakeProc(b"".join(f.tobytes() for f in frames) + b"xx") # (a cut-off third frame) g = wx.FfmpegGrab(":0", 1, 60, 6, 4, exe="ffmpeg", popen=lambda *a, **k: proc) assert np.array_equal(g.read(), frames[0]) and np.array_equal(g.read(), frames[1]) assert g.read() is None assert g.error() == "last line" g.close() assert proc.killed def test_ffmpeg_missing_says_so(monkeypatch): monkeypatch.setattr("shutil.which", lambda _: None) with pytest.raises(RuntimeError, match="ffmpeg"): wx.FfmpegGrab(":0", 1, 60, 6, 4) class FakeX: """geometry() answers from a script: a list of (Rect, shown) or None (gone); the last one repeats.""" name = ":9" def __init__(self, script): self.script, self.redirected = list(script), [] def geometry(self, xid): return self.script.pop(0) if len(self.script) > 1 else self.script[0] def redirect(self, xid): self.redirected.append(xid) return True def screen(self): return Rect(0, 0, 1920, 1080) class FakeGrab: def __init__(self, frames): self.frames, self.closed = list(frames), False def read(self): return self.frames.pop(0) if self.frames else None def error(self): return "ended" def close(self): self.closed = True def frame(v, w=320, h=240): return np.full((h, w, 3), v, np.uint8) def test_source_leaves_out_unchanged_grabs(monkeypatch): monkeypatch.setattr(wx, "CHECK_S", 0.0) monkeypatch.setattr(wx.time, "sleep", lambda s: None) here = (Rect(100, 50, 320, 240), True) x = FakeX([here, here, here, here, here, here, None]) # open, loop start, 4 checks, then the window closes grab = FakeGrab([frame(1), frame(1), frame(2), frame(2), frame(3)]) opened = [] src = wx.X11WindowSource(XWindow(7, "Game", "game", 1, 320, 240), x, open_fn=lambda *a: opened.append(a) or grab) assert (src.w, src.h) == (320, 240) and x.redirected == [7] assert src.info.kind == "window" and src.info.rate == "variable" ticks = list(src) assert [int(t.frame[0, 0, 0]) for t in ticks] == [1, 2, 3] assert [t.index for t in ticks] == [0, 1, 2] assert src.grabs == 5 and src.same == 2 assert opened[0] == (":9", 7, wx.GRAB_HZ, 320, 240) and grab.closed def test_source_restarts_and_scales_after_a_resize(monkeypatch): monkeypatch.setattr(wx, "CHECK_S", 0.0) monkeypatch.setattr(wx.time, "sleep", lambda s: None) small, big = (Rect(0, 0, 320, 240), True), (Rect(0, 0, 640, 480), True) x = FakeX([small, small, big, big, big, None]) grabs = [FakeGrab([frame(1)]), FakeGrab([frame(2, 640, 480)])] sizes = [] src = wx.X11WindowSource(XWindow(7, "Game", "game", 1, 320, 240), x, open_fn=lambda d, xid, hz, w, h: sizes.append((w, h)) or grabs.pop(0)) ticks = list(src) assert sizes == [(320, 240), (640, 480)] # ffmpeg is asked for the window's new size assert [t.frame.shape for t in ticks] == [(240, 320, 3), (240, 320, 3)] # frames keep the session's size assert src.restarts == 1 def test_source_odd_sizes_are_cropped_to_even(): x = FakeX([(Rect(0, 0, 321, 241), True)]) src = wx.X11WindowSource(XWindow(7, "Game", "game", 1, 321, 241), x, open_fn=lambda *a: None) assert (src.w, src.h) == (320, 240) out = src._fit(frame(5, 321, 241)) assert out.shape == (240, 320, 3) and out.flags["C_CONTIGUOUS"] where = src.where() assert where[0] == Rect(0, 0, 320, 240) and where[1] == Rect(0, 0, 1920, 1080) def test_minimised_window_has_no_place_and_tiny_ones_are_refused(): x = FakeX([(Rect(0, 0, 320, 240), True), (Rect(0, 0, 320, 240), False)]) src = wx.X11WindowSource(XWindow(7, "Game", "game", 1, 320, 240), x, open_fn=lambda *a: None) assert src._look() == "hidden" and src.where() is None with pytest.raises(RuntimeError, match="too small"): wx.X11WindowSource(XWindow(8, "Tip", "tip", 1, 40, 20), FakeX([(Rect(0, 0, 40, 20), True)])) with pytest.raises(RuntimeError, match="closed"): wx.X11WindowSource(XWindow(9, "Gone", "gone", 1, 320, 240), FakeX([None])) def test_clock60_puts_the_window_on_a_beat(): """The variable-rate window source through sources.Clock60: a beat with no new grab repeats the last frame.""" from framegen.io import Tick from framegen.sources import Clock60, source_info import threading hold = threading.Event() class Src: info = source_info("window") def __iter__(self): yield Tick(frame(1), 0.0, 0) hold.wait(5) # the game draws nothing more for a while ticks = [] for t in Clock60(Src(), sleep=lambda s: None): ticks.append(t) if len(ticks) == 3: break hold.set() assert ticks[0].new_hint is None # a fresh frame: the pipeline compares pictures assert [t.new_hint for t in ticks[1:]] == [False, False] # beats with nothing new are repeats for certain assert all(t.frame is ticks[0].frame for t in ticks) @pytest.mark.skipif(not os.environ.get("DISPLAY") or os.environ.get("XDG_SESSION_TYPE") == "wayland", reason="needs a real X11 display") def test_real_x_server_lists_windows(): x = wx.X() try: assert x.screen().w > 0 for w in wx.find_windows(x): assert w.title and w.w >= wx.MIN_SIZE[0] finally: x.close() def test_pick_by_dir_finds_a_game_a_launcher_started(): # Steam/Lutris/Heroic start the game; Summit only knows its folder. 500 runs from it, 77 (Konsole) does not. in_dir = lambda pid, folder: pid == 500 and folder == "/games/Voidrunner" assert wx.pick("dir:/games/Voidrunner", WINS, in_dir=in_dir).xid == 10 assert wx.pick("dir:/elsewhere", WINS, in_dir=in_dir) is None assert wx.pick("class:voidrunner.exe|dir:/games/Voidrunner", WINS, in_dir=in_dir).xid == 10 assert wx.pick("dir:", WINS, in_dir=lambda p, f: True) is None def test_under_reads_wine_paths_and_keeps_folder_boundaries(): assert wx.under("/games/Voidrunner/bin/vr", "/games/Voidrunner") assert wx.under("Z:\\games\\Voidrunner\\VR.exe", "/games/voidrunner/") assert wx.under("/games/Voidrunner", "/games/Voidrunner") assert not wx.under("/games/Voidrunner2/vr", "/games/Voidrunner") assert not wx.under("C:\\windows\\explorer.exe", "/games/Voidrunner") def test_pid_in_dir_reads_cwd_exe_and_cmdline(tmp_path): def proc(pid, cwd, exe, cmd): d = tmp_path / str(pid) d.mkdir() os.symlink(cwd, d / "cwd") os.symlink(exe, d / "exe") (d / "cmdline").write_bytes("\0".join(cmd).encode() + b"\0") proc(1, "/games/VR", "/usr/bin/vr", ["vr"]) # runs from the folder proc(2, "/home/me", "/games/VR/vr", ["vr"]) # its program is in it proc(3, "/home/me", "/proton/wine64", ["Z:\\games\\VR\\VR.exe"]) # Wine, the .exe on its command line proc(4, "/home/me", "/usr/bin/steam", ["steam", "steam://rungameid/1"]) # not the game got = [p for p in (1, 2, 3, 4, 5, 0) if wx.pid_in_dir(p, "/games/VR", proc=str(tmp_path))] assert got == [1, 2, 3] def test_ask_matches_nothing_until_a_rule_is_picked(): assert wx.pick("ask:", WINS) is None assert wx.pick("", WINS) is None assert "picked in Summit" in wx.waiting_line("ask:", 300) assert "matching 'class:x'" in wx.waiting_line("class:x", 60) def test_live_query_follows_the_file_summit_writes(tmp_path, capsys): f = tmp_path / "window-rule" live = wx.LiveQuery("ask:", env={"SUMMIT_WINDOW_FILE": str(f)}) assert live.get() == "ask:" # no file yet f.write_text("class:voidrunner\n") assert live.get() == "class:voidrunner" # picked in the launcher assert "now looking for 'class:voidrunner'" in capsys.readouterr().out f.write_text("") assert live.get() == "ask:" # emptied: back to what it was started with assert wx.LiveQuery("class:a", env={}).get() == "class:a" def test_open_window_takes_a_rule_picked_while_it_waits(tmp_path, monkeypatch): f = tmp_path / "window-rule" monkeypatch.setenv("SUMMIT_WINDOW_FILE", str(f)) monkeypatch.setattr(wx, "session_problem", lambda env=None: None) monkeypatch.setattr(wx, "X", lambda *a: object()) monkeypatch.setattr(wx, "find_windows", lambda x=None: WINS) monkeypatch.setattr(wx, "X11WindowSource", lambda target, x: target) looks = [] def sleep(_s): looks.append(1) if len(looks) == 3: f.write_text("class:konsole") # the player picks it in Summit assert wx.open_window("ask:", wait_s=30, sleep=sleep).xid == 12