python-libei 0.8.1__tar.gz → 0.8.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. {python_libei-0.8.1/src/python_libei.egg-info → python_libei-0.8.3}/PKG-INFO +35 -2
  2. {python_libei-0.8.1 → python_libei-0.8.3}/README.md +34 -1
  3. {python_libei-0.8.1 → python_libei-0.8.3}/pyproject.toml +1 -1
  4. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/__init__.py +1 -1
  5. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/ei.py +50 -4
  6. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/portal.py +147 -35
  7. {python_libei-0.8.1 → python_libei-0.8.3/src/python_libei.egg-info}/PKG-INFO +35 -2
  8. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_inputcapture.py +2 -0
  9. python_libei-0.8.3/tests/test_integration_lifetime.py +94 -0
  10. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_integration_socketpair.py +254 -10
  11. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_portal.py +195 -4
  12. python_libei-0.8.1/tests/test_integration_lifetime.py +0 -49
  13. {python_libei-0.8.1 → python_libei-0.8.3}/LICENSE +0 -0
  14. {python_libei-0.8.1 → python_libei-0.8.3}/setup.cfg +0 -0
  15. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/_capi/__init__.py +0 -0
  16. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/_capi/libei.py +0 -0
  17. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/_capi/libeis.py +0 -0
  18. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/_capi/liboeffis.py +0 -0
  19. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/_capi/loader.py +0 -0
  20. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/_cobject.py +0 -0
  21. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/eis.py +0 -0
  22. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/oeffis.py +0 -0
  23. {python_libei-0.8.1 → python_libei-0.8.3}/src/libei/py.typed +0 -0
  24. {python_libei-0.8.1 → python_libei-0.8.3}/src/python_libei.egg-info/SOURCES.txt +0 -0
  25. {python_libei-0.8.1 → python_libei-0.8.3}/src/python_libei.egg-info/dependency_links.txt +0 -0
  26. {python_libei-0.8.1 → python_libei-0.8.3}/src/python_libei.egg-info/requires.txt +0 -0
  27. {python_libei-0.8.1 → python_libei-0.8.3}/src/python_libei.egg-info/top_level.txt +0 -0
  28. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_abi.py +0 -0
  29. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_cobject.py +0 -0
  30. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_documentation_shape.py +0 -0
  31. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_documented_examples.py +0 -0
  32. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_ei_objects.py +0 -0
  33. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_eis_objects.py +0 -0
  34. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_event_accessors.py +0 -0
  35. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_integration_extras.py +0 -0
  36. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_integration_frame.py +0 -0
  37. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_loader.py +0 -0
  38. {python_libei-0.8.1 → python_libei-0.8.3}/tests/test_oeffis.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-libei
3
- Version: 0.8.1
3
+ Version: 0.8.3
4
4
  Summary: Inject, receive and capture input on Wayland from Python: ctypes bindings for libei, libeis and liboeffis, plus the RemoteDesktop and InputCapture portals
5
5
  Author: Dennis K. Paulsen
6
6
  License-Expression: MIT
@@ -175,7 +175,7 @@ and why, is in
175
175
 
176
176
  ## Status
177
177
 
178
- Beta (`0.8.1`), published on [PyPI](https://pypi.org/project/python-libei/)
178
+ Beta (`0.8.3`), published on [PyPI](https://pypi.org/project/python-libei/)
179
179
  since `0.1.0`, and **the API is not frozen** — expect renames before 1.0.
180
180
 
181
181
  The injection path is exercised end to end against the real libraries by the
@@ -190,6 +190,39 @@ asserted.
190
190
  Exactly what was run, when, and against which versions:
191
191
  [docs/developers/verification.md](docs/developers/verification.md).
192
192
 
193
+ ### What the API raises
194
+
195
+ Three independent exception families, by the layer that raises them, so a
196
+ caller can catch at the granularity they need — plus one that sits before
197
+ all of them:
198
+
199
+ - **`LibraryNotFoundError`** (a `RuntimeError`, exported by `libei.ei`,
200
+ `libei.eis` and `libei.oeffis` alike) — the native library could not be
201
+ loaded. Importing never raises it; the first call that needs the library
202
+ does, and every later call after that. `is_available()` asks the same
203
+ question without raising.
204
+ - **`libei.ei.Error`** (and `libei.eis.Error`) — the native library reported
205
+ a failure through its own return codes. One base class per module;
206
+ subclasses are added as distinct failure modes earn them rather than up
207
+ front.
208
+ - **`libei.oeffis.DisconnectedError`**, with `SessionClosedError` under it —
209
+ the EIS connection is gone. `dispatch()` raises the subclass when the
210
+ portal closed the session and the base class when the connection dropped
211
+ or the fd could not be obtained; `eis_fd` raises the base class whenever
212
+ no connection is up yet, so it is `dispatch()` that tells the two apart.
213
+ - **`libei.portal.PortalError`**, with `PortalVersionError`,
214
+ `PortalTimeoutError`, `PortalDeniedError`, `PortalProtocolError` and
215
+ `PortalSessionClosedError` under it — each a *different* thing the portal
216
+ round trip can do, kept separate on purpose: a timeout (no answer), a
217
+ denial (answered no), a protocol surprise (answered malformed) and a
218
+ version mismatch are not interchangeable, and collapsing them would make a
219
+ caller guess. These are the ones worth catching individually.
220
+
221
+ Argument mistakes that are the caller's and not the desktop's —
222
+ no capabilities, the wrong value kind — raise the stock `ValueError` /
223
+ `TypeError`, never a library exception. The hierarchy is stable in shape; as
224
+ with the rest of the API, names may still change before 1.0.
225
+
193
226
  ## Alternatives
194
227
 
195
228
  | Instead of this | Why you might |
@@ -135,7 +135,7 @@ and why, is in
135
135
 
136
136
  ## Status
137
137
 
138
- Beta (`0.8.1`), published on [PyPI](https://pypi.org/project/python-libei/)
138
+ Beta (`0.8.3`), published on [PyPI](https://pypi.org/project/python-libei/)
139
139
  since `0.1.0`, and **the API is not frozen** — expect renames before 1.0.
140
140
 
141
141
  The injection path is exercised end to end against the real libraries by the
@@ -150,6 +150,39 @@ asserted.
150
150
  Exactly what was run, when, and against which versions:
151
151
  [docs/developers/verification.md](docs/developers/verification.md).
152
152
 
153
+ ### What the API raises
154
+
155
+ Three independent exception families, by the layer that raises them, so a
156
+ caller can catch at the granularity they need — plus one that sits before
157
+ all of them:
158
+
159
+ - **`LibraryNotFoundError`** (a `RuntimeError`, exported by `libei.ei`,
160
+ `libei.eis` and `libei.oeffis` alike) — the native library could not be
161
+ loaded. Importing never raises it; the first call that needs the library
162
+ does, and every later call after that. `is_available()` asks the same
163
+ question without raising.
164
+ - **`libei.ei.Error`** (and `libei.eis.Error`) — the native library reported
165
+ a failure through its own return codes. One base class per module;
166
+ subclasses are added as distinct failure modes earn them rather than up
167
+ front.
168
+ - **`libei.oeffis.DisconnectedError`**, with `SessionClosedError` under it —
169
+ the EIS connection is gone. `dispatch()` raises the subclass when the
170
+ portal closed the session and the base class when the connection dropped
171
+ or the fd could not be obtained; `eis_fd` raises the base class whenever
172
+ no connection is up yet, so it is `dispatch()` that tells the two apart.
173
+ - **`libei.portal.PortalError`**, with `PortalVersionError`,
174
+ `PortalTimeoutError`, `PortalDeniedError`, `PortalProtocolError` and
175
+ `PortalSessionClosedError` under it — each a *different* thing the portal
176
+ round trip can do, kept separate on purpose: a timeout (no answer), a
177
+ denial (answered no), a protocol surprise (answered malformed) and a
178
+ version mismatch are not interchangeable, and collapsing them would make a
179
+ caller guess. These are the ones worth catching individually.
180
+
181
+ Argument mistakes that are the caller's and not the desktop's —
182
+ no capabilities, the wrong value kind — raise the stock `ValueError` /
183
+ `TypeError`, never a library exception. The hierarchy is stable in shape; as
184
+ with the rest of the API, names may still change before 1.0.
185
+
153
186
  ## Alternatives
154
187
 
155
188
  | Instead of this | Why you might |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-libei"
7
- version = "0.8.1"
7
+ version = "0.8.3"
8
8
  description = "Inject, receive and capture input on Wayland from Python: ctypes bindings for libei, libeis and liboeffis, plus the RemoteDesktop and InputCapture portals"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -31,6 +31,6 @@ the full breakdown, including which features need which libei version.
31
31
  Beta: the API is not frozen.
32
32
  """
33
33
 
34
- __version__ = "0.8.1"
34
+ __version__ = "0.8.3"
35
35
 
36
36
  __all__ = ["__version__"]
@@ -1081,6 +1081,10 @@ class Context(CObject):
1081
1081
  """
1082
1082
  super().__init__(pointer, _adopt=_adopt)
1083
1083
  self._name: str | None = None
1084
+ # Whether set_fd()/set_socket() has run -- attempted, not
1085
+ # succeeded; see _refuse_a_second_backend() for why those are the
1086
+ # same thing here.
1087
+ self._backend_configured = False
1084
1088
  _capi.libei.log_set_handler(self, _log_handler)
1085
1089
  _capi.libei.log_set_priority(self, _LogPriority.DEBUG)
1086
1090
 
@@ -1145,20 +1149,53 @@ class Context(CObject):
1145
1149
  """The context's current time, in microseconds."""
1146
1150
  return _capi.libei.now(self)
1147
1151
 
1152
+ def _refuse_a_second_backend(self) -> None:
1153
+ """Raise for a transport setup on a context that already had one.
1154
+
1155
+ Letting the call through instead is not an error return: both
1156
+ ``ei_setup_backend_fd()`` and ``ei_setup_backend_socket()`` open
1157
+ on ``assert(!ei->backend)``, which aborts the whole process
1158
+ (measured: SIGABRT on 1.6.0). And each installs its backend
1159
+ object *before* anything that can fail, so a context whose setup
1160
+ failed is just as spent as one whose setup succeeded -- which is
1161
+ why the flag this reads records the attempt, not the outcome.
1162
+ """
1163
+ if self._backend_configured:
1164
+ raise RuntimeError(
1165
+ f"this {type(self).__name__} already has a transport, and a "
1166
+ "failed setup attempt also counts -- libei's setup functions "
1167
+ "abort the process on a second call rather than returning an "
1168
+ "error; create a new context instead"
1169
+ )
1170
+
1148
1171
  def set_fd(self: _ContextT, fd: IO[bytes] | int) -> _ContextT:
1149
1172
  """Use an already-connected socket as the transport.
1150
1173
 
1151
- libei takes ownership of a raw int fd and closes it itself; a file
1152
- object is duplicated first, so the caller's own object stays valid.
1174
+ libei takes ownership of a raw int fd and closes it itself --
1175
+ whether setup succeeds or fails; a file object is duplicated
1176
+ first, so the caller's own object stays valid.
1177
+
1178
+ Once per context, counting :meth:`set_socket` and counting failed
1179
+ attempts: a second call raises ``RuntimeError`` here rather than
1180
+ reaching C, where it is an assertion failure that aborts the
1181
+ process. The refused fd is untouched and stays the caller's.
1153
1182
  """
1183
+ self._refuse_a_second_backend()
1154
1184
  # ei_setup_backend_fd() takes ownership of the fd and will close it
1155
- # itself. A raw int is assumed to already be one the caller is
1156
- # handing off (matching what eis.Eis.add_client()/oeffis.eis_fd
1185
+ # itself -- on its failure path too: the fd goes straight into a
1186
+ # source whose destroy closes it, and failing drops that source
1187
+ # (libei-fd.c -> ei_set_socket() -> source_unref(), read on 1.6.0).
1188
+ # So no close here on error, which would double-close a possibly
1189
+ # reused number. A raw int is assumed to already be one the caller
1190
+ # is handing off (matching what eis.Eis.add_client()/oeffis.eis_fd
1157
1191
  # return); a file object still thinks it owns its own fd and would
1158
1192
  # close it again later -- possibly a *different*, since-reused fd
1159
1193
  # number by then -- so duplicate it rather than handing over the
1160
1194
  # original.
1161
1195
  raw_fd = fd if isinstance(fd, int) else os.dup(fd.fileno())
1196
+ # Spent on the attempt: the C call installs its backend object
1197
+ # before anything that can fail.
1198
+ self._backend_configured = True
1162
1199
  err = _capi.libei.setup_backend_fd(self, raw_fd)
1163
1200
  if err < 0:
1164
1201
  raise Error(os.strerror(-err), -err)
@@ -1169,8 +1206,17 @@ class Context(CObject):
1169
1206
 
1170
1207
  ``None`` uses ``$LIBEI_SOCKET``; a relative path is resolved
1171
1208
  against ``$XDG_RUNTIME_DIR``.
1209
+
1210
+ Once per context, counting :meth:`set_fd` and counting failed
1211
+ attempts -- see :meth:`set_fd`.
1172
1212
  """
1173
1213
  encoded = os.fspath(path).encode("utf-8") if path else None
1214
+ self._refuse_a_second_backend()
1215
+ # Spent on the attempt: the backend object is installed before any
1216
+ # of the failure returns (no $LIBEI_SOCKET, no $XDG_RUNTIME_DIR, a
1217
+ # failed connect), so even a context that never connected cannot
1218
+ # try again.
1219
+ self._backend_configured = True
1174
1220
  err = _capi.libei.setup_backend_socket(self, encoded)
1175
1221
  if err < 0:
1176
1222
  raise Error(os.strerror(-err), -err)
@@ -215,6 +215,15 @@ class PortalProtocolError(PortalError):
215
215
  ``detail`` phrase, since the default shape message above is specific
216
216
  to the session signals. ``step`` is then the method name, matching the
217
217
  sibling errors raised from the same call.
218
+
219
+ :func:`_call_for_fd` -- both portals' ``ConnectToEIS``, whose reply is
220
+ an *index* into a separate out fd list -- raises it for
221
+ the three ways that pair can disagree: no fd list attached at all
222
+ (the out list is nullable), an index outside the list, and the dup
223
+ ``g_unix_fd_list_get()`` does failing on fd exhaustion. ``payload`` is
224
+ the index in each case. Those used to reach the caller as an
225
+ ``AttributeError``, a silent ``-1`` fd, and a raw ``GLib.Error``
226
+ respectively -- none of them catchable as a ``PortalError``.
218
227
  """
219
228
 
220
229
  def __init__(self, step: str, payload: object, detail: str | None = None) -> None:
@@ -671,6 +680,27 @@ def _call_for_fd(
671
680
  wait on and nothing here beyond the call itself -- but it is a call to
672
681
  the same portal that just made the caller wait on a consent dialog, so
673
682
  it is bounded by the same ``timeout`` rather than by GIO's default.
683
+
684
+ The reply carries only an *index* into a separate out fd list, and both
685
+ halves have to be checked before the index is used, because
686
+ `g_unix_fd_list_get()` will not check them for us:
687
+
688
+ * The out fd list is **nullable** -- ``call_with_unix_fd_list_sync()``
689
+ is specified to hand back ``NULL`` for it, so a well-formed ``(h)``
690
+ reply with no fds attached arrives here as ``None``. Dereferencing
691
+ that raised ``AttributeError`` at the caller, outside every
692
+ ``except PortalError``.
693
+ * A bad index is a **programmer error**, not a runtime failure:
694
+ ``g_unix_fd_list_get()`` asserts ``index >= 0 && index < nfd``,
695
+ logs ``GLib-GIO-CRITICAL`` and **returns -1 without raising and
696
+ without setting a GError** (measured on GLib 2.90.1). So an
697
+ out-of-range index cannot be caught by an ``except GLib.Error``; the
698
+ -1 just flows out as the EIS fd. Gio-2.0.gir says as much and names
699
+ the two fixes: ``lookup()``, which is GLib 2.90+ only, or a bounds
700
+ check against ``get_length()`` -- the portable one, used below.
701
+
702
+ The one real ``GLib.Error`` from ``get()`` is the dup itself failing on
703
+ an fd the list does hold, i.e. EMFILE/ENFILE.
674
704
  """
675
705
  try:
676
706
  reply, fd_list = connection.call_with_unix_fd_list_sync(
@@ -690,7 +720,82 @@ def _call_for_fd(
690
720
  raise PortalTimeoutError(method, timeout) from exc
691
721
  raise PortalError(f"{method} failed on the D-Bus: {exc}") from exc
692
722
  (handle_index,) = reply.unpack()
693
- return fd_list.get(handle_index)
723
+ # Each of the three checks below turns something that used to escape a
724
+ # caller's `except PortalError` -- an AttributeError, a silent -1, a raw
725
+ # GLib.Error -- into the same typed protocol error _request() raises for a
726
+ # malformed Response. See this function's docstring for the GLib contract
727
+ # they are reading.
728
+ if fd_list is None:
729
+ raise PortalProtocolError(
730
+ method,
731
+ handle_index,
732
+ "it returned an fd index but attached no fd list to the reply",
733
+ )
734
+ length = fd_list.get_length()
735
+ if handle_index < 0 or handle_index >= length:
736
+ raise PortalProtocolError(
737
+ method,
738
+ handle_index,
739
+ "the fd index it returned is out of range for the reply's fd list "
740
+ f"(index {handle_index}, {length} fd(s) attached)",
741
+ )
742
+ try:
743
+ fd = fd_list.get(handle_index)
744
+ except _glib_error(GLib) as exc:
745
+ # The index is in range, so this is not a lookup failure: the only
746
+ # thing left for g_unix_fd_list_get() to fail at is the dup() it does
747
+ # to hand back an owned fd.
748
+ raise PortalProtocolError(
749
+ method,
750
+ handle_index,
751
+ "duplicating the fd it returned failed -- this process is out of "
752
+ f"file descriptors ({exc})",
753
+ ) from exc
754
+ if fd < 0:
755
+ # Unreachable via the bounds check above, which is the only documented
756
+ # way to get the -1 sentinel; kept so a future GLib that returns it for
757
+ # some other reason surfaces as a typed error rather than as a negative
758
+ # fd handed to ei.Sender.create_for_fd(), which does not check for one.
759
+ raise PortalProtocolError(
760
+ method,
761
+ handle_index,
762
+ f"its fd list returned no usable fd for index {handle_index} (got {fd})",
763
+ )
764
+ return fd
765
+
766
+
767
+ def _portal_version(reply: Any, interface: str) -> int:
768
+ """The ``version`` property out of a `Properties.Get` reply, as an int.
769
+
770
+ `_call_sync` is given no ``reply_type``, here as everywhere else in this
771
+ module, so GDBus validates nothing about the shape of what comes back --
772
+ which is why every other reply-consuming site checks the unpacked value
773
+ before trusting it. These two did not: a reply that unpacked to anything
774
+ but a one-element tuple raised `ValueError`, and a ``version`` that was
775
+ not a number raised `TypeError`, both bare built-ins escaping the
776
+ `except PortalError` that `docs/troubleshooting.md` promises covers the
777
+ negotiation.
778
+ """
779
+ unpacked = reply.unpack()
780
+ try:
781
+ (version,) = unpacked
782
+ except (ValueError, TypeError) as exc:
783
+ raise PortalProtocolError(
784
+ "Get",
785
+ unpacked,
786
+ f"{interface}'s version property is specified as a single "
787
+ f"value, and this reply is not that shape",
788
+ ) from exc
789
+ # bool before int, because bool *is* an int: a True would otherwise read
790
+ # as version 1 and be refused as "too old", blaming the portal's version
791
+ # for a reply that was nonsense.
792
+ if isinstance(version, bool) or not isinstance(version, int):
793
+ raise PortalProtocolError(
794
+ "Get",
795
+ unpacked,
796
+ f"{interface} reported a non-numeric version {version!r}",
797
+ )
798
+ return version
694
799
 
695
800
 
696
801
  def _remote_desktop_version(
@@ -709,8 +814,7 @@ def _remote_desktop_version(
709
814
  None,
710
815
  int(timeout * 1000),
711
816
  )
712
- (version,) = reply.unpack()
713
- return int(version)
817
+ return _portal_version(reply, _REMOTE_DESKTOP)
714
818
 
715
819
 
716
820
  class RemoteDesktopSession:
@@ -1092,8 +1196,7 @@ def _input_capture_version(
1092
1196
  None,
1093
1197
  int(timeout * 1000),
1094
1198
  )
1095
- (version,) = reply.unpack()
1096
- return int(version)
1199
+ return _portal_version(reply, _INPUT_CAPTURE)
1097
1200
 
1098
1201
 
1099
1202
  def _create_input_capture_session_v1(
@@ -1388,35 +1491,44 @@ def _wait_for_signal(
1388
1491
  loop.quit()
1389
1492
  return False
1390
1493
 
1391
- subscription = connection.signal_subscribe(
1392
- busname,
1393
- interface,
1394
- signal,
1395
- _OBJECT_PATH,
1396
- None,
1397
- Gio.DBusSignalFlags.NONE,
1398
- on_signal,
1399
- None,
1400
- )
1401
- closed_subscription = connection.signal_subscribe(
1402
- busname,
1403
- _SESSION_INTERFACE,
1404
- "Closed",
1405
- session_handle,
1406
- None,
1407
- Gio.DBusSignalFlags.NONE,
1408
- on_closed,
1409
- None,
1410
- )
1411
- logger.debug(
1412
- "waiting up to %s for %s.%s on %s for session %s",
1413
- "forever" if timeout is None else f"{timeout:g}s",
1414
- interface,
1415
- signal,
1416
- _OBJECT_PATH,
1417
- session_handle,
1418
- )
1494
+ # Collected as they are made, and unsubscribed from the list, for
1495
+ # `_request`'s reason: taking them into two locals before the try meant
1496
+ # a failure in the second subscribe left the first one registered for
1497
+ # the life of the connection, with nothing holding a handle to it.
1498
+ subscriptions: list[Any] = []
1419
1499
  try:
1500
+ subscriptions.append(
1501
+ connection.signal_subscribe(
1502
+ busname,
1503
+ interface,
1504
+ signal,
1505
+ _OBJECT_PATH,
1506
+ None,
1507
+ Gio.DBusSignalFlags.NONE,
1508
+ on_signal,
1509
+ None,
1510
+ )
1511
+ )
1512
+ subscriptions.append(
1513
+ connection.signal_subscribe(
1514
+ busname,
1515
+ _SESSION_INTERFACE,
1516
+ "Closed",
1517
+ session_handle,
1518
+ None,
1519
+ Gio.DBusSignalFlags.NONE,
1520
+ on_closed,
1521
+ None,
1522
+ )
1523
+ )
1524
+ logger.debug(
1525
+ "waiting up to %s for %s.%s on %s for session %s",
1526
+ "forever" if timeout is None else f"{timeout:g}s",
1527
+ interface,
1528
+ signal,
1529
+ _OBJECT_PATH,
1530
+ session_handle,
1531
+ )
1420
1532
  if not result and not session_closed and not malformed:
1421
1533
  timeout_source = None
1422
1534
  if timeout is not None:
@@ -1441,8 +1553,8 @@ def _wait_for_signal(
1441
1553
  if timeout_source is not None and not timeout_fired:
1442
1554
  GLib.source_remove(timeout_source)
1443
1555
  finally:
1444
- connection.signal_unsubscribe(subscription)
1445
- connection.signal_unsubscribe(closed_subscription)
1556
+ for subscription in subscriptions:
1557
+ connection.signal_unsubscribe(subscription)
1446
1558
  return _signal_outcome(
1447
1559
  signal, timeout, result, malformed, timed_out, session_closed
1448
1560
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-libei
3
- Version: 0.8.1
3
+ Version: 0.8.3
4
4
  Summary: Inject, receive and capture input on Wayland from Python: ctypes bindings for libei, libeis and liboeffis, plus the RemoteDesktop and InputCapture portals
5
5
  Author: Dennis K. Paulsen
6
6
  License-Expression: MIT
@@ -175,7 +175,7 @@ and why, is in
175
175
 
176
176
  ## Status
177
177
 
178
- Beta (`0.8.1`), published on [PyPI](https://pypi.org/project/python-libei/)
178
+ Beta (`0.8.3`), published on [PyPI](https://pypi.org/project/python-libei/)
179
179
  since `0.1.0`, and **the API is not frozen** — expect renames before 1.0.
180
180
 
181
181
  The injection path is exercised end to end against the real libraries by the
@@ -190,6 +190,39 @@ asserted.
190
190
  Exactly what was run, when, and against which versions:
191
191
  [docs/developers/verification.md](docs/developers/verification.md).
192
192
 
193
+ ### What the API raises
194
+
195
+ Three independent exception families, by the layer that raises them, so a
196
+ caller can catch at the granularity they need — plus one that sits before
197
+ all of them:
198
+
199
+ - **`LibraryNotFoundError`** (a `RuntimeError`, exported by `libei.ei`,
200
+ `libei.eis` and `libei.oeffis` alike) — the native library could not be
201
+ loaded. Importing never raises it; the first call that needs the library
202
+ does, and every later call after that. `is_available()` asks the same
203
+ question without raising.
204
+ - **`libei.ei.Error`** (and `libei.eis.Error`) — the native library reported
205
+ a failure through its own return codes. One base class per module;
206
+ subclasses are added as distinct failure modes earn them rather than up
207
+ front.
208
+ - **`libei.oeffis.DisconnectedError`**, with `SessionClosedError` under it —
209
+ the EIS connection is gone. `dispatch()` raises the subclass when the
210
+ portal closed the session and the base class when the connection dropped
211
+ or the fd could not be obtained; `eis_fd` raises the base class whenever
212
+ no connection is up yet, so it is `dispatch()` that tells the two apart.
213
+ - **`libei.portal.PortalError`**, with `PortalVersionError`,
214
+ `PortalTimeoutError`, `PortalDeniedError`, `PortalProtocolError` and
215
+ `PortalSessionClosedError` under it — each a *different* thing the portal
216
+ round trip can do, kept separate on purpose: a timeout (no answer), a
217
+ denial (answered no), a protocol surprise (answered malformed) and a
218
+ version mismatch are not interchangeable, and collapsing them would make a
219
+ caller guess. These are the ones worth catching individually.
220
+
221
+ Argument mistakes that are the caller's and not the desktop's —
222
+ no capabilities, the wrong value kind — raise the stock `ValueError` /
223
+ `TypeError`, never a library exception. The hierarchy is stable in shape; as
224
+ with the rest of the API, names may still change before 1.0.
225
+
193
226
  ## Alternatives
194
227
 
195
228
  | Instead of this | Why you might |
@@ -247,6 +247,8 @@ class FakeInputCaptureConnection:
247
247
  ) -> tuple[FakeReply, FakeUnixFDList]:
248
248
  self.calls.append((method, parameters.value))
249
249
  self.call_targets.append((method, bus_name, object_path, timeout))
250
+ # Index 0 against a one-fd list: the only in-range pair, and now it
251
+ # has to be, since FakeUnixFDList models the real -1-on-bad-index.
250
252
  return FakeReply((0,)), FakeUnixFDList(self.fd_responses[method])
251
253
 
252
254
 
@@ -0,0 +1,94 @@
1
+ """An event used after its loop iteration, through the real library.
2
+
3
+ Each event is released as the loop moves on, and the docs promise a
4
+ ``RuntimeError`` afterwards. test_ei_objects.py checks ``_as_parameter_`` in
5
+ isolation, which is not the path a caller takes: a real call converts its
6
+ arguments inside ctypes, and ctypes re-raises whatever that conversion raised as
7
+ ``ctypes.ArgumentError`` carrying only the text. So the promise is checked here,
8
+ with a real event and a real C call.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import select
15
+ import socket
16
+ from pathlib import Path
17
+
18
+ import pytest
19
+
20
+ from conftest import requires_libei
21
+ from libei import ei, eis
22
+ from test_integration_extras import Pair
23
+
24
+ pytestmark = [pytest.mark.integration, requires_libei]
25
+
26
+
27
+ def test_a_released_event_raises_runtime_error_from_a_real_call() -> None:
28
+ pair = Pair((eis.DeviceCapability.POINTER,))
29
+ kept: list[eis.Event] = []
30
+
31
+ def on_server_event(event: eis.Event) -> None:
32
+ if event.event_type is eis.EventType.POINTER_MOTION:
33
+ kept.append(event)
34
+
35
+ def on_device(device: ei.Device) -> None:
36
+ device.start_emulating().pointer_motion(7, 3).frame().stop_emulating()
37
+
38
+ pair.run(lambda: bool(kept), on_server_event=on_server_event, on_device=on_device)
39
+ # The loop has moved on, so the event has been released.
40
+ if select.select([pair.server.fd], [], [], 0.2)[0]:
41
+ pair.server.dispatch()
42
+ list(pair.server.events)
43
+
44
+ def event_type(event: eis.Event) -> object:
45
+ return event.event_type
46
+
47
+ def pointer_event(event: eis.Event) -> object:
48
+ return event.pointer_event
49
+
50
+ for read in (event_type, pointer_event):
51
+ with pytest.raises(RuntimeError, match="already been released"):
52
+ read(kept[0])
53
+
54
+
55
+ def test_a_second_transport_setup_is_refused_in_python_not_an_abort() -> None:
56
+ # ei_setup_backend_fd() and ei_setup_backend_socket() both open on
57
+ # assert(!ei->backend): a second setup reaching C does not fail, it
58
+ # SIGABRTs the interpreter. That makes this test its own bite check --
59
+ # without the Python-side refusal it cannot merely fail, it kills the
60
+ # whole run.
61
+ server = eis.Eis.create_for_fd()
62
+ client_fd = server.add_client()
63
+ sender = ei.Sender.create_for_fd(client_fd, name="setup-twice-probe")
64
+ first, second = socket.socketpair()
65
+ with first, second:
66
+ spare = os.dup(first.fileno())
67
+ try:
68
+ with pytest.raises(RuntimeError, match="already has a transport"):
69
+ sender.set_fd(spare)
70
+ finally:
71
+ # Refused before the pointer ever reached C, so the fd was not
72
+ # handed off and is still the caller's to close.
73
+ os.close(spare)
74
+ with pytest.raises(RuntimeError, match="already has a transport"):
75
+ sender.set_socket(None)
76
+
77
+
78
+ def test_a_failed_socket_setup_spends_the_context_too() -> None:
79
+ # The C setup installs its backend object before any of its failure
80
+ # returns, so a context whose setup failed hits the same abort on a
81
+ # retry: the refusal has to key on "was setup attempted", not "did it
82
+ # succeed". Built the way create_for_socket() builds it, because the
83
+ # public constructor raises away its context on exactly this failure.
84
+ context = ei.Sender(ei.Sender._new())
85
+ with pytest.raises(ei.Error):
86
+ context.set_socket(Path("/nonexistent-libei-test") / "no-such-socket")
87
+ first, second = socket.socketpair()
88
+ with first, second:
89
+ spare = os.dup(first.fileno())
90
+ try:
91
+ with pytest.raises(RuntimeError, match="already has a transport"):
92
+ context.set_fd(spare)
93
+ finally:
94
+ os.close(spare)
@@ -1,19 +1,28 @@
1
- """End-to-end test against the real libei/libeis, entirely in-process.
2
-
3
- Uses the fd backend on both sides (``Eis.create_for_fd()`` + ``add_client()``
4
- on the server, ``ei.Sender.create_for_fd()`` on the client) -- the same
5
- mechanism xdg-desktop-portal's RemoteDesktop implementation uses to hand a
6
- client its EI fd, but without needing a live portal/compositor/user-consent
7
- dialog. It's what makes this package's core injection path testable in CI
8
- rather than only against a live desktop session -- see
9
- ``_capi/libeis.py``'s module docstring and docs/vs-snegg.md for how this
10
- path's real signatures were worked out.
1
+ """End-to-end tests against the real libei/libeis, entirely in-process.
2
+
3
+ Most of these use the fd backend on both sides (``Eis.create_for_fd()`` +
4
+ ``add_client()`` on the server, ``ei.Sender.create_for_fd()`` on the client)
5
+ -- the same mechanism xdg-desktop-portal's RemoteDesktop implementation uses
6
+ to hand a client its EI fd, but without needing a live
7
+ portal/compositor/user-consent dialog. It's what makes this package's core
8
+ injection path testable in CI rather than only against a live desktop session
9
+ -- see ``_capi/libeis.py``'s module docstring and docs/vs-snegg.md for how
10
+ this path's real signatures were worked out.
11
+
12
+ ``test_socket_backend_round_trips_and_reports_client_pid`` is the exception:
13
+ it drives the *socket* backend (``create_for_socket()`` on both sides), the
14
+ transport no fd-backend test can reach, and reads a client's pid off the live
15
+ peer credential -- which only the socket backend can answer.
11
16
  """
12
17
 
13
18
  from __future__ import annotations
14
19
 
20
+ import os
15
21
  import select
22
+ import shutil
23
+ import tempfile
16
24
  import time
25
+ from pathlib import Path
17
26
 
18
27
  import pytest
19
28
 
@@ -44,6 +53,13 @@ _READ_EMULATING_SEQUENCE = (
44
53
  _SENT_EMULATING_SEQUENCE if has_symbol("libeis.so.1", "eis_set_flag") else 0
45
54
  )
46
55
 
56
+ # eis_backend_socket_get_client_pid is libei 1.5+; the socket transport itself
57
+ # is on the 1.0.0 floor. So test_socket_backend_round_trips_and_reports_client_pid
58
+ # runs on every version and only the pid read is gated -- the same has_symbol
59
+ # branch as above, rather than a mark that would skip the whole test on an older
60
+ # library that can still prove the transport.
61
+ _HAS_CLIENT_PID = has_symbol("libeis.so.1", "eis_backend_socket_get_client_pid")
62
+
47
63
 
48
64
  def test_client_connects() -> None:
49
65
  server = eis.Eis.create_for_fd()
@@ -304,3 +320,231 @@ def test_the_accessors_no_other_test_reaches_round_trip() -> None:
304
320
  # member of the enum is claimed.
305
321
  assert seen["device_type"] in tuple(eis.DeviceType)
306
322
  assert seen["height"] == 0
323
+
324
+
325
+ def test_seat_bind_reports_the_capabilities_the_client_bound() -> None:
326
+ """``eis.Event.seat_capabilities``, read off a real SEAT_BIND event.
327
+
328
+ The binding behind it -- ``eis_event_seat_has_capability`` -- is a
329
+ per-capability probe no other test calls at the value level, and the
330
+ ``SEAT_BIND`` accessor the suite's earlier round-trip pass missed. A wrong
331
+ symbol name or ``restype`` on it would return plausible booleans in
332
+ isolation; this catches that by having the server offer exactly three
333
+ capabilities, the client bind exactly those three, and the ``SEAT_BIND``
334
+ event name all three and nothing else. The offer and the bind each pass
335
+ the three in a *different* non-declaration order, so the asserted result
336
+ -- (POINTER, SCROLL, BUTTON), ``DeviceCapability`` declaration order,
337
+ which is how the accessor assembles the tuple -- can match neither of
338
+ them by accident.
339
+ """
340
+ server = eis.Eis.create_for_fd()
341
+ client_fd = server.add_client()
342
+ sender = ei.Sender.create_for_fd(client_fd, name="seatbind-probe")
343
+
344
+ offered = (
345
+ eis.DeviceCapability.SCROLL,
346
+ eis.DeviceCapability.BUTTON,
347
+ eis.DeviceCapability.POINTER,
348
+ )
349
+ requested = (
350
+ ei.DeviceCapability.BUTTON,
351
+ ei.DeviceCapability.POINTER,
352
+ ei.DeviceCapability.SCROLL,
353
+ )
354
+ bound: tuple[eis.DeviceCapability, ...] | None = None
355
+
356
+ deadline = time.monotonic() + 10.0
357
+ fds: dict[int, eis.Eis | ei.Sender] = {server.fd: server, sender.fd: sender}
358
+ while bound is None and time.monotonic() < deadline:
359
+ ready, _, _ = select.select(list(fds), [], [], 0.2)
360
+ for fd in ready:
361
+ fds[fd].dispatch()
362
+ for server_event in server.events:
363
+ if server_event.event_type is eis.EventType.CLIENT_CONNECT:
364
+ server_event.client.connect()
365
+ seat = server_event.client.new_seat("seatbind-seat")
366
+ seat.configure_capabilities(offered)
367
+ seat.add()
368
+ elif server_event.event_type is eis.EventType.SEAT_BIND:
369
+ bound = server_event.seat_capabilities
370
+ for sender_event in sender.events:
371
+ if (
372
+ sender_event.event_type is ei.EventType.SEAT_ADDED
373
+ and sender_event.seat is not None
374
+ ):
375
+ sender_event.seat.bind(requested)
376
+
377
+ assert bound is not None, "server never saw a SEAT_BIND event"
378
+ assert bound == (
379
+ eis.DeviceCapability.POINTER,
380
+ eis.DeviceCapability.SCROLL,
381
+ eis.DeviceCapability.BUTTON,
382
+ )
383
+
384
+
385
+ def test_scroll_stop_and_cancel_round_trip() -> None:
386
+ """``scroll_stop``/``scroll_cancel`` send, and the event read on the server.
387
+
388
+ Four C symbols no other test exercises at the value level: the client's
389
+ ``ei.Device.scroll_stop()``/``scroll_cancel()`` send path
390
+ (``ei_device_scroll_stop`` / ``ei_device_scroll_cancel``) and the server's
391
+ read of the resulting events (``eis_event_scroll_get_stop_x`` /
392
+ ``eis_event_scroll_get_stop_y``, which ``scroll_stop_event`` accepts for
393
+ both SCROLL_STOP and SCROLL_CANCEL). The two axes are set asymmetrically --
394
+ stop on y only, cancel on x only -- so a getter wired to the wrong axis
395
+ symbol, or an accessor that read a SCROLL_CANCEL as a stop, would disagree
396
+ with the value sent.
397
+ """
398
+ server = eis.Eis.create_for_fd()
399
+ client_fd = server.add_client()
400
+ sender = ei.Sender.create_for_fd(client_fd, name="scrollstop-probe")
401
+
402
+ scroll_caps = (eis.DeviceCapability.POINTER, eis.DeviceCapability.SCROLL)
403
+ client_scroll_caps = (ei.DeviceCapability.POINTER, ei.DeviceCapability.SCROLL)
404
+ device_created = False
405
+ emitted = False
406
+ stop_event: eis.ScrollStopEvent | None = None
407
+ cancel_event: eis.ScrollStopEvent | None = None
408
+
409
+ deadline = time.monotonic() + 15.0
410
+ fds: dict[int, eis.Eis | ei.Sender] = {server.fd: server, sender.fd: sender}
411
+ while (stop_event is None or cancel_event is None) and time.monotonic() < deadline:
412
+ ready, _, _ = select.select(list(fds), [], [], 0.2)
413
+ for fd in ready:
414
+ fds[fd].dispatch()
415
+ for server_event in server.events:
416
+ kind = server_event.event_type
417
+ if kind is eis.EventType.CLIENT_CONNECT:
418
+ server_event.client.connect()
419
+ seat = server_event.client.new_seat("scrollstop-seat")
420
+ seat.configure_capabilities(scroll_caps)
421
+ seat.add()
422
+ elif kind is eis.EventType.SEAT_BIND and not device_created:
423
+ device_created = True
424
+ assert server_event.seat is not None
425
+ device = server_event.seat.new_device()
426
+ device.configure(name="scrollstop-device", capabilities=scroll_caps)
427
+ device.add()
428
+ device.resume()
429
+ elif kind is eis.EventType.SCROLL_STOP:
430
+ stop_event = server_event.scroll_stop_event
431
+ elif kind is eis.EventType.SCROLL_CANCEL:
432
+ cancel_event = server_event.scroll_stop_event
433
+ for sender_event in sender.events:
434
+ kind = sender_event.event_type
435
+ if kind is ei.EventType.SEAT_ADDED and sender_event.seat is not None:
436
+ sender_event.seat.bind(client_scroll_caps)
437
+ elif (
438
+ # DEVICE_RESUMED, not DEVICE_ADDED: a device arrives paused,
439
+ # and ei_device_start_emulating() silently returns unless the
440
+ # device's state is RESUMED. Both events are in flight here,
441
+ # so keying off ADDED happens to work whenever one dispatch
442
+ # batch carries both -- and sends nothing at all the moment
443
+ # they split across batches.
444
+ kind is ei.EventType.DEVICE_RESUMED
445
+ and sender_event.device is not None
446
+ and ei.DeviceCapability.SCROLL in sender_event.device.capabilities
447
+ and not emitted
448
+ ):
449
+ emitted = True
450
+ client_device = sender_event.device
451
+ # scroll_stop/scroll_cancel describe the *end* of a scroll, so
452
+ # each follows a scroll_delta on the same axis within its own
453
+ # frame -- the shape libei's header documents.
454
+ client_device.start_emulating()
455
+ client_device.scroll_delta(0.0, 5.0)
456
+ client_device.scroll_stop(False, True)
457
+ client_device.frame()
458
+ client_device.scroll_delta(5.0, 0.0)
459
+ client_device.scroll_cancel(True, False)
460
+ client_device.frame()
461
+ client_device.stop_emulating()
462
+
463
+ assert stop_event is not None, "server never received a SCROLL_STOP event"
464
+ assert cancel_event is not None, "server never received a SCROLL_CANCEL event"
465
+ assert stop_event == eis.ScrollStopEvent(stop_x=False, stop_y=True)
466
+ assert cancel_event == eis.ScrollStopEvent(stop_x=True, stop_y=False)
467
+
468
+
469
+ def test_socket_backend_round_trips_and_reports_client_pid() -> None:
470
+ """The socket backend -- the transport the fd-backend tests never take.
471
+
472
+ ``eis.Eis.create_for_socket()`` + ``ei.Sender.create_for_socket()`` drive
473
+ ``eis_setup_backend_socket`` and ``ei_setup_backend_socket``, which no other
474
+ integration test reaches. A pointer motion over the socket proves it
475
+ carries real input, and -- on libei 1.5+, which added the symbol --
476
+ ``eis.Client.pid`` reads ``eis_backend_socket_get_client_pid`` off the live
477
+ ``SO_PEERCRED`` credential. Client and server share this process, so the
478
+ reported pid must be exactly ``os.getpid()``; the fd backend has no peer
479
+ socket to ask and could not test this path at all.
480
+ """
481
+ tmpdir = tempfile.mkdtemp(prefix="eis")
482
+
483
+ device_created = False
484
+ client_pid: int | None = None
485
+ received_motion: eis.PointerEvent | None = None
486
+
487
+ try:
488
+ # A short dir under the system temp root keeps the bind path well
489
+ # under the AF_UNIX sun_path limit (108 bytes), which a pytest
490
+ # tmp_path can approach. Both create_for_socket() calls belong inside
491
+ # the try: either can fail -- a bind refused, a connect refused -- and
492
+ # by then libeis may already have put the socket and its .lock in the
493
+ # dir, so a raise out here would leak the whole thing.
494
+ socket_path = Path(tmpdir, "s")
495
+ server = eis.Eis.create_for_socket(socket_path)
496
+ sender = ei.Sender.create_for_socket(socket_path, name="socket-probe")
497
+
498
+ deadline = time.monotonic() + 15.0
499
+ fds: dict[int, eis.Eis | ei.Sender] = {server.fd: server, sender.fd: sender}
500
+ while received_motion is None and time.monotonic() < deadline:
501
+ ready, _, _ = select.select(list(fds), [], [], 0.2)
502
+ for fd in ready:
503
+ fds[fd].dispatch()
504
+ for server_event in server.events:
505
+ kind = server_event.event_type
506
+ if kind is eis.EventType.CLIENT_CONNECT:
507
+ if _HAS_CLIENT_PID:
508
+ client_pid = server_event.client.pid
509
+ server_event.client.connect()
510
+ seat = server_event.client.new_seat("socket-seat")
511
+ seat.configure_capabilities((eis.DeviceCapability.POINTER,))
512
+ seat.add()
513
+ elif kind is eis.EventType.SEAT_BIND and not device_created:
514
+ device_created = True
515
+ assert server_event.seat is not None
516
+ device = server_event.seat.new_device()
517
+ device.configure(
518
+ name="socket-pointer",
519
+ capabilities=(eis.DeviceCapability.POINTER,),
520
+ )
521
+ device.add()
522
+ device.resume()
523
+ elif kind is eis.EventType.POINTER_MOTION:
524
+ received_motion = server_event.pointer_event
525
+ for sender_event in sender.events:
526
+ kind = sender_event.event_type
527
+ if kind is ei.EventType.SEAT_ADDED and sender_event.seat is not None:
528
+ sender_event.seat.bind((ei.DeviceCapability.POINTER,))
529
+ elif (
530
+ # DEVICE_RESUMED, not DEVICE_ADDED -- see the same branch
531
+ # in test_scroll_stop_and_cancel_round_trip:
532
+ # start_emulating() no-ops on a device that is still
533
+ # paused, which is how every device first arrives.
534
+ kind is ei.EventType.DEVICE_RESUMED
535
+ and sender_event.device is not None
536
+ and ei.DeviceCapability.POINTER in sender_event.device.capabilities
537
+ ):
538
+ sender_event.device.start_emulating().pointer_motion(
539
+ 9, 4
540
+ ).frame().stop_emulating()
541
+ finally:
542
+ # rmtree, not rmdir: libeis leaves both the socket and a sibling
543
+ # ``.lock`` file behind, and unlinking an open AF_UNIX socket is fine
544
+ # on Linux.
545
+ shutil.rmtree(tmpdir, ignore_errors=True)
546
+
547
+ assert received_motion is not None, "no pointer motion arrived over the socket"
548
+ assert received_motion == eis.PointerEvent(dx=9, dy=4)
549
+ if _HAS_CLIENT_PID:
550
+ assert client_pid == os.getpid()
@@ -48,11 +48,28 @@ class FakeReply:
48
48
 
49
49
 
50
50
  class FakeUnixFDList:
51
- def __init__(self, fd: int) -> None:
52
- self._fd = fd
51
+ """Stands in for `Gio.UnixFDList`, with its real index semantics.
52
+
53
+ `g_unix_fd_list_get()` treats a bad index as a *programmer error*: it
54
+ asserts `index >= 0 && index < nfd`, logs `GLib-GIO-CRITICAL` and
55
+ returns **-1**, without raising and without setting a `GError`
56
+ (measured on GLib 2.90.1). An earlier version of this fake ignored its
57
+ index and always handed back the one fd it held, which made every
58
+ index equally valid and hid exactly the bug `_call_for_fd`'s bounds
59
+ check exists for. `get_length()` is what that check reads -- the
60
+ portable alternative to `lookup()`, which is GLib 2.90+ only.
61
+ """
62
+
63
+ def __init__(self, *fds: int) -> None:
64
+ self._fds = list(fds)
65
+
66
+ def get_length(self) -> int:
67
+ return len(self._fds)
53
68
 
54
- def get(self, _index: int) -> int:
55
- return self._fd
69
+ def get(self, index: int) -> int:
70
+ if index < 0 or index >= len(self._fds):
71
+ return -1
72
+ return self._fds[index]
56
73
 
57
74
 
58
75
  class FakeGLibError(Exception):
@@ -70,6 +87,19 @@ class FakeGLibError(Exception):
70
87
  self.code = code
71
88
 
72
89
 
90
+ class FailingDupUnixFDList(FakeUnixFDList):
91
+ """A list that holds the fd but cannot dup it: EMFILE/ENFILE.
92
+
93
+ The *only* way a real `g_unix_fd_list_get()` raises `GLib.Error` for an
94
+ in-range index -- it dups the fd to hand back an owned one, and that
95
+ dup can fail when the process is out of descriptors. Kept separate from
96
+ FakeUnixFDList so the common fake stays honest about never raising.
97
+ """
98
+
99
+ def get(self, index: int) -> int:
100
+ raise FakeGLibError("Too many open files")
101
+
102
+
73
103
  _OPEN_PIPES: list[tuple[int, int]] = []
74
104
 
75
105
 
@@ -271,6 +301,8 @@ class FakeConnection:
271
301
  ) -> tuple[FakeReply, FakeUnixFDList]:
272
302
  self.calls.append((method, parameters.value))
273
303
  self.call_targets.append((method, bus_name, object_path, timeout))
304
+ # Index 0 against a one-fd list: the only in-range pair, and now it
305
+ # has to be, since FakeUnixFDList models the real -1-on-bad-index.
274
306
  return FakeReply((0,)), FakeUnixFDList(self.fd_responses[method])
275
307
 
276
308
 
@@ -371,6 +403,48 @@ def test_old_remote_desktop_version_is_refused() -> None:
371
403
  ]
372
404
 
373
405
 
406
+ def test_a_non_numeric_version_property_raises_a_portal_error() -> None:
407
+ # `_call_sync` is given no reply_type -- as everywhere in this module --
408
+ # so GDBus validates nothing about the shape that comes back, and every
409
+ # other reply-consuming site checks the unpacked value before trusting
410
+ # it. These two did not: `int(version)` on a string raised a bare
411
+ # TypeError/ValueError, escaping the `except PortalError` that
412
+ # docs/troubleshooting.md promises covers the negotiation.
413
+ connection = FakeConnection(version="three") # type: ignore[arg-type]
414
+ with install_fake_gi(connection):
415
+ with pytest.raises(portal.PortalProtocolError) as excinfo:
416
+ portal.RemoteDesktopSession.negotiate(connection=connection)
417
+ assert "non-numeric version" in str(excinfo.value)
418
+ assert excinfo.value.step == "Get"
419
+
420
+
421
+ def test_a_version_reply_of_the_wrong_shape_raises_a_portal_error() -> None:
422
+ # The other half: a reply that does not unpack to a one-element tuple
423
+ # raised ValueError out of the tuple assignment itself.
424
+ class WrongShape(FakeConnection):
425
+ def call_sync(self, *args: Any, **kwargs: Any) -> FakeReply:
426
+ if args[3] == "Get":
427
+ self.calls.append(("Get", None))
428
+ return FakeReply(())
429
+ return super().call_sync(*args, **kwargs)
430
+
431
+ connection = WrongShape()
432
+ with install_fake_gi(connection):
433
+ with pytest.raises(portal.PortalProtocolError) as excinfo:
434
+ portal.RemoteDesktopSession.negotiate(connection=connection)
435
+ assert "not that shape" in str(excinfo.value)
436
+
437
+
438
+ def test_a_bool_is_not_accepted_as_a_version() -> None:
439
+ # bool is an int subclass, so a `True` would otherwise read as version 1
440
+ # and be refused with the wrong error -- a version check that says "too
441
+ # old" about a portal that answered nonsense.
442
+ connection = FakeConnection(version=True)
443
+ with install_fake_gi(connection):
444
+ with pytest.raises(portal.PortalProtocolError):
445
+ portal.RemoteDesktopSession.negotiate(connection=connection)
446
+
447
+
374
448
  def test_declined_create_session_raises_portal_denied_error() -> None:
375
449
  connection = FakeConnection(responses={"CreateSession": (1, {})})
376
450
  with install_fake_gi(connection):
@@ -1005,6 +1079,123 @@ def test_a_failed_connect_to_eis_closes_the_portal_session() -> None:
1005
1079
  assert _closed_sessions(connection) == ["/session/1"]
1006
1080
 
1007
1081
 
1082
+ class _FixedFdReplyConnection(FakeConnection):
1083
+ """A FakeConnection whose ConnectToEIS reply is dictated per test.
1084
+
1085
+ `ConnectToEIS` is specified as returning `(h)` -- an *index* into an fd
1086
+ list the reply carries out-of-band -- and the three ways that pair can
1087
+ disagree are what the tests below drive. Each subclass fixes
1088
+ `reply_index` and `out_fd_list` (`None` modelling the nullable out
1089
+ list) and changes nothing else about the negotiation, so what the
1090
+ assertion sees is only the fd-reply handling.
1091
+ """
1092
+
1093
+ reply_index: int = 0
1094
+ out_fd_list: Any = None
1095
+
1096
+ def call_with_unix_fd_list_sync(
1097
+ self,
1098
+ bus_name: Any,
1099
+ object_path: Any,
1100
+ interface: Any,
1101
+ method: str,
1102
+ parameters: FakeVariant,
1103
+ reply_type: Any,
1104
+ flags: Any,
1105
+ timeout: Any,
1106
+ fd_list: Any,
1107
+ cancellable: Any,
1108
+ ) -> tuple[FakeReply, Any]:
1109
+ self.calls.append((method, parameters.value))
1110
+ self.call_targets.append((method, bus_name, object_path, timeout))
1111
+ return FakeReply((self.reply_index,)), self.out_fd_list
1112
+
1113
+
1114
+ def test_connect_to_eis_with_no_out_fd_list_raises_typed() -> None:
1115
+ # GDBusProxy/GDBusConnection's out fd list is nullable: a well-formed
1116
+ # `(h)` reply that attached no fds at all arrives as None. Dereferencing
1117
+ # that used to raise AttributeError ('NoneType' object has no attribute
1118
+ # 'get') from inside negotiate(), which no `except PortalError` catches.
1119
+ class NoFdListConnection(_FixedFdReplyConnection):
1120
+ out_fd_list = None
1121
+
1122
+ connection = NoFdListConnection()
1123
+ with install_fake_gi(connection):
1124
+ with pytest.raises(portal.PortalProtocolError) as excinfo:
1125
+ portal.RemoteDesktopSession.negotiate(connection=connection)
1126
+ assert excinfo.value.step == "ConnectToEIS"
1127
+ assert excinfo.value.payload == 0
1128
+ assert "attached no fd list" in str(excinfo.value)
1129
+ # The session was approved before this failed, so it still has to be
1130
+ # closed on the way out.
1131
+ assert _closed_sessions(connection) == ["/session/1"]
1132
+
1133
+
1134
+ def test_connect_to_eis_with_an_out_of_range_fd_index_raises_typed() -> None:
1135
+ # The case the previous version of this test got wrong. An out-of-range
1136
+ # index is a *programmer error* to g_unix_fd_list_get(): it logs
1137
+ # GLib-GIO-CRITICAL and returns -1 without raising and without setting a
1138
+ # GError (measured, GLib 2.90.1). So nothing is thrown to catch -- the -1
1139
+ # simply flowed out as the EIS fd, and ei.Sender.create_for_fd() has no
1140
+ # guard against a negative one. Only a bounds check against get_length()
1141
+ # catches this, which is why this test fails against the pre-fix
1142
+ # _call_for_fd: it returned -1 and negotiate() succeeded.
1143
+ class OutOfRangeConnection(_FixedFdReplyConnection):
1144
+ reply_index = 1 # one past the end of the one-fd list below
1145
+
1146
+ connection = OutOfRangeConnection()
1147
+ connection.out_fd_list = FakeUnixFDList(_fresh_fd())
1148
+ with install_fake_gi(connection):
1149
+ with pytest.raises(portal.PortalProtocolError) as excinfo:
1150
+ portal.RemoteDesktopSession.negotiate(connection=connection)
1151
+ assert excinfo.value.step == "ConnectToEIS"
1152
+ assert excinfo.value.payload == 1
1153
+ # The message has to name both numbers: an index alone does not say
1154
+ # whether it was one past the end or wildly wrong.
1155
+ assert "index 1, 1 fd(s) attached" in str(excinfo.value)
1156
+ assert _closed_sessions(connection) == ["/session/1"]
1157
+
1158
+
1159
+ def test_connect_to_eis_raises_typed_when_duplicating_the_fd_fails() -> None:
1160
+ # The one real GLib.Error from an *in-range* get(): the function dups the
1161
+ # fd to hand back an owned one, and the dup fails at EMFILE/ENFILE. Left
1162
+ # bare it would reach the caller as the raw GLib type, past every
1163
+ # `except PortalError`. The message must say what it is -- fd exhaustion
1164
+ # -- and not "no matching fd", which is the case the bounds check above
1165
+ # already took.
1166
+ class ExhaustedFdConnection(_FixedFdReplyConnection):
1167
+ reply_index = 0
1168
+
1169
+ connection = ExhaustedFdConnection()
1170
+ connection.out_fd_list = FailingDupUnixFDList(_fresh_fd())
1171
+ with install_fake_gi(connection):
1172
+ with pytest.raises(portal.PortalProtocolError) as excinfo:
1173
+ portal.RemoteDesktopSession.negotiate(connection=connection)
1174
+ assert excinfo.value.step == "ConnectToEIS"
1175
+ assert excinfo.value.payload == 0
1176
+ assert "out of file descriptors" in str(excinfo.value)
1177
+ assert _closed_sessions(connection) == ["/session/1"]
1178
+
1179
+
1180
+ def test_connect_to_eis_resolves_the_index_against_the_fd_list() -> None:
1181
+ # The happy path, with the index doing real work: two fds attached and
1182
+ # the reply naming the *second*, so an implementation that bounds-checked
1183
+ # and then returned the wrong element -- or hardcoded index 0, which
1184
+ # every other test in this file would still pass -- is caught.
1185
+ wanted = _fresh_fd()
1186
+
1187
+ class TwoFdConnection(_FixedFdReplyConnection):
1188
+ reply_index = 1
1189
+
1190
+ connection = TwoFdConnection()
1191
+ connection.out_fd_list = FakeUnixFDList(_fresh_fd(), wanted)
1192
+ with install_fake_gi(connection):
1193
+ session = portal.RemoteDesktopSession.negotiate(connection=connection)
1194
+ assert session.eis_fd == wanted
1195
+ session.close()
1196
+ assert _closed_sessions(connection) == ["/session/1"]
1197
+
1198
+
1008
1199
  def test_an_interrupted_consent_dialog_closes_the_portal_session() -> None:
1009
1200
  # Why the cleanup catches BaseException: Start blocks on a user, so
1010
1201
  # Ctrl-C during that wait is a routine way out of negotiate() -- and it
@@ -1,49 +0,0 @@
1
- """An event used after its loop iteration, through the real library.
2
-
3
- Each event is released as the loop moves on, and the docs promise a
4
- ``RuntimeError`` afterwards. test_ei_objects.py checks ``_as_parameter_`` in
5
- isolation, which is not the path a caller takes: a real call converts its
6
- arguments inside ctypes, and ctypes re-raises whatever that conversion raised as
7
- ``ctypes.ArgumentError`` carrying only the text. So the promise is checked here,
8
- with a real event and a real C call.
9
- """
10
-
11
- from __future__ import annotations
12
-
13
- import select
14
-
15
- import pytest
16
-
17
- from conftest import requires_libei
18
- from libei import ei, eis
19
- from test_integration_extras import Pair
20
-
21
- pytestmark = [pytest.mark.integration, requires_libei]
22
-
23
-
24
- def test_a_released_event_raises_runtime_error_from_a_real_call() -> None:
25
- pair = Pair((eis.DeviceCapability.POINTER,))
26
- kept: list[eis.Event] = []
27
-
28
- def on_server_event(event: eis.Event) -> None:
29
- if event.event_type is eis.EventType.POINTER_MOTION:
30
- kept.append(event)
31
-
32
- def on_device(device: ei.Device) -> None:
33
- device.start_emulating().pointer_motion(7, 3).frame().stop_emulating()
34
-
35
- pair.run(lambda: bool(kept), on_server_event=on_server_event, on_device=on_device)
36
- # The loop has moved on, so the event has been released.
37
- if select.select([pair.server.fd], [], [], 0.2)[0]:
38
- pair.server.dispatch()
39
- list(pair.server.events)
40
-
41
- def event_type(event: eis.Event) -> object:
42
- return event.event_type
43
-
44
- def pointer_event(event: eis.Event) -> object:
45
- return event.pointer_event
46
-
47
- for read in (event_type, pointer_event):
48
- with pytest.raises(RuntimeError, match="already been released"):
49
- read(kept[0])
File without changes
File without changes