Introduce a Python CLI for selecting, processing, and setting wallpapers, including encrypted image and naming-table workflows, monitor-aware image composition, search and exclusion filters, and migration and usage notes. Module guide: - main.py: validates command combinations and coordinates configuration, encryption commands, image processing, monitor detection, wallpaper composition, and GNOME wallpaper setting. - wallpaper_changer/__init__.py: marks the application package. - wallpaper_changer/argument_parser.py: defines CLI options and merges command-line arguments with arguments loaded from the config file. - wallpaper_changer/config.py: loads host-specific image, wallpaper, and private-key settings. - wallpaper_changer/encryption_manager.py: reads and writes legacy OpenSSL encrypted files and loads, stores, encrypts, or decrypts naming tables. - wallpaper_changer/image_repository.py: scans and converts images, manages encrypted images and naming-table entries, and handles image decoding and sequential filename correction. - wallpaper_changer/logging_utils.py: configures and retrieves the project's custom logger. - wallpaper_changer/monitor_manager.py: discovers monitor layouts from DRM data or host configuration files. - wallpaper_changer/naming_table.py: loads legacy plaintext naming-table entries. - wallpaper_changer/wallpaper_builder.py: filters and selects images, decrypts as needed, and composes a labeled multi-monitor wallpaper. - wallpaper_changer/wallpaper_setter.py: sets GNOME background settings using gsettings.
196 lines
7.0 KiB
Python
196 lines
7.0 KiB
Python
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
import re
|
|
import xml.etree.ElementTree as ET
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Monitor:
|
|
width: int
|
|
height: int
|
|
x: int = 0
|
|
|
|
@property
|
|
def aspect_ratio(self) -> float:
|
|
return self.height / self.width
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ScreenLayout:
|
|
monitors: tuple[Monitor, ...]
|
|
|
|
@property
|
|
def monitor_count(self) -> int:
|
|
return len(self.monitors)
|
|
|
|
@property
|
|
def screen_aspect_ratio(self) -> float:
|
|
return self.monitors[0].height / sum(monitor.width for monitor in self.monitors)
|
|
|
|
|
|
class MonitorManager:
|
|
def connected(self) -> list[Path]:
|
|
monitors = []
|
|
for path in Path("/sys/class/drm").glob("card*-*"):
|
|
if (path / "status").read_text().strip() == "connected":
|
|
monitors.append(path)
|
|
return monitors
|
|
|
|
def get_screensize(
|
|
self,
|
|
host: str,
|
|
image_dir: Path,
|
|
monitor_config: int = 0,
|
|
drm_root: Path = Path("/sys/class/drm"),
|
|
monitor_file: Path = Path.home() / ".config/monitors.xml",
|
|
lid_state: Path = Path("/proc/acpi/button/lid/LID0/state"),
|
|
) -> ScreenLayout:
|
|
if host == "serverhost":
|
|
return self._read_server_layout(image_dir, monitor_config)
|
|
if host not in {"quiethost", "vivohost"}:
|
|
raise ValueError(f"Unsupported monitor host: {host}")
|
|
|
|
connectors = self._connected_connectors(host, drm_root, lid_state)
|
|
if len(connectors) == 1:
|
|
width, height = self._read_virtual_size(connectors[0])
|
|
return ScreenLayout((Monitor(width, height),))
|
|
if not connectors:
|
|
raise RuntimeError(f"No enabled monitors found for host {host}")
|
|
|
|
active_connectors = {
|
|
connector.name.split("-", 1)[1]: connector for connector in connectors
|
|
}
|
|
active_sizes = {
|
|
name: self._read_virtual_size(connector)
|
|
for name, connector in active_connectors.items()
|
|
}
|
|
selected: ScreenLayout | None = None
|
|
for configuration in (
|
|
ET.parse(monitor_file).getroot().findall(".//configuration")
|
|
):
|
|
logical_monitors = configuration.findall("logicalmonitor")
|
|
if len(logical_monitors) != len(connectors):
|
|
continue
|
|
|
|
layout_monitors = []
|
|
configured_connectors = set()
|
|
configuration_matches = True
|
|
for logical_monitor in logical_monitors:
|
|
connector_names = {
|
|
connector.text
|
|
for connector in logical_monitor.findall(".//monitorspec/connector")
|
|
if connector.text
|
|
}
|
|
configured_connectors.update(connector_names)
|
|
mode = logical_monitor.find("mode")
|
|
width = self._xml_integer(mode, "width")
|
|
height = self._xml_integer(mode, "height")
|
|
x = self._xml_integer(logical_monitor, "x")
|
|
if not connector_names or any(
|
|
active_sizes.get(name) != (width, height)
|
|
for name in connector_names
|
|
):
|
|
configuration_matches = False
|
|
layout_monitors.append(Monitor(width, height, x))
|
|
|
|
if (
|
|
configuration_matches
|
|
and configured_connectors == active_connectors.keys()
|
|
):
|
|
selected = ScreenLayout(tuple(layout_monitors))
|
|
|
|
if selected is None:
|
|
raise RuntimeError(
|
|
f"No matching monitor configuration found in {monitor_file}"
|
|
)
|
|
return selected
|
|
|
|
@staticmethod
|
|
def _connected_connectors(
|
|
host: str,
|
|
drm_root: Path,
|
|
lid_state: Path,
|
|
) -> list[Path]:
|
|
cards = sorted(
|
|
path
|
|
for path in drm_root.glob("card[0-9]*")
|
|
if re.fullmatch(r"card\d+", path.name)
|
|
)
|
|
|
|
connectors = []
|
|
for card in cards:
|
|
for connector in sorted(drm_root.glob(f"{card.name}-*")):
|
|
if (connector / "status").read_text().strip() != "connected":
|
|
continue
|
|
if (connector / "enabled").read_text().strip() != "enabled":
|
|
continue
|
|
if host == "quiethost" and connector.name.split("-", 1)[-1].startswith(
|
|
"eDP"
|
|
):
|
|
try:
|
|
lid_open = "open" in lid_state.read_text()
|
|
except FileNotFoundError:
|
|
lid_open = False
|
|
if not lid_open:
|
|
continue
|
|
connectors.append(connector)
|
|
return connectors
|
|
|
|
@staticmethod
|
|
def _read_virtual_size(connector: Path) -> tuple[int, int]:
|
|
size_file = connector / "device/device/graphics/fb0/virtual_size"
|
|
size = size_file.read_text().strip().split(",")
|
|
if len(size) != 2:
|
|
raise ValueError(f"Invalid virtual monitor size in {size_file}")
|
|
width, height = (int(value) for value in size)
|
|
if width <= 0 or height <= 0:
|
|
raise ValueError(f"Invalid virtual monitor size in {size_file}")
|
|
return width, height
|
|
|
|
@staticmethod
|
|
def _xml_integer(element: ET.Element | None, child: str) -> int:
|
|
value = element.findtext(child) if element is not None else None
|
|
if value is None:
|
|
raise ValueError(f"Missing <{child}> in monitor configuration")
|
|
return int(value)
|
|
|
|
@staticmethod
|
|
def _read_server_layout(image_dir: Path, monitor_config: int) -> ScreenLayout:
|
|
filename = (
|
|
f"monitors{monitor_config}.cfg" if monitor_config > 0 else "monitors.cfg"
|
|
)
|
|
config_file = image_dir / ".LOG" / filename
|
|
lines = config_file.read_text().splitlines()
|
|
|
|
monitor_line = next(
|
|
(line for line in lines if line.strip().startswith("Mon")), None
|
|
)
|
|
if monitor_line is None:
|
|
raise ValueError(f"Missing monitor count in {config_file}")
|
|
monitor_count = int(monitor_line.split(":")[-1].strip())
|
|
|
|
def read_axis(axis: str) -> list[int]:
|
|
line = next((line for line in lines if line.strip().startswith(axis)), None)
|
|
if line is None:
|
|
raise ValueError(f"Missing {axis} dimensions in {config_file}")
|
|
values = [
|
|
value for value in re.split(r"[:,\s]+", line.strip()[1:]) if value
|
|
]
|
|
return [int(value) for value in values]
|
|
|
|
widths = read_axis("X")
|
|
heights = read_axis("Y")
|
|
if (
|
|
monitor_count <= 0
|
|
or len(widths) != monitor_count
|
|
or len(heights) != monitor_count
|
|
):
|
|
raise ValueError(f"Invalid monitor dimensions in {config_file}")
|
|
if any(width <= 0 for width in widths) or any(
|
|
height <= 0 for height in heights
|
|
):
|
|
raise ValueError(f"Invalid monitor dimensions in {config_file}")
|
|
return ScreenLayout(
|
|
tuple(Monitor(width, height) for width, height in zip(widths, heights))
|
|
)
|