faet(wallaper_changer): filp ratio to with/height, add lid_state check, create parser functions

parse_monitor_config parses monitors.xml file and returns config struct
grm_to_gnome function tranlates card names
remove hostnames from algorithm
lid_state is processed by _connected_drm_connectors
This commit is contained in:
Lucas Vivo committed 2026-11-15 19:55:40 +01:00
1 parent 843389a747
commit 9e88631533
1 file changed
+99 -103
@@ -1,3 +1,4 @@
from glob import glob
import re
import xml.etree.ElementTree as ET
from dataclasses import dataclass
@@ -12,12 +13,12 @@ logger = get_logger(__name__)
class Monitor:
width: int
height: int
x: int = 0
x_coord: int
connector_names: set[str]
@property
def aspect_ratio(self) -> float:
return self.height / self.width
return self.width / self.height
@dataclass(frozen=True)
class ScreenLayout:
@@ -29,8 +30,7 @@ class ScreenLayout:
@property
def screen_aspect_ratio(self) -> float:
return self.monitors[0].height / sum(monitor.width for monitor in self.monitors)
return sum(monitor.width for monitor in self.monitors) / self.monitors[0].height
class MonitorManager:
def connected(self) -> list[Path]:
@@ -42,68 +42,47 @@ class MonitorManager:
def get_screensize(
self,
host: str,
image_dir: Path,
monitor_config: int = 0,
headless_mode: bool,
monitor_file: Path ,
drm_root: Path = Path("/sys/class/drm"),
monitor_file: Path | None = None,
lid_state: Path = Path("/proc/acpi/button/lid/LID0/state"),
lid_state: str = "/proc/acpi/button/lid/LID*/state",
) -> ScreenLayout:
if monitor_file is None:
monitor_file = Path.home() / ".config/monitors.xml"
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
monitor_configurations = self._parse_monitor_configurations(monitor_file)
if headless_mode:
return monitor_configurations[0]
connectors_drm = self._connected_drm_connectors(drm_root, lid_state)
if len(connectors_drm) == 1:
width, height = self._read_virtual_size(connectors_drm[0])
return ScreenLayout((Monitor(width, height, 0, set(connectors_drm[0].name)),))
if not connectors_drm:
raise RuntimeError("No enabled monitors found")
active_gnome_connectors = {
drm_to_gnome(connector.name): connector for connector in connectors_drm
}
active_sizes = {
name: self._read_virtual_size(connector)
for name, connector in active_connectors.items()
for name, connector in active_gnome_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 = []
for configuration in monitor_configurations:
logical_monitors = configuration.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
):
configured_connectors.update(logical_monitor.connector_names)
if active_sizes and (not logical_monitor.connector_names or any(
active_sizes.get(name) != (logical_monitor.width, logical_monitor.height)
for name in logical_monitor.connector_names
)):
configuration_matches = False
layout_monitors.append(Monitor(width, height, x))
if (
if active_gnome_connectors and (
configuration_matches
and configured_connectors == active_connectors.keys()
and configured_connectors == active_gnome_connectors.keys()
):
selected = ScreenLayout(tuple(layout_monitors))
selected = ScreenLayout(tuple(logical_monitors))
if selected is None:
raise RuntimeError(
@@ -113,19 +92,53 @@ class MonitorManager:
f"Selected monitor configuration from {monitor_file}: {selected}"
)
return selected
def _parse_monitor_configurations(self,
monitor_file: Path,) -> list[ScreenLayout]:
monitor_configurations: list[ScreenLayout] = []
for configuration in (
ET.parse(monitor_file).getroot().findall(".//configuration")
):
logical_monitors = configuration.findall("logicalmonitor")
layout_monitors = []
for logical_monitor in logical_monitors:
connector_names = {
connector.text
for connector in logical_monitor.findall(".//monitorspec/connector")
if connector.text
}
mode = logical_monitor.find("./monitor/mode")
width = self._xml_integer(mode, "width")
height = self._xml_integer(mode, "height")
if width <= 0 or height <= 0:
raise ValueError(
f"Invalid monitor configuration in {monitor_file}: "
f"width or height is <= 0 for {logical_monitor}"
)
x_coord = self._xml_integer(logical_monitor, "x")
layout_monitors.append(Monitor(width, height, x_coord, connector_names))
monitor_configurations.append(ScreenLayout(tuple(layout_monitors)))
return monitor_configurations
@staticmethod
def _connected_connectors(
host: str,
def _connected_drm_connectors(
drm_root: Path,
lid_state: Path,
lid_state_regex: str,
) -> list[Path]:
cards = sorted(
path
for path in drm_root.glob("card[0-9]*")
if re.fullmatch(r"card\d+", path.name)
)
lid_state_paths = glob(lid_state_regex)
lid_closed = False
if len(lid_state_paths)>1:
raise RuntimeError("Multiple lid state files found")
elif len(lid_state_paths) == 1:
lid_closed = any(
"close" in Path(path).read_text().lower()
for path in lid_state_paths
)
connectors = []
for card in cards:
for connector in sorted(drm_root.glob(f"{card.name}-*")):
@@ -133,15 +146,8 @@ class MonitorManager:
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
if any(x in connector.name.lower() for x in ("edp", "lvds", "dsi")) and lid_closed:
continue
connectors.append(connector)
return connectors
@@ -159,46 +165,36 @@ class MonitorManager:
@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:
if not value:
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()
def drm_to_gnome(connector: str) -> str:
"""
Convert DRM sysfs connector to GNOME connector.
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())
Example:
card1-HDMI-A-1 -> HDMI-1
card1-DP-1 -> DP-1
"""
connector = connector.removeprefix("card")
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]
# Remove card number
connector = re.sub(r"^\d+-", "", connector)
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))
)
# Convert HDMI-A-N to HDMI-N
connector = re.sub(r"^HDMI-A-", "HDMI-", connector)
return connector
def gnome_to_drm(connector: str, card: int = 1) -> str:
"""
Convert GNOME connector to DRM sysfs connector.
Example:
HDMI-1 -> card1-HDMI-A-1
DP-1 -> card1-DP-1
"""
connector = re.sub(r"^HDMI-", "HDMI-A-", connector)
return f"card{card}-{connector}"