| 1 |
# SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 |
# |
| 3 |
# This file is formatted with Python Black |
| 4 |
|
| 5 |
from dbus.mainloop.glib import DBusGMainLoop |
| 6 |
from gi.repository import GLib, Gio, GioUnix |
| 7 |
from itertools import count |
| 8 |
from typing import Any, Dict, Optional, NamedTuple, Callable, List |
| 9 |
from pathlib import Path |
| 10 |
from enum import Enum, IntEnum |
| 11 |
from dataclasses import dataclass |
| 12 |
from urllib.parse import unquote, urlparse |
| 13 |
|
| 14 |
import os |
| 15 |
import dbus |
| 16 |
import dbus.proxies |
| 17 |
import dbusmock |
| 18 |
import logging |
| 19 |
import subprocess |
| 20 |
|
| 21 |
|
| 22 |
DBusGMainLoop(set_as_default=True) |
| 23 |
|
| 24 |
# Anything that takes longer than 5s needs to fail |
| 25 |
DBUS_TIMEOUT = int(os.environ.get("XDP_DBUS_TIMEOUT", "5000")) |
| 26 |
|
| 27 |
_counter = count() |
| 28 |
|
| 29 |
ASV = Dict[str, Any] |
| 30 |
|
| 31 |
|
| 32 |
def init_logger(name: str) -> logging.Logger: |
| 33 |
""" |
| 34 |
Common logging setup for tests. Use as: |
| 35 |
|
| 36 |
>>> import tests.xdp_utils as xdp |
| 37 |
>>> logger = xdp.init_logger(__name__) |
| 38 |
>>> logger.debug("foo") |
| 39 |
|
| 40 |
""" |
| 41 |
logging.basicConfig( |
| 42 |
format="%(levelname).1s|%(name)s: %(message)s", level=logging.DEBUG |
| 43 |
) |
| 44 |
logger = logging.getLogger(f"xdp.{name}") |
| 45 |
logger.setLevel(logging.DEBUG) |
| 46 |
return logger |
| 47 |
|
| 48 |
|
| 49 |
logger = init_logger("utils") |
| 50 |
|
| 51 |
|
| 52 |
def is_in_ci() -> bool: |
| 53 |
return os.environ.get("XDP_TEST_IN_CI") is not None |
| 54 |
|
| 55 |
|
| 56 |
def is_in_container() -> bool: |
| 57 |
return is_in_ci() or ( |
| 58 |
"container" in os.environ |
| 59 |
and (os.environ["container"] == "docker" or os.environ["container"] == "podman") |
| 60 |
) |
| 61 |
|
| 62 |
|
| 63 |
def run_long_tests() -> bool: |
| 64 |
return os.environ.get("XDP_TEST_RUN_LONG") is not None |
| 65 |
|
| 66 |
|
| 67 |
def is_valgrind() -> bool: |
| 68 |
return os.getenv("XDP_TEST_VALGRIND") is not None |
| 69 |
|
| 70 |
|
| 71 |
def check_program_success(cmd) -> bool: |
| 72 |
proc = subprocess.Popen( |
| 73 |
cmd, stdout=None, stderr=None, shell=True, universal_newlines=True |
| 74 |
) |
| 75 |
_ = proc.communicate() |
| 76 |
return proc.returncode == 0 |
| 77 |
|
| 78 |
|
| 79 |
def uri_same_file(uri1, uri2): |
| 80 |
orig = Path(unquote(urlparse(uri1).path)) |
| 81 |
path = Path(unquote(urlparse(uri2).path)) |
| 82 |
return orig.read_text() == path.read_text() |
| 83 |
|
| 84 |
|
| 85 |
def uris_same_files(uris, uris_other): |
| 86 |
return all( |
| 87 |
uri_same_file(uri, uri_other) for uri, uri_other in zip(uris, uris_other) |
| 88 |
) |
| 89 |
|
| 90 |
|
| 91 |
class FuseNotSupportedException(Exception): |
| 92 |
pass |
| 93 |
|
| 94 |
|
| 95 |
def ensure_fuse_supported() -> None: |
| 96 |
if not check_program_success("fusermount3 --version"): |
| 97 |
raise FuseNotSupportedException("no fusermount3") |
| 98 |
|
| 99 |
if not check_program_success( |
| 100 |
"capsh --print | grep -q 'Bounding set.*[^a-z]cap_sys_admin'" |
| 101 |
): |
| 102 |
raise FuseNotSupportedException( |
| 103 |
"No cap_sys_admin in bounding set, can't use FUSE" |
| 104 |
) |
| 105 |
|
| 106 |
if not check_program_success("[ -w /dev/fuse ]"): |
| 107 |
raise FuseNotSupportedException("no write access to /dev/fuse") |
| 108 |
|
| 109 |
if not check_program_success("[ -e /etc/mtab ]"): |
| 110 |
raise FuseNotSupportedException("no /etc/mtab") |
| 111 |
|
| 112 |
|
| 113 |
def wait(ms: int): |
| 114 |
""" |
| 115 |
Waits for the specified amount of milliseconds. |
| 116 |
""" |
| 117 |
mainloop = GLib.MainLoop() |
| 118 |
GLib.timeout_add(ms, mainloop.quit) |
| 119 |
mainloop.run() |
| 120 |
|
| 121 |
|
| 122 |
def wait_for(fn: Callable[[], bool]): |
| 123 |
""" |
| 124 |
Waits and dispatches to mainloop until the function fn returns true. This is |
| 125 |
useful in combination with a lambda which captures a variable: |
| 126 |
|
| 127 |
my_var = False |
| 128 |
def callback(): |
| 129 |
my_var = True |
| 130 |
do_something_later(callback) |
| 131 |
xdp.wait_for(lambda: my_var) |
| 132 |
""" |
| 133 |
mainloop = GLib.MainLoop() |
| 134 |
while not fn(): |
| 135 |
GLib.timeout_add(50, mainloop.quit) |
| 136 |
mainloop.run() |
| 137 |
|
| 138 |
|
| 139 |
def get_permission_store_iface(bus: dbus.Bus) -> dbus.Interface: |
| 140 |
""" |
| 141 |
Returns the dbus interface of the xdg-permission-store. |
| 142 |
""" |
| 143 |
obj = bus.get_object( |
| 144 |
"org.freedesktop.impl.portal.PermissionStore", |
| 145 |
"/org/freedesktop/impl/portal/PermissionStore", |
| 146 |
) |
| 147 |
return dbus.Interface(obj, "org.freedesktop.impl.portal.PermissionStore") |
| 148 |
|
| 149 |
|
| 150 |
def get_document_portal_iface(bus: dbus.Bus) -> dbus.Interface: |
| 151 |
""" |
| 152 |
Returns the dbus interface of the xdg-document-portal. |
| 153 |
""" |
| 154 |
obj = bus.get_object( |
| 155 |
"org.freedesktop.portal.Documents", |
| 156 |
"/org/freedesktop/portal/documents", |
| 157 |
) |
| 158 |
return dbus.Interface(obj, "org.freedesktop.portal.Documents") |
| 159 |
|
| 160 |
|
| 161 |
def get_mock_iface(bus: dbus.Bus, bus_name: Optional[str] = None) -> dbus.Interface: |
| 162 |
""" |
| 163 |
Returns the mock interface of the xdg-desktop-portal. |
| 164 |
""" |
| 165 |
if not bus_name: |
| 166 |
bus_name = "org.freedesktop.impl.portal.Test" |
| 167 |
|
| 168 |
obj = bus.get_object(bus_name, "/org/freedesktop/portal/desktop") |
| 169 |
return dbus.Interface(obj, dbusmock.MOCK_IFACE) |
| 170 |
|
| 171 |
|
| 172 |
def portal_interface_name(portal_name: str, domain: Optional[str] = None) -> str: |
| 173 |
""" |
| 174 |
Returns the fully qualified interface for a portal name. |
| 175 |
""" |
| 176 |
if domain: |
| 177 |
return f"org.freedesktop.{domain}.portal.{portal_name}" |
| 178 |
else: |
| 179 |
return f"org.freedesktop.portal.{portal_name}" |
| 180 |
|
| 181 |
|
| 182 |
def get_portal_iface( |
| 183 |
bus: dbus.Bus, name: str, domain: Optional[str] = None |
| 184 |
) -> dbus.Interface: |
| 185 |
""" |
| 186 |
Returns the dbus interface for a portal name. |
| 187 |
""" |
| 188 |
name = portal_interface_name(name, domain) |
| 189 |
return get_iface(bus, name) |
| 190 |
|
| 191 |
|
| 192 |
def get_iface(bus: dbus.Bus, name: str) -> dbus.Interface: |
| 193 |
""" |
| 194 |
Returns a named interface of the main portal object. |
| 195 |
""" |
| 196 |
try: |
| 197 |
ifaces = bus._xdp_portal_ifaces |
| 198 |
except AttributeError: |
| 199 |
ifaces = bus._xdp_portal_ifaces = {} |
| 200 |
|
| 201 |
try: |
| 202 |
intf = ifaces[name] |
| 203 |
except KeyError: |
| 204 |
intf = dbus.Interface(get_xdp_dbus_object(bus), name) |
| 205 |
assert intf |
| 206 |
ifaces[name] = intf |
| 207 |
return intf |
| 208 |
|
| 209 |
|
| 210 |
def get_xdp_dbus_object(bus: dbus.Bus) -> dbus.proxies.ProxyObject: |
| 211 |
""" |
| 212 |
Returns the main portal object. |
| 213 |
""" |
| 214 |
try: |
| 215 |
obj = getattr(bus, "_xdp_dbus_object") |
| 216 |
except AttributeError: |
| 217 |
obj = bus.get_object( |
| 218 |
"org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop" |
| 219 |
) |
| 220 |
assert obj |
| 221 |
bus._xdp_dbus_object = obj |
| 222 |
return obj |
| 223 |
|
| 224 |
|
| 225 |
def check_version(bus: dbus.Bus, portal_name: str, expected_version: int): |
| 226 |
""" |
| 227 |
Checks that the portal_name portal version is equal to expected_version. |
| 228 |
""" |
| 229 |
properties_intf = dbus.Interface( |
| 230 |
get_xdp_dbus_object(bus), "org.freedesktop.DBus.Properties" |
| 231 |
) |
| 232 |
portal_iface_name = portal_interface_name(portal_name) |
| 233 |
try: |
| 234 |
portal_version = properties_intf.Get(portal_iface_name, "version") |
| 235 |
assert int(portal_version) == expected_version |
| 236 |
except dbus.exceptions.DBusException as e: |
| 237 |
logger.critical(e) |
| 238 |
assert e is None, str(e) |
| 239 |
|
| 240 |
|
| 241 |
def desktop_files_path() -> Path: |
| 242 |
"""Returns the default path for desktop files""" |
| 243 |
return Path(os.environ["XDG_DATA_HOME"]) / "applications" |
| 244 |
|
| 245 |
|
| 246 |
@dataclass |
| 247 |
class AppInfo: |
| 248 |
""" |
| 249 |
Testing code can use this class to construct a specific XdpAppInfo for the |
| 250 |
xdp_app_info fixture. |
| 251 |
|
| 252 |
To make it possible to collect AppInfo instances in pytest, construction |
| 253 |
only fills out the data. The conftest.py file calls _initialize() to |
| 254 |
properly initialize everything that's needed at run time, and uses some |
| 255 |
properties to modify how it creates the harness. |
| 256 |
""" |
| 257 |
|
| 258 |
app_id: str |
| 259 |
desktop_file: str | None |
| 260 |
|
| 261 |
def __init__(self): |
| 262 |
self._env = {} |
| 263 |
|
| 264 |
def get_xdp_executable_env(self): |
| 265 |
return self._env |
| 266 |
|
| 267 |
def gapp_info(self) -> GioUnix.DesktopAppInfo: |
| 268 |
assert self.desktop_file |
| 269 |
desktop_file_path = desktop_files_path() / self.desktop_file |
| 270 |
if not os.path.exists(desktop_file_path): |
| 271 |
return None |
| 272 |
|
| 273 |
return GioUnix.DesktopAppInfo.new_from_filename(str(desktop_file_path)) |
| 274 |
|
| 275 |
|
| 276 |
@dataclass |
| 277 |
class AppInfoHost(AppInfo): |
| 278 |
app_id: str = "org.example.Test" |
| 279 |
desktop_file: str | None = None |
| 280 |
desktop_entry: bytes | None = None |
| 281 |
|
| 282 |
def __post_init__(self): |
| 283 |
if not self.desktop_file: |
| 284 |
self.desktop_file = f"{self.app_id}.desktop" |
| 285 |
|
| 286 |
self._env = { |
| 287 |
"XDG_DESKTOP_PORTAL_TEST_APP_INFO_KIND": "host", |
| 288 |
"XDG_DESKTOP_PORTAL_TEST_HOST_APPID": self.app_id, |
| 289 |
} |
| 290 |
|
| 291 |
def _initialize(self): |
| 292 |
assert self.desktop_file |
| 293 |
|
| 294 |
if self.desktop_entry: |
| 295 |
path = desktop_files_path() / self.desktop_file |
| 296 |
path.write_bytes(self.desktop_entry) |
| 297 |
|
| 298 |
|
| 299 |
@dataclass |
| 300 |
class AppInfoFlatpak(AppInfo): |
| 301 |
app_id: str = "org.example.Test" |
| 302 |
desktop_file: str | None = None |
| 303 |
desktop_entry: bytes | None = None |
| 304 |
instance_id: str | None = None |
| 305 |
usb_queries: str | None = None |
| 306 |
metadata: bytes | None = None |
| 307 |
|
| 308 |
def __post_init__(self): |
| 309 |
if not self.desktop_file: |
| 310 |
self.desktop_file = f"{self.app_id}.desktop" |
| 311 |
|
| 312 |
self._env = { |
| 313 |
"XDG_DESKTOP_PORTAL_TEST_APP_INFO_KIND": "flatpak", |
| 314 |
} |
| 315 |
|
| 316 |
if not self.instance_id: |
| 317 |
self.instance_id = "1234567890" |
| 318 |
|
| 319 |
if not self.desktop_entry: |
| 320 |
self.desktop_entry = b""" |
| 321 |
[Desktop Entry] |
| 322 |
Version=1.0 |
| 323 |
Name=Example App |
| 324 |
Exec=true %u |
| 325 |
Type=Application |
| 326 |
""" |
| 327 |
|
| 328 |
if not self.metadata: |
| 329 |
metadata_str = f""" |
| 330 |
[Application] |
| 331 |
name={self.app_id} |
| 332 |
runtime=org.freedesktop.Platform/x86_64/23.08 |
| 333 |
sdk=org.freedesktop.Sdk/x86_64/23.08 |
| 334 |
command={self.app_id} |
| 335 |
|
| 336 |
[Instance] |
| 337 |
instance-id={self.instance_id} |
| 338 |
|
| 339 |
[Context] |
| 340 |
shared=network;ipc; |
| 341 |
sockets=x11;wayland;pulseaudio;fallback-x11; |
| 342 |
devices=dri; |
| 343 |
""" |
| 344 |
self.metadata = metadata_str.encode("utf8") |
| 345 |
|
| 346 |
if self.usb_queries: |
| 347 |
metadata_usb_str = f""" |
| 348 |
[USB Devices] |
| 349 |
enumerable-devices={self.usb_queries} |
| 350 |
""" |
| 351 |
self.metadata += metadata_usb_str.encode("utf8") |
| 352 |
|
| 353 |
def _initialize(self): |
| 354 |
assert self.desktop_file |
| 355 |
assert self.desktop_entry |
| 356 |
assert self.metadata |
| 357 |
|
| 358 |
path = desktop_files_path() / self.desktop_file |
| 359 |
path.parent.mkdir(parents=True, exist_ok=True) |
| 360 |
path.write_bytes(self.desktop_entry) |
| 361 |
|
| 362 |
metadata_path = Path(os.environ["TMPDIR"]) / "flatpak-metadata" |
| 363 |
metadata_path.write_bytes(self.metadata) |
| 364 |
|
| 365 |
self._env["XDG_DESKTOP_PORTAL_TEST_FLATPAK_METADATA"] = ( |
| 366 |
metadata_path.absolute().as_posix() |
| 367 |
) |
| 368 |
|
| 369 |
|
| 370 |
@dataclass |
| 371 |
class AppInfoSnap(AppInfo): |
| 372 |
app_id: str = "org.example.Test" |
| 373 |
desktop_file: str | None = None |
| 374 |
desktop_entry: bytes | None = None |
| 375 |
common_id: str = "org.example.Test" |
| 376 |
snap_name: str = "test" |
| 377 |
app_name: str = "test" |
| 378 |
metadata: bytes | None = None |
| 379 |
|
| 380 |
def __post_init__(self): |
| 381 |
self.app_id = f"snap.{self.snap_name}" |
| 382 |
self.desktop_file = f"{self.snap_name}_{self.app_name}.desktop" |
| 383 |
self._env = { |
| 384 |
"XDG_DESKTOP_PORTAL_TEST_APP_INFO_KIND": "snap", |
| 385 |
} |
| 386 |
|
| 387 |
if not self.desktop_entry: |
| 388 |
desktop_entry_str = f""" |
| 389 |
[Desktop Entry] |
| 390 |
Version=1.0 |
| 391 |
Name=Example App |
| 392 |
Exec=true %u |
| 393 |
Type=Application |
| 394 |
X-SnapInstanceName={self.snap_name} |
| 395 |
X-SnapAppName={self.app_name} |
| 396 |
""" |
| 397 |
self.desktop_entry = desktop_entry_str.encode("UTF-8") |
| 398 |
|
| 399 |
if not self.metadata: |
| 400 |
metadata_str = f""" |
| 401 |
[Snap Info] |
| 402 |
InstanceName={self.snap_name} |
| 403 |
AppName={self.app_name} |
| 404 |
CommonID={self.common_id} |
| 405 |
DesktopFile={self.desktop_file} |
| 406 |
""" |
| 407 |
self.metadata = metadata_str.encode("UTF-8") |
| 408 |
|
| 409 |
def _initialize(self): |
| 410 |
assert self.desktop_file |
| 411 |
assert self.desktop_entry |
| 412 |
assert self.metadata |
| 413 |
|
| 414 |
path = desktop_files_path() / self.desktop_file |
| 415 |
path.parent.mkdir(parents=True, exist_ok=True) |
| 416 |
path.write_bytes(self.desktop_entry) |
| 417 |
|
| 418 |
metadata_path = Path(os.environ["TMPDIR"]) / "snap-metadata" |
| 419 |
metadata_path.write_bytes(self.metadata) |
| 420 |
|
| 421 |
self._env["XDG_DESKTOP_PORTAL_TEST_SNAP_METADATA"] = ( |
| 422 |
metadata_path.absolute().as_posix() |
| 423 |
) |
| 424 |
|
| 425 |
|
| 426 |
@dataclass |
| 427 |
class AppInfoLinyaps(AppInfo): |
| 428 |
app_id: str = "org.example.Test" |
| 429 |
desktop_file: str | None = None |
| 430 |
desktop_entry: bytes | None = None |
| 431 |
instance_id: str | None = None |
| 432 |
metadata: bytes | None = None |
| 433 |
|
| 434 |
def __post_init__(self): |
| 435 |
self.desktop_file = f"{self.app_id}.desktop" |
| 436 |
self._env = { |
| 437 |
"XDG_DESKTOP_PORTAL_TEST_APP_INFO_KIND": "linyaps", |
| 438 |
} |
| 439 |
|
| 440 |
if not self.instance_id: |
| 441 |
self.instance_id = ( |
| 442 |
"278575aac695dafe08974feb55c84bba69e862216e980b7ede28c5844e93682c" |
| 443 |
) |
| 444 |
|
| 445 |
if not self.desktop_entry: |
| 446 |
self.desktop_entry = b""" |
| 447 |
[Desktop Entry] |
| 448 |
Version=1.0 |
| 449 |
Name=Example App |
| 450 |
Exec=true %u |
| 451 |
Type=Application |
| 452 |
""" |
| 453 |
|
| 454 |
if not self.metadata: |
| 455 |
metadata_str = f""" |
| 456 |
[General] |
| 457 |
Linyaps-version=1.10.0 |
| 458 |
|
| 459 |
[Application] |
| 460 |
Id={self.app_id} |
| 461 |
|
| 462 |
[Instance] |
| 463 |
Id={self.instance_id} |
| 464 |
|
| 465 |
[Context] |
| 466 |
Network=shared |
| 467 |
""" |
| 468 |
self.metadata = metadata_str.encode("utf8") |
| 469 |
|
| 470 |
def _initialize(self): |
| 471 |
assert self.desktop_file |
| 472 |
assert self.desktop_entry |
| 473 |
assert self.metadata |
| 474 |
|
| 475 |
path = desktop_files_path() / self.desktop_file |
| 476 |
path.parent.mkdir(parents=True, exist_ok=True) |
| 477 |
path.write_bytes(self.desktop_entry) |
| 478 |
|
| 479 |
metadata_path = Path(os.environ["TMPDIR"]) / "linyaps-metadata" |
| 480 |
metadata_path.write_bytes(self.metadata) |
| 481 |
|
| 482 |
self._env["XDG_DESKTOP_PORTAL_TEST_LINYAPS_METADATA"] = ( |
| 483 |
metadata_path.absolute().as_posix() |
| 484 |
) |
| 485 |
|
| 486 |
|
| 487 |
class Response(NamedTuple): |
| 488 |
""" |
| 489 |
Response as returned by a completed :class:`Request` |
| 490 |
""" |
| 491 |
|
| 492 |
response: int |
| 493 |
results: ASV |
| 494 |
|
| 495 |
|
| 496 |
class ResponseTimeout(Exception): |
| 497 |
""" |
| 498 |
Exception raised by :meth:`Request.call` if the Request did not receive a |
| 499 |
Response in time. |
| 500 |
""" |
| 501 |
|
| 502 |
pass |
| 503 |
|
| 504 |
|
| 505 |
class Closable: |
| 506 |
""" |
| 507 |
Parent class for both Session and Request. Both of these have a Close() |
| 508 |
method. |
| 509 |
""" |
| 510 |
|
| 511 |
def __init__(self, bus: dbus.Bus, objpath: str): |
| 512 |
self.objpath = objpath |
| 513 |
# GLib makes assertions in callbacks impossible, so we wrap all |
| 514 |
# callbacks into a try: except and store the error on the request to |
| 515 |
# be raised later when we're back in the main context |
| 516 |
self.error: Optional[Exception] = None |
| 517 |
|
| 518 |
self._mainloop: Optional[GLib.MainLoop] = None |
| 519 |
self._impl_closed = False |
| 520 |
self._bus = bus |
| 521 |
|
| 522 |
self._closable = type(self).__name__ |
| 523 |
assert self._closable in ("Request", "Session") |
| 524 |
proxy = bus.get_object("org.freedesktop.portal.Desktop", objpath) |
| 525 |
self._closable_interface = dbus.Interface( |
| 526 |
proxy, f"org.freedesktop.portal.{self._closable}" |
| 527 |
) |
| 528 |
|
| 529 |
@property |
| 530 |
def bus(self) -> dbus.Bus: |
| 531 |
return self._bus |
| 532 |
|
| 533 |
@property |
| 534 |
def closed(self) -> bool: |
| 535 |
""" |
| 536 |
True if the impl.portal was closed |
| 537 |
""" |
| 538 |
return self._impl_closed |
| 539 |
|
| 540 |
def close(self) -> None: |
| 541 |
signal_match = None |
| 542 |
|
| 543 |
def cb_impl_closed_by_portal(handle) -> None: |
| 544 |
if handle == self.objpath: |
| 545 |
logger.debug(f"Impl{self._closable} {self.objpath} was closed") |
| 546 |
signal_match.remove() # type: ignore |
| 547 |
self._impl_closed = True |
| 548 |
if self.closed and self._mainloop: |
| 549 |
self._mainloop.quit() |
| 550 |
|
| 551 |
# See :class:`ImplRequest`, this signal is a side-channel for the |
| 552 |
# impl.portal template to notify us when the impl.Request was really |
| 553 |
# closed by the portal. |
| 554 |
signal_match = self._bus.add_signal_receiver( |
| 555 |
cb_impl_closed_by_portal, |
| 556 |
f"{self._closable}Closed", |
| 557 |
dbus_interface="org.freedesktop.impl.portal.Mock", |
| 558 |
) |
| 559 |
|
| 560 |
logger.debug(f"Closing {self._closable} {self.objpath}") |
| 561 |
self._closable_interface.Close() |
| 562 |
|
| 563 |
def schedule_close(self, timeout_ms=300): |
| 564 |
""" |
| 565 |
Schedule an automatic Close() on the given timeout in milliseconds. |
| 566 |
""" |
| 567 |
assert 0 < timeout_ms < DBUS_TIMEOUT |
| 568 |
GLib.timeout_add(timeout_ms * 10 if is_valgrind() else timeout_ms, self.close) |
| 569 |
|
| 570 |
|
| 571 |
class Request(Closable): |
| 572 |
""" |
| 573 |
Helper class for executing methods that use Requests. This calls takes |
| 574 |
care of subscribing to the signals and invokes the method on the |
| 575 |
interface with the expected behaviors. A typical invocation is: |
| 576 |
|
| 577 |
>>> response = Request(connection, interface).call("Foo", bar="bar") |
| 578 |
>>> assert response.response == 0 |
| 579 |
|
| 580 |
Requests can only be used once, to call a second method you must |
| 581 |
instantiate a new Request object. |
| 582 |
""" |
| 583 |
|
| 584 |
def __init__(self, bus: dbus.Bus, interface: dbus.Interface): |
| 585 |
def sanitize(name): |
| 586 |
return name.lstrip(":").replace(".", "_") |
| 587 |
|
| 588 |
sender_token = sanitize(bus.get_unique_name()) |
| 589 |
self._handle_token = f"request{next(_counter)}" |
| 590 |
self.handle = f"/org/freedesktop/portal/desktop/request/{sender_token}/{self._handle_token}" |
| 591 |
# The Closable |
| 592 |
super().__init__(bus, self.handle) |
| 593 |
|
| 594 |
self.interface = interface |
| 595 |
self.response: Optional[Response] = None |
| 596 |
self.used = False |
| 597 |
# GLib makes assertions in callbacks impossible, so we wrap all |
| 598 |
# callbacks into a try: except and store the error on the request to |
| 599 |
# be raised later when we're back in the main context |
| 600 |
self.error: Optional[Exception] = None |
| 601 |
|
| 602 |
proxy = bus.get_object("org.freedesktop.portal.Desktop", self.handle) |
| 603 |
self.mock_interface = dbus.Interface(proxy, dbusmock.MOCK_IFACE) |
| 604 |
self._proxy = bus.get_object("org.freedesktop.portal.Desktop", self.handle) |
| 605 |
|
| 606 |
def cb_response(response: int, results: ASV) -> None: |
| 607 |
try: |
| 608 |
logger.debug(f"Response received on {self.handle}") |
| 609 |
assert self.response is None |
| 610 |
self.response = Response(response, results) |
| 611 |
if self._mainloop: |
| 612 |
self._mainloop.quit() |
| 613 |
except Exception as e: |
| 614 |
self.error = e |
| 615 |
|
| 616 |
self.request_interface = dbus.Interface(proxy, "org.freedesktop.portal.Request") |
| 617 |
self.request_interface.connect_to_signal("Response", cb_response) |
| 618 |
|
| 619 |
@property |
| 620 |
def handle_token(self) -> dbus.String: |
| 621 |
""" |
| 622 |
Returns the dbus-ready handle_token, ready to be put into the options |
| 623 |
""" |
| 624 |
return dbus.String(self._handle_token, variant_level=1) |
| 625 |
|
| 626 |
def call(self, methodname: str, **kwargs) -> Optional[Response]: |
| 627 |
""" |
| 628 |
Semi-synchronously call method ``methodname`` on the interface given |
| 629 |
in the Request's constructor. The kwargs must be specified in the |
| 630 |
order the DBus method takes them but the handle_token is automatically |
| 631 |
filled in. |
| 632 |
|
| 633 |
>>> response = Request(connection, interface).call("Foo", bar="bar") |
| 634 |
>>> if response.response != 0: |
| 635 |
... print("some error occured") |
| 636 |
|
| 637 |
The DBus call itself is asynchronous (required for signals to work) |
| 638 |
but this method does not return until the Response is received, the |
| 639 |
Request is closed or an error occurs. If the Request is closed, the |
| 640 |
Response is None. |
| 641 |
|
| 642 |
If the "reply_handler" and "error_handler" keywords are present, those |
| 643 |
callbacks are called just like they would be as dbus.service.ProxyObject. |
| 644 |
""" |
| 645 |
assert not self.used |
| 646 |
self.used = True |
| 647 |
|
| 648 |
# Make sure options exists and has the handle_token set |
| 649 |
try: |
| 650 |
options = kwargs["options"] |
| 651 |
except KeyError: |
| 652 |
options = dbus.Dictionary({}, signature="sv") |
| 653 |
|
| 654 |
if "handle_token" not in options: |
| 655 |
options["handle_token"] = self.handle_token |
| 656 |
|
| 657 |
# Anything that takes longer than 5s needs to fail |
| 658 |
self._mainloop = GLib.MainLoop() |
| 659 |
GLib.timeout_add( |
| 660 |
DBUS_TIMEOUT * 10 if is_valgrind() else DBUS_TIMEOUT, self._mainloop.quit |
| 661 |
) |
| 662 |
|
| 663 |
method = getattr(self.interface, methodname) |
| 664 |
assert method |
| 665 |
|
| 666 |
reply_handler = kwargs.pop("reply_handler", None) |
| 667 |
error_handler = kwargs.pop("error_handler", None) |
| 668 |
|
| 669 |
# Handle the normal method reply which returns is the Request object |
| 670 |
# path. We don't exit the mainloop here, we're waiting for either the |
| 671 |
# Response signal on the Request itself or the Close() handling |
| 672 |
def reply_cb(handle): |
| 673 |
try: |
| 674 |
logger.debug(f"Reply to {methodname} with {self.handle}") |
| 675 |
assert handle == self.handle |
| 676 |
|
| 677 |
if reply_handler: |
| 678 |
reply_handler(handle) |
| 679 |
except Exception as e: |
| 680 |
self.error = e |
| 681 |
|
| 682 |
# Handle any exceptions during the actual method call (not the Request |
| 683 |
# handling itself). Can exit the mainloop if that happens |
| 684 |
def error_cb(error): |
| 685 |
try: |
| 686 |
logger.debug(f"Error after {methodname} with {error}") |
| 687 |
if error_handler: |
| 688 |
error_handler(error) |
| 689 |
self.error = error |
| 690 |
except Exception as e: |
| 691 |
self.error = e |
| 692 |
finally: |
| 693 |
if self._mainloop: |
| 694 |
self._mainloop.quit() |
| 695 |
|
| 696 |
# Method is invoked async, otherwise we can't mix and match signals |
| 697 |
# and other calls. It's still sync as seen by the caller in that we |
| 698 |
# have a mainloop that waits for us to finish though. |
| 699 |
method( |
| 700 |
*list(kwargs.values()), |
| 701 |
reply_handler=reply_cb, |
| 702 |
error_handler=error_cb, |
| 703 |
) |
| 704 |
|
| 705 |
self._mainloop.run() |
| 706 |
|
| 707 |
if self.error: |
| 708 |
raise self.error |
| 709 |
elif not self.closed and self.response is None: |
| 710 |
raise ResponseTimeout(f"Timed out waiting for response from {methodname}") |
| 711 |
|
| 712 |
return self.response |
| 713 |
|
| 714 |
|
| 715 |
class Session(Closable): |
| 716 |
""" |
| 717 |
Helper class for a Session created by a portal. This class takes care of |
| 718 |
subscribing to the `Closed` signals. A typical invocation is: |
| 719 |
|
| 720 |
>>> response = Request(connection, interface).call("CreateSession") |
| 721 |
>>> session = Session.from_response(response) |
| 722 |
# Now run the main loop and do other stuff |
| 723 |
# Check if the session was closed |
| 724 |
>>> if session.closed: |
| 725 |
... pass |
| 726 |
# or close the session explicitly |
| 727 |
>>> session.close() # to close the session or |
| 728 |
""" |
| 729 |
|
| 730 |
def __init__(self, bus: dbus.Bus, handle: str): |
| 731 |
assert handle |
| 732 |
super().__init__(bus, handle) |
| 733 |
|
| 734 |
self.handle = handle |
| 735 |
self.details = None |
| 736 |
# GLib makes assertions in callbacks impossible, so we wrap all |
| 737 |
# callbacks into a try: except and store the error on the request to |
| 738 |
# be raised later when we're back in the main context |
| 739 |
self.error = None |
| 740 |
self._closed_sig_received = False |
| 741 |
|
| 742 |
def cb_closed(details: ASV) -> None: |
| 743 |
try: |
| 744 |
logger.debug(f"Session.Closed received on {self.handle}") |
| 745 |
assert not self._closed_sig_received |
| 746 |
self._closed_sig_received = True |
| 747 |
self.details = details |
| 748 |
if self._mainloop: |
| 749 |
self._mainloop.quit() |
| 750 |
except Exception as e: |
| 751 |
self.error = e |
| 752 |
|
| 753 |
proxy = bus.get_object("org.freedesktop.portal.Desktop", handle) |
| 754 |
self.session_interface = dbus.Interface(proxy, "org.freedesktop.portal.Session") |
| 755 |
self.session_interface.connect_to_signal("Closed", cb_closed) |
| 756 |
|
| 757 |
@property |
| 758 |
def closed(self): |
| 759 |
""" |
| 760 |
Returns True if the session was closed by the backend |
| 761 |
""" |
| 762 |
return self._closed_sig_received or super().closed |
| 763 |
|
| 764 |
@classmethod |
| 765 |
def from_response(cls, bus: dbus.Bus, response: Response) -> "Session": |
| 766 |
return cls(bus, response.results["session_handle"]) |
| 767 |
|
| 768 |
|
| 769 |
class GDBusIfaceSignal: |
| 770 |
""" |
| 771 |
Helper class which represents a connected signal on a GDBusIface and can be |
| 772 |
used to disconnect from the signal. |
| 773 |
""" |
| 774 |
|
| 775 |
def __init__(self, signal_id: int, proxy: Gio.DBusProxy): |
| 776 |
self.signal_id = signal_id |
| 777 |
self.proxy = proxy |
| 778 |
|
| 779 |
def disconnect(self): |
| 780 |
""" |
| 781 |
Disconnects the signal |
| 782 |
""" |
| 783 |
self.proxy.disconnect(self.signal_id) |
| 784 |
|
| 785 |
|
| 786 |
class GDBusIface: |
| 787 |
""" |
| 788 |
Helper class for calling dbus interfaces with complex arguments. |
| 789 |
Usually you want to use python-dbus on the dbus_con fixture with |
| 790 |
get_portal_iface , get_mock_iface or get_iface. This is convenient but |
| 791 |
might not be sufficient for complex arguments or for asynchronously calling |
| 792 |
a method. |
| 793 |
""" |
| 794 |
|
| 795 |
def __init__(self, bus: str, obj: str, iface: str): |
| 796 |
""" |
| 797 |
Creates a GDBusIface for a specific bus, object and interface on the |
| 798 |
session bus. |
| 799 |
""" |
| 800 |
address = Gio.dbus_address_get_for_bus_sync(Gio.BusType.SESSION, None) |
| 801 |
session_bus = Gio.DBusConnection.new_for_address_sync( |
| 802 |
address, |
| 803 |
Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT |
| 804 |
| Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, |
| 805 |
None, |
| 806 |
None, |
| 807 |
) |
| 808 |
assert session_bus |
| 809 |
self._proxy = Gio.DBusProxy.new_sync( |
| 810 |
session_bus, |
| 811 |
Gio.DBusProxyFlags.NONE, |
| 812 |
None, |
| 813 |
bus, |
| 814 |
obj, |
| 815 |
iface, |
| 816 |
None, |
| 817 |
) |
| 818 |
|
| 819 |
def _call( |
| 820 |
self, method_name: str, args_variant: GLib.Variant, fds: List[int] = [] |
| 821 |
) -> GLib.Variant: |
| 822 |
""" |
| 823 |
Calls a method synchronously with the arguments passed in args_variant, |
| 824 |
passing the file descriptors specified in fds. |
| 825 |
Returns the result of the dbus call. |
| 826 |
""" |
| 827 |
fdlist = Gio.UnixFDList.new() |
| 828 |
for fd in fds: |
| 829 |
fdlist.append(fd) |
| 830 |
|
| 831 |
return self._proxy.call_with_unix_fd_list_sync( |
| 832 |
method_name, |
| 833 |
args_variant, |
| 834 |
0, |
| 835 |
-1, |
| 836 |
fdlist, |
| 837 |
None, |
| 838 |
) |
| 839 |
|
| 840 |
def _call_async( |
| 841 |
self, |
| 842 |
method_name: str, |
| 843 |
args_variant: GLib.Variant, |
| 844 |
fds: List[int] = [], |
| 845 |
cb: Optional[Callable[[GLib.Variant], None]] = None, |
| 846 |
) -> None: |
| 847 |
""" |
| 848 |
Calls a method asynchronously with the arguments passed in args_variant, |
| 849 |
passing the file descriptors specified in fds. |
| 850 |
Invokes the callback cb when the call finished. |
| 851 |
""" |
| 852 |
fdlist = Gio.UnixFDList.new() |
| 853 |
for fd in fds: |
| 854 |
fdlist.append(fd) |
| 855 |
|
| 856 |
def internal_cb(s, res, _): |
| 857 |
res = s.call_finish(res) |
| 858 |
if cb: |
| 859 |
cb(res) |
| 860 |
|
| 861 |
self._proxy.call_with_unix_fd_list( |
| 862 |
method_name, |
| 863 |
args_variant, |
| 864 |
0, |
| 865 |
-1, |
| 866 |
fdlist, |
| 867 |
None, |
| 868 |
internal_cb, |
| 869 |
None, |
| 870 |
) |
| 871 |
|
| 872 |
def connect_to_signal( |
| 873 |
self, name: str, cb: Callable[[GLib.Variant], None] |
| 874 |
) -> GDBusIfaceSignal: |
| 875 |
""" |
| 876 |
Connects to the dbus signal name to the callback cb. Returns an object |
| 877 |
representing the connection which can be used to disconnect it again. |
| 878 |
""" |
| 879 |
|
| 880 |
def internal_cb(proxy, sender_name, signal_name, parameters): |
| 881 |
if signal_name != name: |
| 882 |
return |
| 883 |
cb(parameters) |
| 884 |
|
| 885 |
signal_id = self._proxy.connect("g-signal", internal_cb) |
| 886 |
return GDBusIfaceSignal(signal_id, self._proxy) |
| 887 |
|
| 888 |
|
| 889 |
class FileAccessMode(Enum): |
| 890 |
READ_WRITE = "read-write" |
| 891 |
READ_ONLY = "read-only" |
| 892 |
HIDDEN = "hidden" |
| 893 |
|
| 894 |
|
| 895 |
class ExecutableMock(object): |
| 896 |
def __init__(self, executable: str, access_mode: FileAccessMode): |
| 897 |
self.executable = executable |
| 898 |
self.access_mode = access_mode |
| 899 |
|
| 900 |
def create(self, path: Path): |
| 901 |
self.path = path / self.executable |
| 902 |
self.path.write_bytes(self.get_executable()) |
| 903 |
self.path.chmod(0o755) |
| 904 |
|
| 905 |
def get_executable(self): |
| 906 |
return f"#!/usr/bin/env sh\necho {self.access_mode.value}".encode("utf8") |
| 907 |
|
| 908 |
|
| 909 |
class SessionPersistenceMode(IntEnum): |
| 910 |
NONE = 0 |
| 911 |
TRANSIENT = 1 |
| 912 |
PERSISTENT = 2 |