Repository navigation
Expand file tree
/
Copy pathoeffis.py
More file actions
254 lines (211 loc) · 9.8 KB
/
Copy pathoeffis.py
File metadata and controls
254 lines (211 loc) · 9.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"""Pythonic wrapper around liboeffis.
Negotiates an EIS connection through the
``org.freedesktop.portal.RemoteDesktop`` XDG desktop portal.
This is the path a sandboxed or otherwise non-privileged client uses to get
an EI socket: it asks the portal, the user is shown a consent dialog, and on
approval this hands back a file descriptor to pass to
:meth:`libei.ei.Sender.create_for_fd`::
oeffis = Oeffis.create(devices=DeviceType.POINTER)
while True:
ready, _, _ = select.select([oeffis.fd], [], [], timeout)
if not ready:
continue
if oeffis.dispatch():
break
sender = ei.Sender.create_for_fd(oeffis.eis_fd, name="my-app")
Two limitations worth knowing before building on this:
* **Every run prompts.** The portal supports remembering an approval --
``SelectDevices`` takes a ``persist_mode`` and ``Start`` returns a
``restore_token`` to replay next time -- but liboeffis exposes neither:
``oeffis_create_session()`` takes a device-type bitmask and nothing else.
A caller that must not re-prompt has to drive
``org.freedesktop.portal.RemoteDesktop`` over D-Bus itself and pass the
resulting fd to :meth:`libei.ei.Sender.create_for_fd`, which does not
care how the fd was obtained. See the README section "Avoiding the
consent dialog on every run".
* **Least verified path here.** In live testing this has been the least
reliable part of the underlying libraries (see the project README) --
treat failures as possibly environment-specific rather than necessarily
a bug in this wrapper.
"""
from __future__ import annotations
import enum
import logging
import os
from . import _capi
from ._capi.loader import LibraryNotFoundError
logger = logging.getLogger("libei.oeffis")
def is_available() -> bool:
"""Whether liboeffis.so.1 can be loaded on this system."""
return _capi.liboeffis.lib.is_available()
class DisconnectedError(Exception):
"""The portal session ended unexpectedly (error, or denied by the user)."""
def __init__(self, message: str | None) -> None:
"""Record why the session ended."""
super().__init__(message)
self.message = message
class SessionClosedError(DisconnectedError):
"""The portal explicitly closed the session (not necessarily an error)."""
def __init__(self) -> None:
"""Build the fixed "Session closed" message."""
super().__init__(message="Session closed")
class DeviceType(enum.IntFlag):
"""Device types to request from the portal, OR'd together.
Mirrors ``enum oeffis_device`` from liboeffis.h. Unlike libei's own
capability lists, these *are* passed to C as a single OR'd bitmask --
``oeffis_create_session()`` takes one ``uint32_t``.
"""
ALL_DEVICES = 0
KEYBOARD = 1
POINTER = 2
TOUCHSCREEN = 4
class _EventType(enum.IntEnum):
"""Mirrors ``enum oeffis_event_type``; also used as this object's state.
:meth:`Oeffis.dispatch` stores the last event it saw in ``_state``, so
the terminal ones (CLOSED, DISCONNECTED) keep raising on every later
call rather than silently doing nothing.
"""
NONE = 0
CONNECTED_TO_EIS = 1
CLOSED = 2
DISCONNECTED = 3
class Oeffis:
"""Wraps a liboeffis context for one portal session.
Must be kept alive for the duration of the session -- destroying it
closes the session and invalidates ``eis_fd`` for any :mod:`libei.ei`
context still using it.
"""
def __init__(self) -> None:
"""Create the underlying liboeffis context (no portal call yet)."""
pointer = _capi.liboeffis.new(None)
if not pointer:
raise DisconnectedError("oeffis_new() returned NULL")
self._pointer = pointer
self._eis_fd: int | None = None
# Set the first (and only the first) time the `eis_fd` property is
# read -- reading it hands the fd to the caller (typically to pass
# straight to Sender.create_for_fd(), which takes ownership and
# closes it itself), so __del__ must not also close it once that's
# happened. But oeffis_get_eis_fd() docs say the caller owns the
# dup()'d fd it returns, and if the session dies (or this object is
# just dropped) before anyone ever reads `eis_fd`, nothing else
# will ever close it -- __del__ closes it itself in that case.
self._eis_fd_claimed = False
self._state = _EventType.NONE
def __del__(self) -> None:
"""Release the session, closing the EIS fd if nobody claimed it.
Safe on a half-built object: __init__ can raise before every
attribute exists, and this still runs.
"""
# getattr() with defaults rather than plain attribute access:
# __init__ raises DisconnectedError when oeffis_new() returns NULL,
# and Python still calls __del__ on the half-built object, where
# none of these attributes exist yet. A bare self._eis_fd would
# raise AttributeError inside __del__ -- which Python swallows to
# stderr -- and skip the unref below.
eis_fd = getattr(self, "_eis_fd", None)
# The `True` default is the fail-safe direction: if the attribute is
# somehow missing, assume the fd was claimed and leave it alone.
# Not closing an fd we own leaks one; closing one the caller already
# handed to ei_setup_backend_fd() would break a live connection, or
# close an unrelated fd that has since reused the number.
if eis_fd is not None and not getattr(self, "_eis_fd_claimed", True):
os.close(eis_fd)
pointer = getattr(self, "_pointer", None)
if pointer:
_capi.liboeffis.unref(pointer)
@property
def fd(self) -> int:
"""Poll this fd; call :meth:`dispatch` whenever it's readable."""
return _capi.liboeffis.get_fd(self._pointer)
@property
def eis_fd(self) -> int:
"""The fd to pass to :meth:`libei.ei.Sender.create_for_fd`.
Raises :class:`DisconnectedError` if accessed before
:meth:`dispatch` has returned ``True``.
"""
if self._state != _EventType.CONNECTED_TO_EIS:
raise DisconnectedError(self.error_message)
assert self._eis_fd is not None
self._eis_fd_claimed = True
return self._eis_fd
def dispatch(self) -> bool:
"""Process pending events; return True once connected to EIS.
Raises :class:`DisconnectedError` or :class:`SessionClosedError` if
the session ended; further calls after that keep raising the same
exception rather than silently doing nothing.
"""
if self._state == _EventType.CLOSED:
raise SessionClosedError()
if self._state == _EventType.DISCONNECTED:
raise DisconnectedError(self.error_message)
_capi.liboeffis.dispatch(self._pointer)
while True:
raw_event = _capi.liboeffis.get_event(self._pointer)
try:
event = _EventType(raw_event)
except ValueError:
# Same contract as ei/eis EventType: an event value this
# table doesn't know about must not crash the caller. Skip
# it and keep draining rather than raising out of dispatch.
logger.debug("ignoring unknown oeffis event type %d", raw_event)
continue
if event == _EventType.NONE:
return False
if event == _EventType.CONNECTED_TO_EIS:
eis_fd = _capi.liboeffis.get_eis_fd(self._pointer)
if eis_fd < 0:
# Documented as "-1 on failure or before the fd was
# retrieved". Treating that as a live fd would hand -1
# to ei_setup_backend_fd() and fail far from the cause.
self._state = _EventType.DISCONNECTED
raise DisconnectedError(
self.error_message
or "oeffis_get_eis_fd() failed after CONNECTED_TO_EIS"
)
self._eis_fd = eis_fd
self._state = _EventType.CONNECTED_TO_EIS
return True
if event == _EventType.DISCONNECTED:
self._state = _EventType.DISCONNECTED
raise DisconnectedError(self.error_message)
if event == _EventType.CLOSED:
self._state = _EventType.CLOSED
raise SessionClosedError()
@property
def error_message(self) -> str | None:
"""The last error liboeffis reported, or ``None`` if it has none.
Populated when a session disconnects or fails; a healthy session
normally reports nothing, but ``None`` only ever means "no message
available", not "no error occurred".
"""
message = _capi.liboeffis.get_error_message(self._pointer)
return message.decode("utf-8") if message else None
@classmethod
def create(
cls,
devices: DeviceType = DeviceType.ALL_DEVICES,
busname: str = "org.freedesktop.portal.Desktop",
) -> Oeffis:
"""Start a RemoteDesktop portal session request.
Returns immediately -- the portal typically prompts the user for
consent, so poll :attr:`fd` and call :meth:`dispatch` until it
returns ``True`` before reading :attr:`eis_fd`.
"""
session = cls()
_capi.liboeffis.create_session_on_bus(
session._pointer, busname.encode("utf-8"), devices
)
return session
__all__ = [
"DeviceType",
"DisconnectedError",
# Imported rather than defined here: every call bound through
# _capi.liboeffis can raise it -- Oeffis.create() on a machine with no
# liboeffis is the ordinary one -- so a caller importing from this
# module catches it from here too. See docs/troubleshooting.md.
"LibraryNotFoundError",
"Oeffis",
"SessionClosedError",
"is_available",
]