python-libei 0.8.1__py3-none-any.whl → 0.8.3__py3-none-any.whl

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.
libei/__init__.py CHANGED
@@ -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__"]
libei/ei.py CHANGED
@@ -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)
libei/portal.py CHANGED
@@ -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 |
@@ -1,17 +1,17 @@
1
- libei/__init__.py,sha256=7fJVf_RPxcEEeOM2YTQHtJPP3ilPhFREQKNmCoJqOL4,1858
1
+ libei/__init__.py,sha256=312stxiJuabMPVgrF7OplROJZhuajmIAPnRyQoXL5hA,1858
2
2
  libei/_cobject.py,sha256=XjbUNJpZ87jAyPWh6dmRslk6cMy831oMRFhWmfjLDFo,13344
3
- libei/ei.py,sha256=3oaZ4dxo-ytBHtES3_1_LUca2ZbR8r3SwA50Rj0hGxo,49541
3
+ libei/ei.py,sha256=UA7dYyyelVoeNnjVocf_22YOxPTSFoiUyQqlkwk8g-M,52010
4
4
  libei/eis.py,sha256=kcFi6vfw9F9uBt6Bz-blGD-0M6mLEMTYDCgC_SKK7vU,46843
5
5
  libei/oeffis.py,sha256=gJHR90s9VhQrgkjWUMDx-lxZ8qKxkttnqbx_xo-7oxs,10035
6
- libei/portal.py,sha256=95f3I5q8BF2ehGP6LEEMzRKTisrwBxkf20rY1MvD1ic,88168
6
+ libei/portal.py,sha256=lULdezDuLj65iKY70f2GNywedwN1pgoiA3sdOfuFyyc,93747
7
7
  libei/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
8
  libei/_capi/__init__.py,sha256=raISSWSV9hAcE92DcLCz-vUb1IPcsmxRZaS-iAoQJBE,211
9
9
  libei/_capi/libei.py,sha256=AQgVZ2ZsHH8rywwcmq1EJ-IauuNHbBMhwauMelX83yE,11754
10
10
  libei/_capi/libeis.py,sha256=C_Uh7DwNncFC8A4wuMhviAj5C_TUmKHtLJYq0Qhhz1E,13142
11
11
  libei/_capi/liboeffis.py,sha256=V8jdmJm3qOQUzzNiCAXt4Jr2JY11Y4-w6NIfIxbxGI4,1218
12
12
  libei/_capi/loader.py,sha256=xW67uk35ckgeFaheDGrHC05ZM5w_cxBGvX5lG_GUSu8,6625
13
- python_libei-0.8.1.dist-info/licenses/LICENSE,sha256=l6xbMU6Y-JZDzmBciBj-J5t6h6jNg_Bcyp4bHxDepqU,1074
14
- python_libei-0.8.1.dist-info/METADATA,sha256=gGc0OayDeot7yFnA2wmURo_xZjjr1UoQxpK7mdynrWk,23364
15
- python_libei-0.8.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
16
- python_libei-0.8.1.dist-info/top_level.txt,sha256=_DQXzGjDsUBENI_cNkiOxPB4xi8coCbQS1lq18FMudQ,6
17
- python_libei-0.8.1.dist-info/RECORD,,
13
+ python_libei-0.8.3.dist-info/licenses/LICENSE,sha256=l6xbMU6Y-JZDzmBciBj-J5t6h6jNg_Bcyp4bHxDepqU,1074
14
+ python_libei-0.8.3.dist-info/METADATA,sha256=JghxAh-bPNxubjncnnWf10uhvJ3a2B66IblD3Aij9rg,25256
15
+ python_libei-0.8.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
16
+ python_libei-0.8.3.dist-info/top_level.txt,sha256=_DQXzGjDsUBENI_cNkiOxPB4xi8coCbQS1lq18FMudQ,6
17
+ python_libei-0.8.3.dist-info/RECORD,,