Debian Codegraph @

DisplayCAL/xrandr.py

raw
1 """X11/Xrandr ctypes interface.
2
3 It allows querying and manipulating X display properties, including retrieving
4 window and output properties. The module is useful for working with X server
5 configurations and display outputs programmatically.
6 """
7
8 from __future__ import annotations
9
10 import os
11 import sys
12 from ctypes import (
13 POINTER,
14 Structure,
15 c_int,
16 c_long,
17 c_ubyte,
18 c_ulong,
19 cdll,
20 pointer,
21 util,
22 )
23 from typing import ClassVar, TYPE_CHECKING
24
25
26 if TYPE_CHECKING:
27 if sys.version_info >= (3, 11):
28 from typing import Self
29 else:
30 from typing_extensions import Self
31
32
33 libx11pth = util.find_library("X11")
34 if not libx11pth:
35 raise ImportError("Couldn't find libX11")
36 try:
37 libx11 = cdll.LoadLibrary(libx11pth)
38 except OSError as e:
39 raise ImportError("Couldn't load libX11") from e
40
41 libxrandrpth = util.find_library("Xrandr")
42 if not libxrandrpth:
43 raise ImportError("Couldn't find libXrandr")
44 try:
45 libxrandr = cdll.LoadLibrary(libxrandrpth)
46 except OSError as e:
47 raise ImportError("Couldn't load libXrandr") from e
48
49 from DisplayCAL.options import DEBUG
50
51 XA_CARDINAL = 6
52 XA_INTEGER = 19
53
54 Atom = c_ulong
55
56
57 class Display(Structure):
58 """Structure representing an X display connection.
59
60 This structure is used to manage the connection to the X server and
61 perform operations on the display.
62 """
63
64 __slots__ = []
65 _fields_: ClassVar[list[tuple]] = [("_opaque_struct", c_int)]
66
67
68 try:
69 libx11.XInternAtom.restype = Atom
70 libx11.XOpenDisplay.restype = POINTER(Display)
71 libx11.XRootWindow.restype = c_ulong
72 libx11.XGetWindowProperty.restype = c_int
73 libx11.XGetWindowProperty.argtypes = [
74 POINTER(Display),
75 c_ulong,
76 Atom,
77 c_long,
78 c_long,
79 c_int,
80 c_ulong,
81 POINTER(c_ulong),
82 POINTER(c_int),
83 POINTER(c_ulong),
84 POINTER(c_ulong),
85 POINTER(POINTER(c_ubyte)),
86 ]
87 except AttributeError as exception:
88 raise ImportError(f"libX11: {exception}") from exception
89
90 try:
91 libxrandr.XRRGetOutputProperty.restype = c_int
92 libxrandr.XRRGetOutputProperty.argtypes = [
93 POINTER(Display),
94 c_ulong,
95 Atom,
96 c_long,
97 c_long,
98 c_int,
99 c_int,
100 c_ulong,
101 POINTER(c_ulong),
102 POINTER(c_int),
103 POINTER(c_ulong),
104 POINTER(c_ulong),
105 POINTER(POINTER(c_ubyte)),
106 ]
107 except AttributeError as exception:
108 raise ImportError(f"libXrandr: {exception}") from exception
109
110
111 class XDisplay:
112 """Class to manage an X display connection and perform operations on it.
113
114 Args:
115 name (None | str): The name of the display to connect to. If None, it
116 will use the DISPLAY environment variable. Defaults to None.
117 """
118
119 def __init__(self, name=None):
120 self.name = name or os.getenv("DISPLAY")
121
122 def __enter__(self) -> Self:
123 """Enter the runtime context related to this object."""
124 self.open()
125 return self
126
127 def __exit__(self, exc_type, exc_value, tb) -> None:
128 """Exit the runtime context related to this object.
129
130 Args:
131 exc_type: The exception type.
132 exc_value: The exception value.
133 tb: The traceback object.
134 """
135 self.close()
136
137 def open(self) -> None:
138 """Open a connection to the X display.
139
140 Raises:
141 ValueError: If the display name is invalid or cannot be opened.
142 """
143 self.display = libx11.XOpenDisplay(self.name.encode())
144 if not self.display:
145 raise ValueError(f"Invalid X display {self.name!r}")
146
147 def close(self) -> None:
148 """Close the X display connection."""
149 libx11.XCloseDisplay(self.display)
150
151 def intern_atom(self, atom_name):
152 """Intern an atom by its name.
153
154 Args:
155 atom_name (str): The name of the atom to intern.
156
157 Raises:
158 ValueError: If the atom name is invalid or cannot be interned.
159
160 Returns:
161 int: The atom identifier for the specified atom name.
162 """
163 atom_id = libx11.XInternAtom(self.display, atom_name, False)
164 if not atom_id:
165 raise ValueError(f"Invalid atom name {atom_name!r}")
166
167 return atom_id
168
169 def root_window(self, screen_no=0):
170 """Get the root window for a given screen number.
171
172 Args:
173 screen_no (int): The screen number for which to get the root window.
174 Defaults to 0.
175
176 Raises:
177 ValueError: If the screen number is invalid or the root window cannot
178 be retrieved.
179
180 Returns:
181 int: The root window identifier for the specified screen.
182 """
183 window = libx11.XRootWindow(self.display, screen_no)
184 if not window:
185 raise ValueError(f"Invalid X screen {screen_no!r}")
186
187 return window
188
189 def get_window_property(self, window, atom_id, atom_type=XA_CARDINAL):
190 """Get the property of an X window.
191
192 Args:
193 window (int): The window identifier.
194 atom_id (int): The atom identifier for the property.
195 atom_type (int): The type of the atom, default is XA_CARDINAL.
196
197 Raises:
198 ValueError: If the window is invalid or the property cannot be retrieved.
199
200 Returns:
201 list: A list of property values for the specified window.
202 """
203 ret_type, ret_format, ret_len, ret_togo, atomv = (
204 c_ulong(),
205 c_int(),
206 c_ulong(),
207 c_ulong(),
208 pointer(c_ubyte()),
209 )
210
211 window_property = None
212 if (
213 libx11.XGetWindowProperty(
214 self.display,
215 window,
216 atom_id,
217 0,
218 0x7FFFFFF,
219 False,
220 atom_type,
221 ret_type,
222 ret_format,
223 ret_len,
224 ret_togo,
225 atomv,
226 )
227 == 0
228 and ret_len.value > 0
229 ):
230 if DEBUG:
231 print("ret_type:", ret_type.value)
232 print("ret_format:", ret_format.value)
233 print("ret_len:", ret_len.value)
234 print("ret_togo:", ret_togo.value)
235 window_property = [atomv[i] for i in range(ret_len.value)]
236
237 return window_property
238
239 def get_output_property(self, output, atom_id, atom_type=XA_CARDINAL):
240 """Get the property of an X output.
241
242 Args:
243 output (int): The output identifier.
244 atom_id (int): The atom identifier for the property.
245 atom_type (int): The type of the atom, default is XA_CARDINAL.
246
247 Raises:
248 ValueError: If the output is invalid or the property cannot be retrieved.
249
250 Returns:
251 list: A list of property values for the specified output.
252 """
253 if not output:
254 raise ValueError(f"Invalid output {output!r} specified")
255
256 ret_type, ret_format, ret_len, ret_togo, atomv = (
257 c_ulong(),
258 c_int(),
259 c_ulong(),
260 c_ulong(),
261 pointer(c_ubyte()),
262 )
263
264 output_property = None
265 if (
266 libxrandr.XRRGetOutputProperty(
267 self.display,
268 output,
269 atom_id,
270 0,
271 0x7FFFFFF,
272 False,
273 False,
274 atom_type,
275 ret_type,
276 ret_format,
277 ret_len,
278 ret_togo,
279 atomv,
280 )
281 == 0
282 and ret_len.value > 0
283 ):
284 if DEBUG:
285 print("ret_type:", ret_type.value)
286 print("ret_format:", ret_format.value)
287 print("ret_len:", ret_len.value)
288 print("ret_togo:", ret_togo.value)
289 output_property = [atomv[i] for i in range(ret_len.value)]
290
291 return output_property
292
293
294 if __name__ == "__main__":
295 with XDisplay() as display:
296 output_property = display.get_output_property(
297 int(sys.argv[1]), sys.argv[2], int(sys.argv[3])
298 )
299 print(f"{sys.argv[2]} for display {sys.argv[1]}: {output_property!r}")