From 2f45bfb39e7c0b296082c033b728436c88b189fc Mon Sep 17 00:00:00 2001 From: Christopher Warner Date: Thu, 9 Apr 2026 08:22:58 -0400 Subject: Rename to aerial_screensaver for python import compatibility and add tests --- aerial-screensaver.py | 213 --------------------------------------------- aerial-screensaver.service | 2 +- aerial_screensaver.py | 213 +++++++++++++++++++++++++++++++++++++++++++++ test_screensaver.py | 37 ++++++++ 4 files changed, 251 insertions(+), 214 deletions(-) delete mode 100755 aerial-screensaver.py create mode 100755 aerial_screensaver.py create mode 100644 test_screensaver.py diff --git a/aerial-screensaver.py b/aerial-screensaver.py deleted file mode 100755 index 87d7581..0000000 --- a/aerial-screensaver.py +++ /dev/null @@ -1,213 +0,0 @@ -#!/usr/bin/env python3 -import time -import subprocess -import os -import random -import sys -import threading -import logging -from gi.repository import Gio, GLib - -# Setup Logging -LOG_PATH = os.path.expanduser("~/aerial_debug.log") -logging.basicConfig( - level=logging.DEBUG, - format='%(asctime)s %(levelname)s: %(message)s', - handlers=[ - logging.FileHandler(LOG_PATH), - logging.StreamHandler(sys.stdout) - ] -) - -# Configuration -IDLE_TIMEOUT_SECONDS = 300 # 5 minutes -VIDEO_DIR = os.path.expanduser("~/Videos/Screensavers/Aerial") -LID_STATE_FILE = "/proc/acpi/button/lid/LID0/state" - -# mpv "Lite" Command (Mimicking VLC efficiency) -MPV_COMMAND = [ - "nice", "-n", "19", - "mpv", - "--fullscreen", - "--no-stop-screensaver", - "--loop-playlist=inf", - "--shuffle", - "--input-ipc-server=/tmp/mpv_socket", - "--hwdec=vaapi", - "--vaapi-device=/dev/dri/by-path/pci-0000:c4:00.0-render", - "--vo=gpu", # Standard GPU renderer (lighter than gpu-next) - "--gpu-context=wayland", - "--video-sync=audio", # Lower overhead than display-resample - "--framedrop=vo", # Efficiently drop frames to match display - "--no-osc", - "--no-osd-bar", - "--osd-level=0", - "--cursor-autohide=always", - "--no-audio", - "--playlist=-" -] - -class AerialScreensaver: - def __init__(self): - self.process = None - self.idle_monitor = None - self.watch_id = None - - logging.info("Initializing Aerial Screensaver (mpv Lite Backend, AC-only, Lid-Aware)...") - - 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 - ) - - # Add watch for idle time - reply = self.idle_monitor.call_sync( - "AddIdleWatch", - GLib.Variant("(t)", (IDLE_TIMEOUT_SECONDS * 1000,)), - Gio.DBusCallFlags.NONE, - -1, - None - ) - self.watch_id = reply.unpack()[0] - logging.info(f"Added IdleWatch with ID: {self.watch_id} for {IDLE_TIMEOUT_SECONDS}s") - - # Listen for signals - self.idle_monitor.connect("g-signal", self.on_dbus_signal) - connected = True - - except Exception as e: - logging.error(f"Failed to connect to IdleMonitor: {e}") - logging.info("Retrying in 5 seconds...") - time.sleep(5) - self.idle_monitor = None - - def is_on_ac(self): - try: - for ac in os.listdir('/sys/class/power_supply/'): - if ac.startswith('AC'): - with open(f'/sys/class/power_supply/{ac}/online', 'r') as f: - if f.read().strip() == '1': - return True - return False - except Exception as e: - logging.error(f"Error checking AC status: {e}") - return False - - def is_lid_open(self): - try: - if not os.path.exists(LID_STATE_FILE): - return True - with open(LID_STATE_FILE, 'r') as f: - content = f.read().strip() - return "open" in content - except Exception as e: - logging.error(f"Error checking lid status: {e}") - return True - - def on_dbus_signal(self, proxy, sender_name, signal_name, parameters): - if signal_name == "WatchFired": - watch_id = parameters.unpack()[0] - if watch_id == self.watch_id: - if self.is_on_ac() and self.is_lid_open(): - logging.info("Idle threshold reached, on AC and lid is OPEN. Starting mpv.") - self.start_screensaver() - else: - logging.info(f"Idle threshold reached but skip (AC: {self.is_on_ac()}, Lid Open: {self.is_lid_open()})") - - def start_screensaver(self): - if self.process and self.process.poll() is None: - return - - try: - if not os.path.isdir(VIDEO_DIR): - logging.error(f"Video directory not found: {VIDEO_DIR}") - return - - videos = [ - os.path.join(VIDEO_DIR, f) - for f in os.listdir(VIDEO_DIR) - if f.lower().endswith(('.mov', '.mp4', '.mkv')) - ] - - if not videos: - logging.error("No video files found.") - return - - urls = "\n".join(videos) - - self.process = subprocess.Popen( - MPV_COMMAND, - stdin=subprocess.PIPE, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - text=True - ) - - if self.process.stdin: - self.process.stdin.write(urls) - self.process.stdin.close() - - logging.info(f"mpv started with PID: {self.process.pid}") - threading.Thread(target=self.monitor_activity, daemon=True).start() - - except Exception as e: - logging.error(f"Error starting mpv: {e}") - - def monitor_activity(self): - while self.process and self.process.poll() is None: - time.sleep(1) - try: - # Stop if lid is closed - if not self.is_lid_open(): - logging.info("Lid closed during playback. Stopping mpv.") - self.stop_screensaver() - break - - reply = self.idle_monitor.call_sync( - "GetIdletime", - None, - Gio.DBusCallFlags.NONE, - -1, - None - ) - idle_time = reply.unpack()[0] - - if idle_time < 1000: - self.stop_screensaver() - break - - if not self.is_on_ac(): - self.stop_screensaver() - break - - except Exception as e: - logging.error(f"Error in monitor_activity: {e}") - break - - def stop_screensaver(self): - if self.process: - self.process.terminate() - try: - self.process.wait(timeout=2) - except subprocess.TimeoutExpired: - self.process.kill() - self.process = None - - def run(self): - loop = GLib.MainLoop() - try: - loop.run() - except KeyboardInterrupt: - pass - -if __name__ == "__main__": - app = AerialScreensaver() - app.run() diff --git a/aerial-screensaver.service b/aerial-screensaver.service index fb9d603..9286643 100644 --- a/aerial-screensaver.service +++ b/aerial-screensaver.service @@ -4,7 +4,7 @@ PartOf=graphical-session.target After=graphical-session.target [Service] -ExecStart=/usr/bin/python3 /home/christopherwarner/.local/bin/aerial-screensaver +ExecStart=/usr/bin/python3 /home/christopherwarner/.local/bin/aerial_screensaver Restart=on-failure RestartSec=5s Nice=19 diff --git a/aerial_screensaver.py b/aerial_screensaver.py new file mode 100755 index 0000000..87d7581 --- /dev/null +++ b/aerial_screensaver.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +import time +import subprocess +import os +import random +import sys +import threading +import logging +from gi.repository import Gio, GLib + +# Setup Logging +LOG_PATH = os.path.expanduser("~/aerial_debug.log") +logging.basicConfig( + level=logging.DEBUG, + format='%(asctime)s %(levelname)s: %(message)s', + handlers=[ + logging.FileHandler(LOG_PATH), + logging.StreamHandler(sys.stdout) + ] +) + +# Configuration +IDLE_TIMEOUT_SECONDS = 300 # 5 minutes +VIDEO_DIR = os.path.expanduser("~/Videos/Screensavers/Aerial") +LID_STATE_FILE = "/proc/acpi/button/lid/LID0/state" + +# mpv "Lite" Command (Mimicking VLC efficiency) +MPV_COMMAND = [ + "nice", "-n", "19", + "mpv", + "--fullscreen", + "--no-stop-screensaver", + "--loop-playlist=inf", + "--shuffle", + "--input-ipc-server=/tmp/mpv_socket", + "--hwdec=vaapi", + "--vaapi-device=/dev/dri/by-path/pci-0000:c4:00.0-render", + "--vo=gpu", # Standard GPU renderer (lighter than gpu-next) + "--gpu-context=wayland", + "--video-sync=audio", # Lower overhead than display-resample + "--framedrop=vo", # Efficiently drop frames to match display + "--no-osc", + "--no-osd-bar", + "--osd-level=0", + "--cursor-autohide=always", + "--no-audio", + "--playlist=-" +] + +class AerialScreensaver: + def __init__(self): + self.process = None + self.idle_monitor = None + self.watch_id = None + + logging.info("Initializing Aerial Screensaver (mpv Lite Backend, AC-only, Lid-Aware)...") + + 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 + ) + + # Add watch for idle time + reply = self.idle_monitor.call_sync( + "AddIdleWatch", + GLib.Variant("(t)", (IDLE_TIMEOUT_SECONDS * 1000,)), + Gio.DBusCallFlags.NONE, + -1, + None + ) + self.watch_id = reply.unpack()[0] + logging.info(f"Added IdleWatch with ID: {self.watch_id} for {IDLE_TIMEOUT_SECONDS}s") + + # Listen for signals + self.idle_monitor.connect("g-signal", self.on_dbus_signal) + connected = True + + except Exception as e: + logging.error(f"Failed to connect to IdleMonitor: {e}") + logging.info("Retrying in 5 seconds...") + time.sleep(5) + self.idle_monitor = None + + def is_on_ac(self): + try: + for ac in os.listdir('/sys/class/power_supply/'): + if ac.startswith('AC'): + with open(f'/sys/class/power_supply/{ac}/online', 'r') as f: + if f.read().strip() == '1': + return True + return False + except Exception as e: + logging.error(f"Error checking AC status: {e}") + return False + + def is_lid_open(self): + try: + if not os.path.exists(LID_STATE_FILE): + return True + with open(LID_STATE_FILE, 'r') as f: + content = f.read().strip() + return "open" in content + except Exception as e: + logging.error(f"Error checking lid status: {e}") + return True + + def on_dbus_signal(self, proxy, sender_name, signal_name, parameters): + if signal_name == "WatchFired": + watch_id = parameters.unpack()[0] + if watch_id == self.watch_id: + if self.is_on_ac() and self.is_lid_open(): + logging.info("Idle threshold reached, on AC and lid is OPEN. Starting mpv.") + self.start_screensaver() + else: + logging.info(f"Idle threshold reached but skip (AC: {self.is_on_ac()}, Lid Open: {self.is_lid_open()})") + + def start_screensaver(self): + if self.process and self.process.poll() is None: + return + + try: + if not os.path.isdir(VIDEO_DIR): + logging.error(f"Video directory not found: {VIDEO_DIR}") + return + + videos = [ + os.path.join(VIDEO_DIR, f) + for f in os.listdir(VIDEO_DIR) + if f.lower().endswith(('.mov', '.mp4', '.mkv')) + ] + + if not videos: + logging.error("No video files found.") + return + + urls = "\n".join(videos) + + self.process = subprocess.Popen( + MPV_COMMAND, + stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + text=True + ) + + if self.process.stdin: + self.process.stdin.write(urls) + self.process.stdin.close() + + logging.info(f"mpv started with PID: {self.process.pid}") + threading.Thread(target=self.monitor_activity, daemon=True).start() + + except Exception as e: + logging.error(f"Error starting mpv: {e}") + + def monitor_activity(self): + while self.process and self.process.poll() is None: + time.sleep(1) + try: + # Stop if lid is closed + if not self.is_lid_open(): + logging.info("Lid closed during playback. Stopping mpv.") + self.stop_screensaver() + break + + reply = self.idle_monitor.call_sync( + "GetIdletime", + None, + Gio.DBusCallFlags.NONE, + -1, + None + ) + idle_time = reply.unpack()[0] + + if idle_time < 1000: + self.stop_screensaver() + break + + if not self.is_on_ac(): + self.stop_screensaver() + break + + except Exception as e: + logging.error(f"Error in monitor_activity: {e}") + break + + def stop_screensaver(self): + if self.process: + self.process.terminate() + try: + self.process.wait(timeout=2) + except subprocess.TimeoutExpired: + self.process.kill() + self.process = None + + def run(self): + loop = GLib.MainLoop() + try: + loop.run() + except KeyboardInterrupt: + pass + +if __name__ == "__main__": + app = AerialScreensaver() + app.run() diff --git a/test_screensaver.py b/test_screensaver.py new file mode 100644 index 0000000..da27714 --- /dev/null +++ b/test_screensaver.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +import unittest +from unittest.mock import patch, mock_open +import os +import sys + +# Append current directory to path +sys.path.append(os.path.dirname(os.path.abspath(__file__))) + +import aerial_screensaver + +class TestAerialScreensaver(unittest.TestCase): + @patch("os.path.exists") + def test_is_lid_open_file_missing(self, mock_exists): + mock_exists.return_value = False + app = aerial_screensaver.AerialScreensaver.__new__(aerial_screensaver.AerialScreensaver) + self.assertTrue(app.is_lid_open()) + + @patch("os.path.exists") + def test_is_lid_open_closed(self, mock_exists): + mock_exists.return_value = True + mock_content = "state: closed\n" + with patch("builtins.open", mock_open(read_data=mock_content)): + app = aerial_screensaver.AerialScreensaver.__new__(aerial_screensaver.AerialScreensaver) + self.assertFalse(app.is_lid_open()) + + @patch("os.path.exists") + def test_is_lid_open_open(self, mock_exists): + mock_exists.return_value = True + mock_content = "state: open\n" + with patch("builtins.open", mock_open(read_data=mock_content)): + app = aerial_screensaver.AerialScreensaver.__new__(aerial_screensaver.AerialScreensaver) + self.assertTrue(app.is_lid_open()) + +if __name__ == "__main__": + # We need to mock more things because AerialScreensaver.__init__ tries to connect to DBus + unittest.main() -- cgit v1.2.3