From 09e9fde0a248d9d8b11dc3aacd56382010666621 Mon Sep 17 00:00:00 2001 From: "Dennis K. Paulsen" Date: Tue, 8 Sep 2026 16:50:17 -0500 Subject: [PATCH] Fall back to InputCapture v1 CreateSession when version reports 0, fixing negotiation against xdg-desktop-portal-gnome 50 -- release 0.5.1 --- CHANGELOG.md | 33 ++++++ README.md | 2 +- docs/developers/verification.md | 30 ++++-- pyproject.toml | 2 +- src/libei/__init__.py | 2 +- src/libei/portal.py | 179 ++++++++++++++++++++++++-------- tests/test_inputcapture.py | 57 ++++++++-- 7 files changed, 239 insertions(+), 66 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18e7691..f4ee891 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,39 @@ All notable changes to python-libei are recorded here. The format follows ## [Unreleased] +## [0.5.1] - 2026-09-08 + +### Fixed + +- **`InputCaptureSession.negotiate()` now works against pre-v2 portals**, via + the deprecated v1 `CreateSession`. Only `CreateSession2` and `Start` are + version 2 additions to the interface -- `GetZones`, `SetPointerBarriers`, + `Enable`, `Disable`, `Release` and `ConnectToEIS` are all v1 originals -- so + just session creation forks and everything after negotiating is unchanged. + On v1 a single `CreateSession` carries `capabilities` and raises the consent + dialog itself; there is no `Start` to call. + + This turns out to matter on shipping systems, not just old ones: + **xdg-desktop-portal-gnome 50 reports InputCapture version 0** -- it + registers the complete impl interface (including `ConnectToEIS`, the + `Activated`/`Deactivated` signals and `SupportedCapabilities = 15`) and + simply never sets the `version` property, and the frontend derives its own + version from the impl's. Previously that raised + `PortalVersionError: InputCapture version 0 is too old for CreateSession2` + and there was no way through. Live-validated on Fedora 44 / GNOME Shell 50.0 + (xdg-desktop-portal 1.21.1): negotiation returns a real EIS fd and `zones()` + answers `(0, [(1920, 1080, 0, 0)])`. + + Note that such a portal's introspection XML advertises `CreateSession2` + anyway -- that XML is static and says nothing about what the frontend will + dispatch, which is why the `version` property is read first and believed. + Calling `CreateSession2` there fails with `UnknownMethod`. + + The one thing v1 cannot do is persist: `persist_mode` and `restore_token` + were added to `Start`, which does not exist. Passing either against a pre-v2 + portal now raises `PortalVersionError` explaining that, rather than being + silently ignored and handing back a `restore_token` of `None`. + ## [0.5.0] - 2026-09-08 ### Added diff --git a/README.md b/README.md index e61076d..afd2f29 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ and why, is in ## Status -Beta (`0.5.0`), published on [PyPI](https://pypi.org/project/python-libei/) +Beta (`0.5.1`), published on [PyPI](https://pypi.org/project/python-libei/) since `0.1.0`, and **the API is not frozen** — expect renames before 1.0. The injection path is exercised end to end against the real libraries by the diff --git a/docs/developers/verification.md b/docs/developers/verification.md index 7911411..71aadd7 100644 --- a/docs/developers/verification.md +++ b/docs/developers/verification.md @@ -1,6 +1,6 @@ # What has actually been verified -The package is beta (`0.5.0`) and the API is not frozen — expect renames +The package is beta (`0.5.1`) and the API is not frozen — expect renames before 1.0. This page is what that qualifier covers, concretely: which paths have been driven against real libraries, which have only ever been driven against fakes, and which libei versions the whole thing has met. @@ -36,16 +36,24 @@ By hand: relative pointer, keyboard, absolute pointer, in that order, which is the device race `ei`-side callers must handle; and `Session.Close()` was exercised. No input was injected — emulation is `libei.ei`'s job. -- **`libei.portal.InputCaptureSession` (added 0.5.0) has never been run - against a real portal, unlike everything else on this list** — and unlike - the rest of `libei.portal`, its consent dialog is not the whole reason why. - Approving it exclusively diverts the approving human's own pointer, - keyboard or touch input away from their desktop for as long as the capture - stays active, so verifying it needs someone to deliberately accept that, - not merely click through a permission prompt. Designed against the shipped - D-Bus spec (`/usr/share/dbus-1/interfaces/org.freedesktop.portal. - InputCapture.xml`) and unit-tested against a fake connection reproducing - its documented shapes (`tests/test_inputcapture.py`) instead. +- **`libei.portal.InputCaptureSession` (added 0.5.0), negotiation half only**, + 2026-09-08, against a real Fedora 44 / GNOME Shell 50.0 session + (xdg-desktop-portal 1.21.1). That portal reports InputCapture **version 0**, + so this exercised the **v1 `CreateSession` path**: consent dialog approved, + a real EIS fd returned, `zones()` answering `(0, [(1920, 1080, 0, 0)])`, and + `Session.Close()` exercised. The v2 `CreateSession2` -> `Start` path has + still never been run live. + + **The capture half remains unverified**, and unlike the rest of + `libei.portal` its consent dialog is not the whole reason why. Approving a + capture exclusively diverts the approving human's own pointer, keyboard or + touch input away from their desktop for as long as it stays active, so + verifying `set_pointer_barriers()` / `enable()` / `wait_for_activation()` + needs someone to deliberately accept that, not merely click through a + permission prompt. Those were designed against the shipped D-Bus spec + (`/usr/share/dbus-1/interfaces/org.freedesktop.portal.InputCapture.xml`) + and unit-tested against a fake connection reproducing its documented shapes + (`tests/test_inputcapture.py`) instead. ## Which libei versions this has met diff --git a/pyproject.toml b/pyproject.toml index b1e58b9..a71a1bc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "python-libei" -version = "0.5.0" +version = "0.5.1" description = "Inject and receive input on Wayland from Python: ctypes bindings for libei, libeis and liboeffis" readme = "README.md" license = "MIT" diff --git a/src/libei/__init__.py b/src/libei/__init__.py index 83d4d83..97aecb9 100644 --- a/src/libei/__init__.py +++ b/src/libei/__init__.py @@ -31,6 +31,6 @@ Beta: the API is not frozen. """ -__version__ = "0.5.0" +__version__ = "0.5.1" __all__ = ["__version__"] diff --git a/src/libei/portal.py b/src/libei/portal.py index 616521b..e40ca19 100644 --- a/src/libei/portal.py +++ b/src/libei/portal.py @@ -926,6 +926,53 @@ def _input_capture_version( return int(version) +def _create_input_capture_session_v1( + connection: Any, + Gio: Any, + GLib: Any, + busname: str, + types: int, + timeout: float, +) -> str: + """Create an InputCapture session on a portal that predates v2. + + v1 has no ``Start`` at all -- that method, like ``CreateSession2``, was + added in version 2. Here ``CreateSession`` itself carries + ``capabilities`` and raises the consent dialog, and the session is ready + for ``GetZones`` / ``SetPointerBarriers`` / ``Enable`` the moment its + ``Response`` arrives. ``ConnectToEIS`` is a v1 original, so the rest of + this class works against such a portal unchanged. + + Returns the session handle. ``persist_mode`` and ``restore_token`` have + no v1 equivalent -- both are documented as version 2 additions to + ``Start``, which does not exist here -- so the caller must reject them + before getting this far rather than have them silently ignored. + """ + code, results = _request( + connection, + Gio, + GLib, + busname, + _INPUT_CAPTURE, + "CreateSession", + "(sa{sv})", + ("",), + { + "session_handle_token": GLib.Variant("s", uuid.uuid4().hex), + "capabilities": GLib.Variant("u", int(types)), + }, + timeout, + ) + if code != 0: + raise PortalDeniedError( + "CreateSession", "the user declined the input-capture consent dialog" + ) + session_handle = results.get("session_handle") + if not isinstance(session_handle, str): + raise PortalError("CreateSession returned no session_handle") + return session_handle + + def _wait_for_signal( connection: Any, Gio: Any, @@ -1392,11 +1439,18 @@ def negotiate( Blocks until ``CreateSession2`` -> ``Start`` -> ``ConnectToEIS`` resolves, prompting the user for consent along the way unless ``restore_token`` lets the portal skip that. Raises - :class:`PortalVersionError` if the compositor's InputCapture portal - predates ``CreateSession2`` (needs v2+ -- this module never speaks - the deprecated v1 ``CreateSession``), :class:`PortalDeniedError` if - ``Start`` is declined, and :class:`PortalTimeoutError` if any one - round trip exceeds ``timeout`` seconds. + :class:`PortalDeniedError` if consent is declined, and + :class:`PortalTimeoutError` if any one round trip exceeds ``timeout`` + seconds. + + A portal older than v2 has neither ``CreateSession2`` nor ``Start``, + and is negotiated through the deprecated v1 ``CreateSession`` + instead -- one call that carries ``capabilities`` and raises the + consent dialog itself. Everything after negotiation is identical; + ``ConnectToEIS`` is a v1 original. The one thing v1 cannot do is + persist: ``persist_mode`` and ``restore_token`` were added to + ``Start``, so passing either against such a portal raises + :class:`PortalVersionError` rather than being quietly ignored. Returns before anything is actually captured: :meth:`set_pointer_barriers` and :meth:`enable` still have to be called, and even then nothing @@ -1435,62 +1489,95 @@ def negotiate( raise PortalError(f"cannot reach the session bus: {exc}") from exc version = _input_capture_version(connection, Gio, GLib, busname, timeout) - if version < _MIN_INPUT_CAPTURE_VERSION: + # A version below 2 is not a portal to give up on -- it is a portal + # that speaks the older half of the same interface. Only + # `CreateSession2` and `Start` are version 2 additions; `GetZones`, + # `SetPointerBarriers`, `Enable`, `Disable`, `Release` and, crucially, + # `ConnectToEIS` are all v1 originals, so everything this class does + # after negotiation works either way and only session creation forks. + # + # This is not hypothetical. xdg-desktop-portal-gnome 50 reports + # version 0 -- it registers the full impl interface and never sets the + # property -- and calling `CreateSession2` against it fails with + # `UnknownMethod`, while v1 `CreateSession` is dispatched normally. + # Note that its introspection XML advertises `CreateSession2` anyway: + # that XML is static, so it says nothing about what the frontend will + # actually dispatch. The `version` property is the only usable signal, + # which is why it is read first and believed. + legacy = version < _MIN_INPUT_CAPTURE_VERSION + + if legacy and (persist_mode != PersistMode.NONE or restore_token is not None): raise PortalVersionError( - f"InputCapture version {version} is too old for " - f"CreateSession2 (need {_MIN_INPUT_CAPTURE_VERSION}+)" + f"InputCapture version {version} has no Start method, and " + f"persist_mode/restore_token are version " + f"{_MIN_INPUT_CAPTURE_VERSION} additions to it -- this portal " + f"cannot persist a session. Retry with persist_mode=NONE and " + f"no restore_token to negotiate a one-shot session." ) if capabilities == DeviceType.ALL_DEVICES: types = _ALL_DEVICE_TYPES else: types = capabilities - reply = _call_sync( - connection, - Gio, - GLib, - busname, - _OBJECT_PATH, - _INPUT_CAPTURE, - "CreateSession2", - GLib.Variant( - "(a{sv})", - ({"session_handle_token": GLib.Variant("s", uuid.uuid4().hex)},), - ), - None, - int(timeout * 1000), - ) - (results,) = reply.unpack() - session_handle = results.get("session_handle") - if not isinstance(session_handle, str): - raise PortalError("CreateSession2 returned no session_handle") - # Past this point a session exists inside xdg-desktop-portal, and - # nothing else can close it -- see RemoteDesktopSession.negotiate's - # identical reasoning, which this mirrors line for line. - try: - options: dict[str, Any] = {"capabilities": GLib.Variant("u", int(types))} - if persist_mode != PersistMode.NONE: - options["persist_mode"] = GLib.Variant("u", int(persist_mode)) - if restore_token is not None: - options["restore_token"] = GLib.Variant("s", restore_token) - code, start_results = _request( + if legacy: + session_handle = _create_input_capture_session_v1( + connection, Gio, GLib, busname, int(types), timeout + ) + else: + reply = _call_sync( connection, Gio, GLib, busname, + _OBJECT_PATH, _INPUT_CAPTURE, - "Start", - "(osa{sv})", - (session_handle, ""), - options, - timeout, + "CreateSession2", + GLib.Variant( + "(a{sv})", + ({"session_handle_token": GLib.Variant("s", uuid.uuid4().hex)},), + ), + None, + int(timeout * 1000), ) - if code != 0: - raise PortalDeniedError( - "Start", "the user declined the input-capture consent dialog" + (results,) = reply.unpack() + session_handle = results.get("session_handle") + if not isinstance(session_handle, str): + raise PortalError("CreateSession2 returned no session_handle") + + # Past this point a session exists inside xdg-desktop-portal, and + # nothing else can close it -- see RemoteDesktopSession.negotiate's + # identical reasoning, which this mirrors line for line. + try: + # v1 asked for consent and capabilities in CreateSession itself, + # and has no Start to call; it can therefore never issue a + # restore token either. + new_restore_token = None + if not legacy: + options: dict[str, Any] = { + "capabilities": GLib.Variant("u", int(types)) + } + if persist_mode != PersistMode.NONE: + options["persist_mode"] = GLib.Variant("u", int(persist_mode)) + if restore_token is not None: + options["restore_token"] = GLib.Variant("s", restore_token) + code, start_results = _request( + connection, + Gio, + GLib, + busname, + _INPUT_CAPTURE, + "Start", + "(osa{sv})", + (session_handle, ""), + options, + timeout, ) - new_restore_token = start_results.get("restore_token") + if code != 0: + raise PortalDeniedError( + "Start", "the user declined the input-capture consent dialog" + ) + new_restore_token = start_results.get("restore_token") eis_fd = _call_for_fd( connection, diff --git a/tests/test_inputcapture.py b/tests/test_inputcapture.py index a2c0c7b..0c9c1aa 100644 --- a/tests/test_inputcapture.py +++ b/tests/test_inputcapture.py @@ -46,8 +46,8 @@ class FakeInputCaptureConnection: Three call shapes, told apart by method name: `Get` (the version property), `CreateSession2`/`Enable`/`Disable`/`Release` (plain calls, - no Request/Response), and `Start`/`GetZones`/`SetPointerBarriers` - (Request-shaped, exactly like RemoteDesktop's own calls -- the + no Request/Response), and `CreateSession` (v1)/`Start`/`GetZones`/ + `SetPointerBarriers` (Request-shaped, exactly like RemoteDesktop's -- the `handle_token` lives in whichever positional argument is a dict, found by type rather than by a fixed index, since SetPointerBarriers's options argument is not last). @@ -78,6 +78,9 @@ def __init__( self.session_handle = session_handle self.responses = responses or { "Start": (0, {"capabilities": 3}), + # v1 CreateSession is Request-shaped too, and answers with the + # handle CreateSession2 returns directly. + "CreateSession": (0, {"session_handle": session_handle}), "GetZones": (0, {"zone_set": 1, "zones": [(1920, 1080, 0, 0)]}), "SetPointerBarriers": (0, {"failed_barriers": []}), } @@ -209,17 +212,59 @@ def test_successful_negotiation_calls_every_step_in_order() -> None: assert session.session_handle == connection.session_handle -def test_old_input_capture_version_is_refused() -> None: +@pytest.mark.parametrize("version", [1, 0]) +def test_pre_v2_portal_negotiates_through_v1_create_session(version: int) -> None: + """v1 has no CreateSession2 and no Start -- one call does both jobs. + + version 0 takes the same path: xdg-desktop-portal-gnome 50 registers the + whole impl interface and never sets the property, so 0 reaches us from a + portal that speaks v1 perfectly well. + """ + connection = FakeInputCaptureConnection(version=version) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + assert [c[0] for c in connection.calls] == [ + "Get", + "CreateSession", + "ConnectToEIS", + ] + assert session.session_handle == connection.session_handle + assert session.eis_fd == connection.fd_responses["ConnectToEIS"] + # v1 can never issue one: restore_token is a v2 addition to Start. + assert session.restore_token is None + # capabilities ride on CreateSession here, not on Start. + options = next(v for v in connection.calls[1][1] if isinstance(v, dict)) + assert options["capabilities"].value == int(portal._ALL_DEVICE_TYPES) + + +def test_v1_portal_refuses_persistence_rather_than_ignoring_it() -> None: + """persist_mode/restore_token are v2 additions to a method v1 lacks.""" connection = FakeInputCaptureConnection(version=1) with install_fake_gi(connection): - with pytest.raises(portal.PortalVersionError): - portal.InputCaptureSession.negotiate(connection=connection) - # Refused before ever calling CreateSession2. + with pytest.raises(portal.PortalVersionError, match="cannot persist"): + portal.InputCaptureSession.negotiate( + connection=connection, persist_mode=portal.PersistMode.UNTIL_REVOKED + ) + # Refused before creating anything that would need cleaning up. assert connection.calls == [ ("Get", ("org.freedesktop.portal.InputCapture", "version")) ] +def test_declined_v1_create_session_raises_denied_error() -> None: + """v1 raises its consent dialog in CreateSession, so that is the step.""" + connection = FakeInputCaptureConnection( + version=1, + responses={"CreateSession": (1, {})}, # 1 == user cancelled + ) + with install_fake_gi(connection): + with pytest.raises(portal.PortalDeniedError) as excinfo: + portal.InputCaptureSession.negotiate(connection=connection) + assert excinfo.value.step == "CreateSession" + # No session handle came back, so there is nothing to Close. + assert [c[0] for c in connection.calls] == ["Get", "CreateSession"] + + def test_a_missing_session_handle_raises_portal_error() -> None: class NoHandleConnection(FakeInputCaptureConnection): def call_sync(self, *args: Any, **kwargs: Any) -> FakeReply: