#!/usr/bin/env python3 """GNOME idle Aerial screensaver — AC-only, lid-aware, multi-monitor mpv.""" from __future__ import annotations import logging import os import re import subprocess import sys import threading import time from pathlib import Path from gi.repository import Gio, GLib CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "aerial-screensaver" CONFIG_FILE = CONFIG_DIR / "config" DEFAULT_VIDEO_DIR = Path.home() / "Videos" / "Screensavers" / "Aerial" DEFAULT_IDLE_SECONDS = 300 LID_STATE_CANDIDATES = ( "/proc/acpi/button/lid/LID0/state", "/proc/acpi/button/lid/LID/state", ) # Built-in panel connectors (clamshell = lid closed + non-builtin still active). BUILTIN_CONNECTOR_PREFIXES = ("eDP", "LVDS", "DSI") IPC_SOCKET_PREFIX = "/tmp/mpv_aerial_" LOG_PATH = Path.home() / "aerial_debug.log" def _load_config() -> dict[str, str]: cfg: dict[str, str] = {} if CONFIG_FILE.is_file(): for line in CONFIG_FILE.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) cfg[key.strip()] = value.strip().strip('"').strip("'") # Environment overrides config for key in ( "VIDEO_DIR", "IDLE_TIMEOUT_SECONDS", "VAAPI_DEVICE", "REQUIRE_AC", "ALLOW_CLAMSHELL", ): env = os.environ.get(f"AERIAL_{key}") if env: cfg[key] = env return cfg def _connector_is_builtin(connector: str) -> bool: return connector.startswith(BUILTIN_CONNECTOR_PREFIXES) def xrandr_geometry(connector: str) -> str | None: """Return mpv --geometry string (WxH+X+Y) for a connector via xrandr.""" try: out = subprocess.check_output( ["xrandr", "--listmonitors"], text=True, stderr=subprocess.DEVNULL, ) except (FileNotFoundError, subprocess.CalledProcessError): return None # Example: 0: +*DP-1 6144/700x3456/390+0+0 DP-1 pat = re.compile( r"(\d+)/\d+x(\d+)/\d+\+(\d+)\+(\d+)\s+" + re.escape(connector) + r"\s*$" ) for line in out.splitlines(): m = pat.search(line.strip()) if m: w, h, x, y = m.group(1), m.group(2), m.group(3), m.group(4) return f"{w}x{h}+{x}+{y}" return None def _pci_attrs_for_render(render: Path) -> tuple[str, str]: """Return (pci_class, vendor) hex strings for a render node.""" try: device = Path("/sys/class/drm") / render.name / "device" cls = (device / "class").read_text(encoding="utf-8").strip() if (device / "class").is_file() else "" vendor = (device / "vendor").read_text(encoding="utf-8").strip() if (device / "vendor").is_file() else "" return cls, vendor except OSError: return "", "" def find_vaapi_device(preferred: str | None = None) -> str | None: """Pick a DRM render node for VAAPI. Prefer iGPU (Intel / AMD display).""" if preferred and Path(preferred).exists(): return preferred renders: list[Path] = [] by_path = Path("/dev/dri/by-path") if by_path.is_dir(): for path in sorted(by_path.glob("*-render")): if "usb" in path.name.lower(): continue renders.append(path.resolve() if path.exists() else path) if not renders: renders = sorted(Path("/dev/dri").glob("renderD*")) if not renders: return None # Lower score wins: Intel (T480) / AMD display-class, then other, then dGPU/NVIDIA. scored: list[tuple[int, str]] = [] for node in renders: cls, vendor = _pci_attrs_for_render(node) if vendor == "0x8086": score = 0 elif cls.startswith("0x038"): score = 0 elif vendor == "0x10de": score = 3 elif cls.startswith("0x030"): score = 2 else: score = 1 scored.append((score, str(node))) scored.sort() return scored[0][1] def setup_logging() -> None: logging.basicConfig( level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s", handlers=[ logging.FileHandler(LOG_PATH), logging.StreamHandler(sys.stdout), ], ) class AerialScreensaver: def __init__(self) -> None: setup_logging() cfg = _load_config() self.video_dir = Path(cfg.get("VIDEO_DIR", str(DEFAULT_VIDEO_DIR))).expanduser() self.idle_timeout_seconds = int(cfg.get("IDLE_TIMEOUT_SECONDS", DEFAULT_IDLE_SECONDS)) self.require_ac = cfg.get("REQUIRE_AC", "1").lower() not in ("0", "false", "no") # Lid closed + external display (docked / clamshell) is allowed by default. self.allow_clamshell = cfg.get("ALLOW_CLAMSHELL", "1").lower() not in ( "0", "false", "no", ) self.vaapi_device = find_vaapi_device(cfg.get("VAAPI_DEVICE") or None) self.processes: list[subprocess.Popen] = [] self.idle_monitor = None self.watch_id = None self.lid_state_file = next( (p for p in LID_STATE_CANDIDATES if os.path.exists(p)), LID_STATE_CANDIDATES[0], ) logging.info( "Initializing Aerial Screensaver " "(mpv lite, AC=%s, clamshell=%s, multi-screen, vaapi=%s)...", self.require_ac, self.allow_clamshell, self.vaapi_device or "auto", ) self._connect_idle_monitor() def _connect_idle_monitor(self) -> None: connected = False while not connected: try: self.idle_monitor = Gio.DBusProxy.new_for_bus_sync( Gio.BusType.SESSION, Gio.DBusProxyFlags.NONE, None, "org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core", "org.gnome.Mutter.IdleMonitor", None, ) reply = self.idle_monitor.call_sync( "AddIdleWatch", GLib.Variant("(t)", (self.idle_timeout_seconds * 1000,)), Gio.DBusCallFlags.NONE, -1, None, ) self.watch_id = reply.unpack()[0] logging.info( "Added IdleWatch with ID: %s for %ss", self.watch_id, self.idle_timeout_seconds, ) self.idle_monitor.connect("g-signal", self.on_dbus_signal) connected = True except Exception as e: logging.error("Failed to connect to IdleMonitor: %s", e) logging.info("Retrying in 5 seconds...") time.sleep(5) self.idle_monitor = None def is_on_ac(self) -> bool: if not self.require_ac: return True try: for ac in os.listdir("/sys/class/power_supply/"): if ac.startswith("AC"): with open(f"/sys/class/power_supply/{ac}/online", "r", encoding="utf-8") as f: if f.read().strip() == "1": return True # Desktops often have no AC* supply — treat as on AC. supplies = os.listdir("/sys/class/power_supply/") if not any(s.startswith("AC") for s in supplies): return True return False except Exception as e: logging.error("Error checking AC status: %s", e) return False def is_lid_open(self) -> bool: try: if not os.path.exists(self.lid_state_file): return True with open(self.lid_state_file, "r", encoding="utf-8") as f: return "open" in f.read().strip() except Exception as e: logging.error("Error checking lid status: %s", e) return True def list_logical_screens(self) -> list[dict]: """Active GNOME logical monitors as mpv screen targets. Each item: {index, connector, primary, builtin}. Index matches Mutter logical-monitor order (what mpv --screen uses). """ try: proxy = Gio.DBusProxy.new_for_bus_sync( Gio.BusType.SESSION, Gio.DBusProxyFlags.NONE, None, "org.gnome.Mutter.DisplayConfig", "/org/gnome/Mutter/DisplayConfig", "org.gnome.Mutter.DisplayConfig", None, ) reply = proxy.call_sync( "GetCurrentState", None, Gio.DBusCallFlags.NONE, -1, None, ) _serial, monitors, logical_monitors, _props = reply.unpack() # connector -> (width, height) of current mode mode_size: dict[str, tuple[int, int]] = {} for mon in monitors: try: connector = mon[0][0] for mode in mon[1]: props = mode[6] if len(mode) > 6 else {} if isinstance(props, dict) and props.get("is-current"): mode_size[connector] = (int(mode[1]), int(mode[2])) break except (IndexError, TypeError, ValueError): continue screens: list[dict] = [] for index, lm in enumerate(logical_monitors): # (x, y, scale, transform, primary, monitors, properties) primary = bool(lm[4]) connectors = [mon[0] for mon in lm[5]] connector = connectors[0] if connectors else f"screen-{index}" builtin = any(_connector_is_builtin(c) for c in connectors) width, height = mode_size.get(connector, (1920, 1080)) # Prefer Mutter logical coords (Wayland). xrandr uses physical # pixels under fractional scaling and mis-places secondary outputs. geom = f"{width}x{height}+{int(lm[0])}+{int(lm[1])}" xrandr_geom = xrandr_geometry(connector) screens.append( { "index": index, "connector": connector, "primary": primary, "builtin": builtin, "geometry": geom, "xrandr_geometry": xrandr_geom, "product": lm[5][0][2] if lm[5] else "", } ) return screens except Exception as e: logging.error("Error detecting displays: %s", e) return [] def get_screen_count(self) -> int: """Return active GNOME logical monitor count (fallback: 1).""" screens = self.list_logical_screens() return max(1, len(screens)) if screens else 1 def has_external_display(self) -> bool: return any(not s["builtin"] for s in self.list_logical_screens()) def display_ok(self) -> bool: """Lid open, or clamshell (lid closed + external display) when allowed.""" if self.is_lid_open(): return True if self.allow_clamshell and self.has_external_display(): return True return False def screens_for_playback(self) -> list[dict]: """Which screens should show the screensaver. Lid open: every logical monitor. Lid closed (clamshell): only external (non-eDP) monitors, primary first. """ screens = self.list_logical_screens() if not screens: return [{"index": 0, "connector": "unknown", "primary": True, "builtin": False}] if self.is_lid_open(): return screens external = [s for s in screens if not s["builtin"]] if not external: # No external detected — fall back to primary rather than a blank lid panel. primary = [s for s in screens if s["primary"]] return primary or screens[:1] external.sort(key=lambda s: (not s["primary"], s["index"])) return external def on_dbus_signal(self, proxy, sender_name, signal_name, parameters) -> None: if signal_name != "WatchFired": return watch_id = parameters.unpack()[0] if watch_id != self.watch_id: return on_ac = self.is_on_ac() display_ok = self.display_ok() if on_ac and display_ok: lid = "open" if self.is_lid_open() else "closed (clamshell/external)" logging.info( "Idle threshold reached, on AC, display ok (lid %s). Starting mpv.", lid, ) self.start_screensaver() else: logging.info( "Idle threshold reached but skip (AC: %s, Lid Open: %s, External: %s)", on_ac, self.is_lid_open(), self.has_external_display(), ) def _collect_videos(self) -> list[str]: if not self.video_dir.is_dir(): return [] return sorted( str(self.video_dir / f) for f in os.listdir(self.video_dir) if f.lower().endswith((".mov", ".mp4", ".mkv")) and not f.startswith("_test") and not f.startswith(".") and ".partial." not in f.lower() ) def _session_env(self) -> dict[str, str]: env = os.environ.copy() runtime = env.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}") if not env.get("WAYLAND_DISPLAY"): for name in ("wayland-0", "wayland-1"): if Path(runtime, name).exists(): env["WAYLAND_DISPLAY"] = name break if not env.get("DISPLAY"): env["DISPLAY"] = ":0" return env def _mpv_base_command(self, gpu_context: str = "wayland") -> list[str]: cmd = [ "nice", "-n", "19", "mpv", "--force-window=immediate", "--fullscreen", "--no-stop-screensaver", "--loop-playlist=inf", "--shuffle", "--hwdec=vaapi", "--vo=gpu", f"--gpu-context={gpu_context}", "--gpu-api=opengl", "--scale=bilinear", "--cscale=bilinear", "--dscale=bilinear", "--dither=no", "--correct-downscaling=no", "--sigmoid-upscaling=no", "--video-sync=audio", "--framedrop=vo", "--vf=fps=24", "--no-osc", "--no-osd-bar", "--osd-level=0", "--cursor-autohide=always", "--no-audio", "--msg-level=vo=v,cplayer=status,wayland=v,x11=v", "--playlist=-", ] if self.vaapi_device: cmd.insert(cmd.index("--hwdec=vaapi") + 1, f"--vaapi-device={self.vaapi_device}") return cmd def _any_running(self) -> bool: return any(p.poll() is None for p in self.processes) def _mpv_log_path(self, connector: str) -> Path: safe = re.sub(r"[^\w.-]+", "_", connector) return Path.home() / f"aerial_mpv_{safe}.log" def _spawn_mpv( self, urls: str, target: dict, gpu_context: str, use_screen_name: bool, ) -> subprocess.Popen: connector = target["connector"] screen = int(target["index"]) # x11egl prefers xrandr physical pixels; wayland wants Mutter logical. if gpu_context == "x11egl" and target.get("xrandr_geometry"): geometry = target["xrandr_geometry"] else: geometry = target.get("geometry") or "1920x1080+0+0" ipc = f"{IPC_SOCKET_PREFIX}{screen}" mpv_log = self._mpv_log_path(connector) try: os.unlink(ipc) except FileNotFoundError: pass try: mpv_log.unlink() except FileNotFoundError: pass cmd = self._mpv_base_command(gpu_context) + [ f"--input-ipc-server={ipc}", f"--log-file={mpv_log}", f"--geometry={geometry}", ] # Never pass --screen/--fs-screen integers (Mutter order ≠ mpv wl_output). if use_screen_name: cmd += [ f"--screen-name={connector}", f"--fs-screen-name={connector}", ] proc = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True, env=self._session_env(), ) if proc.stdin: proc.stdin.write(urls) proc.stdin.close() logging.info( "mpv spawn connector=%s geometry=%s context=%s screen-name=%s PID=%s log=%s", connector, geometry, gpu_context, use_screen_name, proc.pid, mpv_log, ) return proc def _mpv_landed_on_target(self, connector: str, log_path: Path) -> bool: """True when mpv log shows the window on the requested connector.""" if not log_path.is_file() or log_path.stat().st_size == 0: return False text = log_path.read_text(encoding="utf-8", errors="replace") # Wayland: "Surface entered output … (DP-1)" if f"({connector})" in text and "Surface entered output" in text: # Prefer the last enter event (can move between outputs during setup) last_enter = "" for line in text.splitlines(): if "Surface entered output" in line and "(" in line: last_enter = line if last_enter and f"({connector})" in last_enter: return True if last_enter: return False # Explicit failure of --screen-name / --fs-screen-name if "Falling back to screen 0" in text: return _connector_is_builtin(connector) # X11/XWayland: listed our display and completed a vo reconfig if f"({connector})" in text and "reconfig to" in text: return True # Geometry-only spawn with no name: accept a living vo reconfig return "reconfig to" in text and "Falling back to screen 0" not in text def start_screensaver(self) -> None: if self._any_running(): return try: videos = self._collect_videos() if not videos: logging.error("No video files found in %s", self.video_dir) return targets = self.screens_for_playback() logging.info( "Using %s clips from %s on %s screen(s): %s", len(videos), self.video_dir, len(targets), ", ".join( f"{t['connector']}(geom={t.get('geometry')},primary={t['primary']})" for t in targets ), ) urls = "\n".join(videos) self.processes = [] for target in targets: connector = target["connector"] log_path = self._mpv_log_path(connector) # 1) Wayland + geometry + connector name proc = self._spawn_mpv(urls, target, "wayland", use_screen_name=True) self.processes.append(proc) time.sleep(1.2) if proc.poll() is not None: logging.error( "mpv exited early on %s (code %s). See %s", connector, proc.returncode, log_path, ) self.processes.remove(proc) continue if self._mpv_landed_on_target(connector, log_path): logging.info("mpv confirmed on %s (wayland)", connector) continue # 2) Retry with X11/XWayland + geometry only (reliable on GNOME) logging.warning( "wayland placement uncertain for %s; retrying via x11egl+geometry. Log: %s", connector, log_path, ) proc.terminate() try: proc.wait(timeout=2) except subprocess.TimeoutExpired: proc.kill() self.processes.remove(proc) proc = self._spawn_mpv(urls, target, "x11egl", use_screen_name=False) self.processes.append(proc) time.sleep(1.2) if proc.poll() is not None: logging.error( "mpv x11egl exited early on %s (code %s). See %s", connector, proc.returncode, log_path, ) self.processes.remove(proc) continue if self._mpv_landed_on_target(connector, log_path): logging.info("mpv confirmed on %s (x11egl)", connector) else: # Dump a short hint into the main debug log tail = "" if log_path.is_file(): lines = log_path.read_text(errors="replace").splitlines() tail = "\n".join(lines[-30:]) logging.error( "mpv still not confirmed on %s; last log lines:\n%s", connector, tail, ) if not self.processes: logging.error("No mpv instances running after start attempts") return threading.Thread(target=self.monitor_activity, daemon=True).start() except Exception as e: logging.error("Error starting mpv: %s", e) self.stop_screensaver() def monitor_activity(self) -> None: while self._any_running(): time.sleep(1) try: if not self.display_ok(): logging.info( "No usable display (lid closed without external). Stopping mpv." ) self.stop_screensaver() break reply = self.idle_monitor.call_sync( "GetIdletime", None, Gio.DBusCallFlags.NONE, -1, None, ) if reply.unpack()[0] < 1000: self.stop_screensaver() break if not self.is_on_ac(): self.stop_screensaver() break except Exception as e: logging.error("Error in monitor_activity: %s", e) break def stop_screensaver(self) -> None: for proc in self.processes: if proc.poll() is None: proc.terminate() try: proc.wait(timeout=2) except subprocess.TimeoutExpired: proc.kill() self.processes = [] for i in range(8): try: os.unlink(f"{IPC_SOCKET_PREFIX}{i}") except FileNotFoundError: pass def run(self) -> None: loop = GLib.MainLoop() try: loop.run() except KeyboardInterrupt: pass if __name__ == "__main__": AerialScreensaver().run()