Debian Codegraph @

DisplayCAL/util_dbus.py

raw
1 """Utilities for interacting with D-Bus using Gio or dbus.
2
3 Provides object access, method calls, properties, and introspection.
4 """
5
6 # Standard library imports
7 from __future__ import annotations
8
9 import sys
10
11 USE_GI = True
12
13 DBusException = Exception
14
15 if sys.platform not in ("darwin", "win32"):
16 if USE_GI:
17 try:
18 from gi.repository import Gio, GLib
19 except ImportError:
20 USE_GI = False
21 if not USE_GI:
22 import dbus
23 from dbus.mainloop import glib
24 from DisplayCAL.util_xml import XMLDict
25
26 if USE_GI:
27 dbus_session = Gio.bus_get_sync(Gio.BusType.SESSION, None)
28 dbus_system = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
29
30 DBusException = GLib.Error
31 else:
32 glib.threads_init()
33
34 dbus_session = dbus.SessionBus()
35 dbus_system = dbus.SystemBus()
36
37 DBusException = dbus.exceptions.DBusException
38
39
40 from DisplayCAL.util_str import safe_str
41
42 BUSTYPE_SESSION = 1
43 BUSTYPE_SYSTEM = 2
44
45
46 class DBusObjectInterfaceMethod:
47 """A class representing a D-Bus object interface method.
48
49 Args:
50 iface (object): The D-Bus interface object.
51 method_name (str): The name of the D-Bus method.
52 """
53
54 def __init__(self, iface: object, method_name: str) -> None:
55 self._iface = iface
56 self._method_name = method_name
57
58 def __call__(self, *args, **kwargs) -> object:
59 """Call the D-Bus method with the given arguments.
60
61 Args:
62 *args: Positional arguments to pass to the D-Bus method.
63 **kwargs: Keyword arguments to pass to the D-Bus method.
64
65 Returns:
66 object: The result of the D-Bus method call.
67 """
68 if USE_GI:
69 format_string = ""
70 value = []
71 for arg in args:
72 if isinstance(arg, str):
73 format_string += "s"
74 elif isinstance(arg, int):
75 if arg < 0:
76 format_string += "i"
77 else:
78 format_string += "u"
79 elif isinstance(arg, float):
80 format_string += "f"
81 else:
82 raise TypeError(f"Unsupported argument type: {type(arg)}")
83 value.append(arg)
84 args = [f"({format_string})"]
85 args.extend(value)
86 if "timeout" not in kwargs:
87 kwargs["timeout"] = 500
88 return getattr(self._iface, self._method_name)(*args, **kwargs)
89
90
91 class DBusObject:
92 """A class representing a D-Bus object.
93
94 Args:
95 bus_type (int): The type of D-Bus bus (BUSTYPE_SESSION or
96 BUSTYPE_SYSTEM).
97 bus_name (str): The D-Bus bus name.
98 object_path (None | str): The D-Bus object path. If None, it is
99 derived from the bus name.
100 iface_name (None | str): The D-Bus interface name. If None, the
101 bus name is used as the interface name.
102 """
103
104 def __init__(
105 self,
106 bus_type: int,
107 bus_name: str,
108 object_path: None | str = None,
109 iface_name: None | str = None,
110 ) -> None:
111 self._bus_type = bus_type
112 self._bus_name = bus_name
113 if object_path is None:
114 object_path = "/" + bus_name.replace(".", "/")
115 self._object_path = object_path
116 self._iface_name = iface_name
117 self._proxy = None
118 self._iface = None
119 if object_path:
120 bus = dbus_session if bus_type == BUSTYPE_SESSION else dbus_system
121 self._bus = bus
122 interface = self._bus_name
123 if self._iface_name:
124 interface += "." + self._iface_name
125 try:
126 if USE_GI:
127 self._proxy = Gio.DBusProxy.new_sync(
128 bus,
129 Gio.DBusProxyFlags.NONE,
130 None,
131 bus_name,
132 object_path,
133 interface,
134 None,
135 )
136 self._iface = self._proxy
137 else:
138 self._proxy = bus.get_object(bus_name, object_path)
139 self._iface = dbus.Interface(self._proxy, dbus_interface=interface)
140 except (TypeError, ValueError, DBusException) as exception:
141 raise DBusObjectError(exception, self._bus_name) from exception
142 self._introspectable = None
143
144 def __getattr__(self, name: str) -> DBusObjectInterfaceMethod:
145 """Get an attribute of the D-Bus object.
146
147 Args:
148 name (str): The name of the attribute to get.
149
150 Raises:
151 DBusObjectError: If the attribute cannot be accessed.
152
153 Returns:
154 DBusObjectInterfaceMethod: The method corresponding to the attribute name.
155 """
156 name = "".join(part.capitalize() for part in name.split("_"))
157 try:
158 return DBusObjectInterfaceMethod(self._iface, name)
159 except (AttributeError, TypeError, ValueError, DBusException) as exception:
160 raise DBusObjectError(exception, self._bus_name) from exception
161
162 @property
163 def properties(self) -> dict:
164 """Get all properties of the D-Bus object.
165
166 Raises:
167 DBusObjectError: If properties cannot be accessed.
168
169 Returns:
170 dict: A dictionary of all properties of the D-Bus object.
171 """
172 if not self._proxy:
173 return {}
174 interface = self._bus_name
175 if self._iface_name:
176 interface += f".{self._iface_name}"
177 try:
178 if USE_GI:
179 iface = Gio.DBusProxy.new_sync(
180 self._bus,
181 Gio.DBusProxyFlags.NONE,
182 None,
183 self._bus_name,
184 self._object_path,
185 "org.freedesktop.DBus.Properties",
186 None,
187 )
188 else:
189 iface = dbus.Interface(self._proxy, "org.freedesktop.DBus.Properties")
190 return DBusObjectInterfaceMethod(iface, "GetAll")(interface)
191 except (TypeError, ValueError, DBusException) as exception:
192 raise DBusObjectError(exception, self._bus_name) from exception
193
194 def introspect(self) -> XMLDict:
195 """Introspect the D-Bus object to get its XML representation.
196
197 Raises:
198 DBusObjectError: If introspection fails.
199
200 Returns:
201 XMLDict: An XMLDict representation of the introspected D-Bus object.
202 """
203 if not self._introspectable:
204 self._introspectable = DBusObject(
205 self._bus_type,
206 "org.freedesktop.DBus",
207 "/" + self._bus_name.replace(".", "/"),
208 "Introspectable",
209 )
210 xml = self._introspectable.Introspect()
211 return XMLDict(xml)
212
213
214 class DBusObjectError(DBusException):
215 """Custom exception class for D-Bus object errors.
216
217 Args:
218 exception (Exception): The original exception that occurred.
219 bus_name (str | None): The D-Bus bus name associated with the error.
220 """
221
222 def __init__(self, exception: Exception, bus_name: None | str = None) -> None:
223 self._dbus_error_name = getattr(exception, "get_dbus_name", lambda: None)()
224 if self._dbus_error_name == "org.freedesktop.DBus.Error.ServiceUnknown":
225 exception = f"{exception}: {bus_name}"
226 DBusException.__init__(self, safe_str(exception))
227
228 def get_dbus_name(self) -> None | str:
229 """Get the D-Bus error name.
230
231 Returns:
232 None | str: The D-Bus error name, or None if not available.
233 """
234 return self._dbus_error_name