Debian Codegraph @

DisplayCAL/real_display_size_mm.py

raw
1 """Utilities for retrieving and managing display information.
2
3 It supports various platforms and integrates with ArgyllCMS's `dispwin` tool to
4 enumerate displays and extract detailed display data.
5 """
6
7 from __future__ import annotations
8
9 import os
10 import re
11 import subprocess
12 import sys
13
14 from DisplayCAL import argyll
15 from DisplayCAL import localization as lang
16 from DisplayCAL.util_dbus import BUSTYPE_SESSION, DBusException, DBusObject
17 from DisplayCAL.util_x import get_display as _get_x_display
18
19 _displays = None
20
21
22 def get_xrandr_output_xid(display_no: int = 0) -> int:
23 """Return the XRandR output X11 ID of a given display.
24
25 Args:
26 display_no (int): Display number.
27
28 Returns:
29 int: The XRandR output X11 ID or 0 if not found.
30 """
31 display = get_display(display_no)
32 if display:
33 return display.get("output", 0)
34 return 0
35
36
37 def real_display_size_mm(display_no: int = 0) -> tuple[int, int]:
38 """Return the size (in mm) of a given display.
39
40 Args:
41 display_no (int): Display number.
42
43 Returns:
44 (int, int): The display size in mm.
45 """
46 if display := get_display(display_no):
47 return display.get("size_mm", (0, 0))
48 return 0, 0
49
50
51 class Display:
52 """Store information about display."""
53
54 def __init__(self) -> None:
55 self.name = None
56 """Display name."""
57 self.description = None # USED
58 """Description of display or URL."""
59
60 self.xrandr_name = None # Generated from self.description
61
62 self.pos = (0, 0) # USED
63 """Display offset in pixel."""
64 # self.sx = None
65 # """Display offset in pixels (X)."""
66 # self.sy = None
67 # """Display offset in pixels (Y)."""
68
69 self.size = (0, 0) # USED
70 """Display width and height in pixels."""
71
72 # WINDOWS / NT
73 self.monitor_id = None
74 """Monitor ID."""
75 self.prim = None
76 """ NZ if primary display monitor."""
77
78 # APPLE
79 self.display_device_id = None
80
81 # UNIX
82 self.screen = None
83 """X11 (possibly virtual) Screen."""
84 self.uscreen = None
85 """Underlying Xinerama/XRandr screen."""
86 self.rscreen = None
87 """Underlying RAMDAC screen (user override)."""
88 self.icc_atom = None
89 """ICC profile root/output atom for this display."""
90 self.edid = None
91 """128, 256 or 384 bytes of monitor EDID, NULL if none."""
92 self.edid_len = None
93 """128, 256 or 384."""
94
95 # Xrandr stuff - output is connected 1:1 to a display
96 self.crtc = None
97 """Associated crtc."""
98 self.output = None
99 """Associated output."""
100 self.icc_out_atom = None
101 """ICC profile atom for this output."""
102
103 def from_dispwin_data(self, display_info_line: str) -> None:
104 """Parse from dispwin display list data.
105
106 Args:
107 display_info_line (str): The dispwin data line.
108 """
109 display_info_line = display_info_line.strip()
110 description_data = re.findall(
111 rb"[\s\d]+= '(?P<description>.*)'", display_info_line
112 )
113 dispwin_error_message = lang.getstr(
114 "error.generic",
115 (-1, "dispwin returns no usable data while enumerating displays."),
116 )
117 if not description_data:
118 raise ValueError(dispwin_error_message)
119 self.description = description_data[0]
120 match = re.match(
121 rb"[\s]*(?P<id>\d) = '(?P<name>.*) at (?P<x>[-\d]+), (?P<y>[-\d]+), "
122 rb"width (?P<width>\d+), height (?P<height>\d+).*'",
123 display_info_line,
124 )
125 if not match:
126 raise ValueError(dispwin_error_message)
127 groups_dict = match.groupdict()
128 self.monitor_id = int(groups_dict["id"])
129 self.name = groups_dict["name"]
130 # fix the name ending with "," for ArgyllCMS<3.3.0
131 if self.name.endswith(b","):
132 self.name = self.name[:-1]
133 x = int(groups_dict["x"])
134 y = int(groups_dict["y"])
135 self.pos = (x, y)
136 width = int(groups_dict["width"])
137 height = int(groups_dict["height"])
138 self.size = (width, height)
139
140 def to_dict(self) -> dict:
141 """Return a dictionary.
142
143 Returns:
144 dict: The display data as dictionary, matching the previous
145 implementation.
146 """
147 display_dict = {}
148 if self.monitor_id is not None:
149 display_dict["monid"] = self.monitor_id
150 if self.description is not None:
151 display_dict["description"] = self.description
152 if self.name is not None:
153 display_dict["name"] = self.name
154 if self.pos is not None:
155 display_dict["pos"] = self.pos
156 if self.size is not None:
157 display_dict["size"] = self.size
158
159 return display_dict
160
161
162 def get_dispwin_output() -> bytes:
163 """Return Argyll dispwin output.
164
165 Returns:
166 bytes: The dispwin output.
167 """
168 dispwin_path = argyll.get_argyll_util("dispwin")
169 if dispwin_path is None:
170 return b""
171
172 if sys.platform == "win32":
173 startupinfo = subprocess.STARTUPINFO()
174 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
175 startupinfo.wShowWindow = subprocess.SW_HIDE
176 else:
177 startupinfo = None
178
179 # the invalid value of "-d0" is intentional,
180 # we just want to get the information we want and close the dispwin,
181 # if we don't supply "-d0" it will start showing color patches.
182 p = subprocess.Popen(
183 [dispwin_path, "-v", "-d0"],
184 stdin=subprocess.PIPE,
185 stdout=subprocess.PIPE,
186 stderr=subprocess.STDOUT,
187 startupinfo=startupinfo,
188 )
189 output, _ = p.communicate()
190 return output
191
192
193 def _enumerate_displays() -> list[dict]:
194 """Generate display information data from ArgyllCMS's dispwin.
195
196 Returns:
197 list[dict]: A list of dictionary containing display data.
198 """
199 displays = []
200 has_display = False
201 dispwin_output = get_dispwin_output()
202 for line in dispwin_output.split(b"\n"):
203 if has_display and b"-dweb[:port]" in line:
204 break
205 if has_display and b"=" in line:
206 display = Display()
207 display.from_dispwin_data(line)
208 displays.append(display.to_dict())
209 if not has_display and b"-d n" in line:
210 has_display = True
211
212 return displays
213
214
215 def enumerate_displays() -> list[dict]:
216 """Enumerate and return a list of displays.
217
218 Returns:
219 list[dict]: A list of dictionary containing display data.
220 """
221 global _displays
222 _displays = _enumerate_displays()
223
224 if _displays is None:
225 _displays = []
226
227 for display in _displays:
228 desc = display.get("description")
229 if not desc:
230 continue
231 match = re.findall(
232 rb"(.+?),? at (-?\d+), (-?\d+), width (\d+), height (\d+)", desc
233 )
234 if not len(match):
235 continue
236
237 # update xrandr_name from description
238 if sys.platform not in ("darwin", "win32"):
239 if (
240 os.getenv("XDG_SESSION_TYPE") == "wayland"
241 and "pos" in display
242 and "size" in display
243 ):
244 x, y, w, h = display["pos"] + display["size"]
245 wayland_display = get_wayland_display(x, y, w, h)
246 if wayland_display:
247 display.update(wayland_display)
248 else:
249 xrandr_name = re.search(rb", Output (.+)", match[0][0])
250 if xrandr_name:
251 display["xrandr_name"] = xrandr_name.group(1)
252 desc = b"%s @ %s, %s, %sx%s" % match[0]
253 display["description"] = desc
254 return _displays
255
256
257 def get_display(display_no: int = 0) -> None | dict:
258 """Return display data for a given display number.
259
260 Args:
261 display_no (int): Display number.
262
263 Returns:
264 None | dict: The display data.
265 """
266 if _displays is None:
267 enumerate_displays()
268
269 # Ensure _displays is not None after calling enumerate_displays
270 if _displays is None:
271 return None
272
273 # Translate from Argyll display index to enumerated display index using the
274 # coordinates and dimensions
275 from DisplayCAL.config import getcfg, is_virtual_display
276
277 if is_virtual_display(display_no):
278 return None
279
280 getcfg_displays = getcfg("displays")
281 if len(getcfg_displays) < display_no:
282 return None
283
284 argyll_display = getcfg_displays[display_no]
285
286 if argyll_display.endswith(" [PRIMARY]"):
287 argyll_display = " ".join(argyll_display.split(" ")[:-1])
288
289 for display in _displays:
290 desc = display.get("description")
291 if not desc:
292 continue
293 geometry = b"".join(desc.split(b"@ ")[-1:])
294 if argyll_display.endswith((b"@ " + geometry).decode("utf-8")):
295 return display
296 return None
297
298
299 def get_wayland_display(x: int, y: int, w: int, h: int) -> None | dict:
300 """Find matching Wayland display.
301
302 Given x, y, width and height of display geometry, find matching Wayland display.
303
304 Args:
305 x (int): X position.
306 y (int): Y position.
307 w (int): Width.
308 h (int): Height.
309
310 Returns:
311 None | dict: The Wayland display data.
312 """
313 # Note that we apparently CANNOT use width and height because the reported
314 # values from Argyll code and Mutter can be slightly different,
315 # e.g. 3660x1941 from Mutter vs 3656x1941 from Argyll when HiDPI is enabled.
316 # The xrandr output is also interesting in that case:
317 # $ xrandr
318 # Screen 0: minimum 320 x 200, current 3660 x 1941, maximum 8192 x 8192
319 # XWAYLAND0 connected 3656x1941+0+0 (normal left inverted right x axis y axis) 0mm x 0mm,B950 # noqa: E501
320 # 3656x1941 59.96*+
321 # Note the apparent mismatch between first and 2nd/3rd line.
322 # Look for active display at x, y instead.
323 # Currently, only support for GNOME 3 / Mutter
324 try:
325 iface = DBusObject(
326 BUSTYPE_SESSION,
327 "org.gnome.Mutter.DisplayConfig",
328 "/org/gnome/Mutter/DisplayConfig",
329 )
330 res = iface.get_resources()
331 except DBusException:
332 return None
333
334 if not res or len(res) < 2:
335 return None
336
337 # See
338 # https://github.com/GNOME/mutter/blob/master/src/org.gnome.Mutter.DisplayConfig.xml
339 output_storage = None
340 found = False
341 crtcs = res[1]
342 # Look for matching CRTC
343 for crtc in crtcs:
344 if len(crtc) < 7 or crtc[2:4] != (x, y) or crtc[6] == -1:
345 continue
346
347 # Found our CRTC
348 crtc_id = crtc[0]
349 # Look for matching output
350 outputs = res[2]
351 for output in outputs:
352 if len(output) < 2:
353 continue
354 if output[2] == crtc_id:
355 # Found our output
356 found = True
357 output_storage = output
358 break
359 if found:
360 break
361
362 if found and output_storage is not None and len(output_storage) > 7:
363 properties = output_storage[7]
364 wayland_display = {"xrandr_name": output_storage[4]}
365 raw_edid = properties.get("edid", ())
366 edid = b"".join(v.to_bytes(1, "big") for v in raw_edid)
367
368 if edid:
369 wayland_display["edid"] = edid
370 w_mm = properties.get("width-mm")
371 h_mm = properties.get("height-mm")
372 if w_mm and h_mm:
373 wayland_display["size_mm"] = (w_mm, h_mm)
374 return wayland_display
375 return None
376
377
378 def get_x_display(display_no: int = 0) -> None | str:
379 """Get the X display name for a given display number.
380
381 Args:
382 display_no (int): Display number.
383
384 Returns:
385 None | str: The X display name.
386 """
387 if (display := get_display(display_no)) and (name := display.get("name")):
388 return _get_x_display(name)
389 return None
390
391
392 def get_x_icc_profile_atom_id(display_no: int = 0) -> None | int:
393 """Get the ICC profile atom ID for a given display number.
394
395 Args:
396 display_no (int): Display number.
397
398 Returns:
399 None | int: The ICC profile atom ID.
400 """
401 display = get_display(display_no)
402 return display.get("icc_profile_atom_id") if display else None
403
404
405 def get_x_icc_profile_output_atom_id(display_no: int = 0) -> None | int:
406 """Get the ICC profile output atom ID for a given display number.
407
408 Args:
409 display_no (int): Display number.
410
411 Returns:
412 None | int: The ICC profile output atom ID.
413 """
414 display = get_display(display_no)
415 return display.get("icc_profile_output_atom_id") if display else None