diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..fc86a24 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,31 @@ +# What an editor should do with the files in this repository, whatever editor +# that is -- VS Code, PyCharm, Vim, Emacs, Sublime and the rest read this file. +# Every setting below is the one the tree is already written in, not a +# preference being imposed on it. +# +# Line endings are the half of this that matters: a file saved with CRLF comes +# back as a whole-file diff to everyone else, and a CRLF shell script will not +# run on Linux. Git cannot see an editor's settings, so this file is paired +# with `.gitattributes`, which makes git normalize what it stores; this is what +# an editor is told before it writes. +# +# Measured rather than assumed, when this was written: every tracked file has +# LF in the index and no tracked file contains a tab. + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{yml,yaml,json}] +indent_size = 2 + +[*.md] +# Two trailing spaces are a hard line break in Markdown; trimming them would +# join lines that are meant to be apart. +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..5c1d97d --- /dev/null +++ b/.gitattributes @@ -0,0 +1,27 @@ +# Line endings and binary-ness, decided by git rather than by whichever editor +# or platform last touched a file. The companion to `.editorconfig`: that one +# tells an editor what to write, and this one makes git normalize what it +# stores, which is the half an editor's settings cannot reach. +# +# Why it earns its place: this package is a Linux library (libei is) that is +# also edited from Windows, where a global `core.autocrlf` would otherwise +# check these files out with CRLF -- and a shell script with CRLF endings +# fails on Linux with a confusing "bad interpreter" error. Every tracked file +# already has LF in the index -- measured, not assumed -- so there is nothing +# to renormalize for this to take effect. +# +# `text=auto` lets git decide what is text; `eol=lf` is what it puts in the +# working tree even on Windows. +* text=auto eol=lf + +# Not text at all: git must never translate these. +*.png binary +*.gif binary +*.jpg binary +*.jpeg binary +*.pdf binary +*.so binary +*.pyc binary +*.whl binary +*.zip binary +*.tar.gz binary diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ee725a..34ad2ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,62 @@ All notable changes to python-libei are recorded here. The format follows ## [Unreleased] +## [0.6.1] - 2026-10-01 + +### Changed + +- **The package metadata and README now say `libei.portal` captures input, and + the README counts its modules right.** `InputCaptureSession` -- receiving the + user's real pointer and keyboard through the InputCapture portal -- was in the + module docstring and nowhere a reader looks: not the PyPI description, not the + keywords, and not the README's table of what to use for what. The description + now names it, `input-capture` and `eis` join the keywords, and the table has a + row that says, as `docs/developers/verification.md` does, that only its + negotiation half has been run against a real desktop. Also the `POSIX` + operating-system classifier the other two packages carry, a `documentation` URL + and a link to pyguitest, its main consumer. The README said "Five modules" + where there are four (`ei`, `eis`, `oeffis`, `portal`; the table has five rows). + `InputCaptureSession`'s docstring said "Never live-tested", which the + verification log contradicts for its negotiation half; it now says half. + ### Fixed +- **Using a released event raised `ctypes.ArgumentError`, not the documented + `RuntimeError`.** Each event is released as the loop moves on, and the README + and `docs/recipes.md` promise a `RuntimeError` if one is used afterwards. What + a caller actually got, from a real call, was + `ArgumentError: argument 1: RuntimeError: Event has already been released` -- + ctypes wraps anything raised while converting an argument and keeps only its + text, so `except RuntimeError` missed it. The unit test passed because it read + `_as_parameter_` directly and never crossed ctypes; found by probing the real + library for the README's claims. `LazyLibrary` now re-raises the original + `RuntimeError` when an argument is a released object, and an ordinary bad + argument is still ctypes' own error. + +- **Six bindings named no libei version, so an old library read as a mystery.** + `ei_touch_cancel`, `ei_event_touch_get_is_cancel`, `ei_event_pong_get_ping` and + their libeis counterparts arrived in libei 1.4, and + `eis_backend_socket_get_client_pid` in 1.5; none carried the `# libei X.Y+` + marker the other gated declarations do. Found by checking every declaration + against the headers of 1.0.0, 1.2.1, 1.4.0, 1.5.0 and 1.6.0. Behaviour was + already right -- the README's version table had them correctly -- so this is + the source catching up with it. + +- **The docs said forgetting `frame()` means nothing happens, silently. It is + only true without `stop_emulating()`.** Measured against libei 1.2.1 and 1.6.0: + a motion queued and then followed by `stop_emulating()` is delivered, in a + `FRAME` libei adds itself, and logged as an error -- + `Bug: ei_device_stop_emulating: missing call to ei_device_frame()`. Only a + queue that is never stopped is dropped with no log line at all. The README, + getting-started and troubleshooting now say so. The same probing corrected + two more claims: an event sent to a device lacking the capability is dropped + with a `Bug: ... device is not a keyboard` error log rather than "silently", + and the wrong-accessor read libei answers with zeros is likewise logged at + error level rather than "a line the caller never sees". The README's list of + versions the suite has been run against named 1.5.0, which + `docs/developers/verification.md` has no record of, and contradicted its own + Status section on CI's 1.2.1; both now agree. + - **The test suite ran nothing at all off Linux and FreeBSD.** `tests/test_loader.py` raised at module level when `ctypes.util.find_library("c")` found no C library, which pytest reports as a *collection* error -- so on Windows `pytest -q -rs` @@ -23,6 +77,31 @@ All notable changes to python-libei are recorded here. The format follows stylus protocol has landed there too. Still none of it is in a release, so still none of it is bound. +### Tests + +- **The bindings are checked against the real headers and libraries.** + `tests/test_abi.py` compares every declared function's argument count and + argument and return classes (pointer, 4- or 8-byte int, double, bool, void) + with the upstream prototype, every Python enum member with its C enumerator + value, and every declaration with the installed library's exports, where a + missing one must carry a version marker. There are no `ctypes.Structure` + bindings, so there is no layout to check. It needs the headers, via + `LIBEI_SOURCE_DIR`, and otherwise skips; see CONTRIBUTING.md. Clean against + the public headers of 1.0.0, 1.2.1, 1.4.0, 1.5.0 and 1.6.0, and against the + installed 1.6.0 (Fedora 45) and 1.2.1 (Ubuntu 24.04) libraries. + `LazyLibrary` now records what is declared on it (`declared`, `soname`) for this. +- **Every event accessor against every event type.** + `tests/test_event_accessors.py` reads the accessor list from the source, so a + new one is covered automatically, and checks that each raises `TypeError` + before any C accessor is called for every wrong type, on both the client and + server side, and that an accessor added without a guard fails. Previously one + wrong type per library was pinned. +- **Forgetting `frame()` and using a released event, against the real library.** + `tests/test_integration_frame.py` pins the four behaviours above and + `tests/test_integration_lifetime.py` the released-event error; the loader tests + gain missing-symbol behaviour (named, repeatable, the rest still working) and + one-open-under-concurrent-first-calls. + ## [0.6.0] - 2026-09-22 ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a9962c1..d55fb10 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -67,6 +67,24 @@ LD_LIBRARY_PATH=$PWD/prefix/lib64 pytest -q -rs # from this checkout Expect passes plus skips, never failures or hangs. +### Checking the bindings against the headers + +`tests/test_abi.py` compares every binding with the upstream prototypes and +enums, but only when it can find the headers. Point `LIBEI_SOURCE_DIR` at an +upstream checkout or release tarball (the directory holding `meson.build`): + +```sh +for v in 1.0.0 1.2.1 1.4.0 1.6.0; do + curl -sL https://gitlab.freedesktop.org/libinput/libei/-/archive/$v/libei-$v.tar.gz | tar xz + LIBEI_SOURCE_DIR=$PWD/libei-$v pytest tests/test_abi.py -q +done +``` + +A failure there means a wrong argument count or width, or a wrong enum value -- +or a function declared without the `# libei X.Y+` marker on its `lib.function(` +line saying which release added it. Without the headers, only the check against +the installed libraries runs, and the rest skips. + A separate job installs the package with no native libraries at all and imports it, which is the property the lazy loader exists to provide. What has and has not been verified, and against which libei versions, is in diff --git a/README.md b/README.md index de3af76..fa2b378 100644 --- a/README.md +++ b/README.md @@ -16,8 +16,11 @@ device.start_emulating().pointer_motion(5, 0).frame().stop_emulating() ``` **The one concept:** events queue up, and **`frame()` is what sends them** as -one logical hardware event. Forget it and nothing happens — no exception, no -warning, no movement. Fill the package, then post it. +one logical hardware event. Forget it and the motion is usually lost — no +exception, no warning, no movement. (Ending the chain with `stop_emulating()` +makes libei frame the queue for you, but it logs an error-level `Bug:` line +when it does; see [Things that will bite you](#things-that-will-bite-you).) Fill +the package, then post it. New here? [docs/getting-started.md](docs/getting-started.md) is install through a first real pointer motion, in five minutes. @@ -59,8 +62,8 @@ than a widget-tree back door: ## Which API do I need? -Five modules, and most callers need exactly two of them: `oeffis` or `portal` -to get permission, then `ei` to inject. +Four modules (`ei`, `eis`, `oeffis`, `portal`), and most callers need exactly +two of them: `oeffis` or `portal` to get permission, then `ei` to inject. | You want to… | Use | Notes | | --- | --- | --- | @@ -68,6 +71,7 @@ to get permission, then `ei` to inject. | **Consume input** from a compositor | `libei.ei` → `Receiver` | Compositor-side or input-capture code; same connection dance | | **Get permission**, simply | `libei.oeffis` | One call, pollable fd, no dependencies. The consent dialog appears on **every** run | | **Get permission**, and not be asked again | `libei.portal` | Same handshake over D-Bus directly, with `persist_mode` / `restore_token`. Needs PyGObject | +| **Capture the user's real input** | `libei.portal` → `InputCaptureSession` | The read direction, through the InputCapture portal: once the compositor decides to, the user's pointer and keyboard are diverted to you over EIS. Exclusive while active, so hold it briefly. Only its negotiation half has been run against a real desktop — see [verification](docs/developers/verification.md) | | **Be the server**, for tests or a compositor | `libei.eis` | Drives your client code with no real compositor and no consent dialog | Each module has `is_available()`. `ei` and `eis` share the shapes around them: @@ -130,7 +134,7 @@ and why, is in ## Status -Beta (`0.6.0`), published on [PyPI](https://pypi.org/project/python-libei/) +Beta (`0.6.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 @@ -171,9 +175,13 @@ Exactly what was run, when, and against which versions: - libei 1.0.0 or newer for the core: connecting, binding a seat, and sending pointer, button, keyboard, scroll and touch input all use symbols that have existed with a stable signature since 1.0.0, and upstream keeps - API/ABI back-compatible within the 1.x series. Only 1.5.0 and 1.6.0 have - actually been run against -- 1.6.0 on both Fedora 44 and FreeBSD 15, where - the injection path passes the full suite with nothing skipped. + API/ABI back-compatible within the 1.x series. The suite has been run + against 1.2.1 (Ubuntu 24.04, in CI) and 1.6.0 -- the latter on Fedora 44 and + 45 and FreeBSD 15, where the injection path passes the full suite with + nothing skipped. Every binding's name, argument types and return type, and + every enum value, is also checked against the upstream headers of 1.0.0, + 1.2.1, 1.4.0, 1.5.0 and 1.6.0 (`tests/test_abi.py`), which is the only + coverage 1.0.0, 1.4.0 and 1.5.0 have had. Newer libei buys you more, per feature: @@ -331,8 +339,12 @@ All four, with working code: soon as the loop moves on, and using it afterwards raises `RuntimeError`. Objects you pull *off* an event (`event.device`, `event.seat`) are safe to keep — copy out `event.pointer_event` and friends rather than the event. -- **`frame()` or nothing happens.** Events queue up until a `frame()` commits - them. +- **`frame()` or the input is lost.** Events queue up until a `frame()` commits + them, and queued events that are never framed are dropped without an + exception or a log line. The one exception is a chain that ends in + `stop_emulating()`: libei frames what is queued, delivers it, and logs + `Bug: ei_device_stop_emulating: missing call to ei_device_frame()` at error + level. Measured against libei 1.2.1 and 1.6.0; don't rely on it. - **`bind()` needs at least one capability.** Binding an empty set sends nothing, so the device you are waiting for never arrives; this raises `ValueError` rather than hanging. @@ -341,20 +353,22 @@ All four, with working code: - **One seat can resume several devices.** Bind both `POINTER` and `POINTER_ABSOLUTE` and GNOME gives you two, relative first. Taking whichever resumes first is a coin flip — select on `device.capabilities` - instead. Sending an event the device lacks the capability for is silently - ignored, which makes this look like the injection simply not working. + instead. Sending an event the device lacks the capability for is dropped with + no exception — libei only logs an error-level `Bug: ... device is not a + keyboard` line — which makes this look like the injection simply not working. - **Read the accessor that matches the event type.** `event.key_event` on a `POINTER_MOTION` event raises `TypeError` naming both types. libei itself would have returned `KeyEvent(key=0, is_press=False)` — a real-looking - value — while logging a `Bug:` line the caller never sees, so branch on - `event_type` first. `TOUCH_UP` has its own `touch_up_event`, since it + value — and raised nothing, only logging a `Bug:` line at error level, so + branch on `event_type` first. `TOUCH_UP` has its own `touch_up_event`, since it carries no coordinates. - **`GESTURES` and `STYLUS` are not in any released libei.** They match upstream `main` and are here ready for it, but 1.6.0's capability enum stops at `TEXT`. Binding them against a shipping library silently does nothing — no error, no device, no events. -Nearly all of these fail *silently*, which is why +Nearly all of these fail without raising — some only log an error-level `Bug:` +line, some not even that — which is why [docs/troubleshooting.md](docs/troubleshooting.md) is a checklist rather than a list of error messages. Start there when nothing happens. diff --git a/docs/developers/verification.md b/docs/developers/verification.md index 94398f0..5bcf5b9 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.6.0`) and the API is not frozen — expect renames +The package is beta (`0.6.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. @@ -79,7 +79,30 @@ By hand: and 1.6 features gating themselves out. - CI repeats the 1.2.1 run on Python 3.10–3.13, so the 1.0.0 core floor is exercised on a real old build rather than asserted. -- **1.0–1.1 and 1.3 have never been run against.** +- Re-run 2026-09-30 against **1.6.0** on Fedora 45 (libei 1.6.0-3, under Python + 3.15rc2) and against Ubuntu 24.04's **1.2.1** in a container: the full suite + passes on both, the 1.4 and 1.6 features gating themselves out on 1.2.1. +- **1.0–1.1 and 1.3 have never been run against** -- and neither has 1.4 or 1.5 + at runtime. What they have had is the header check below. + +### Checked against the headers + +`tests/test_abi.py` compares every bound function's argument count, argument +classes and return class (pointer, 4-byte int, 8-byte int, double, bool, void) +with the upstream prototype, and every Python enum member's value with the C +enumerator. It needs the headers, so it runs only when `LIBEI_SOURCE_DIR` names +an upstream checkout (or an installed `libei-dev` provides them). Run on +2026-09-30 against the public headers of **1.0.0, 1.2.1, 1.4.0, 1.5.0 and +1.6.0**, with the installed 1.6.0 and 1.2.1 libraries checked for every +declared export: clean on all five once six declarations were marked with the +release that added them (touch cancellation and `pong_get_ping` on both sides +in 1.4, `eis_backend_socket_get_client_pid` in 1.5). They had no marker, so the +version each one needs was missing from the source -- an omission that cost +nothing on 1.6 and would have presented as an unexplained missing symbol on an +older library. + +There are no `ctypes.Structure` bindings, so there is no layout to verify; +every object is an opaque pointer and every value crosses as a scalar. A separate CI job installs the package with no native libraries at all and imports it, which is the property the lazy loader exists to provide. diff --git a/docs/getting-started.md b/docs/getting-started.md index f7f5bf9..4083f8c 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -37,9 +37,14 @@ them as one logical hardware event**: device.start_emulating().pointer_motion(5, 0).frame().stop_emulating() ``` -Forget `frame()` and nothing happens. No exception, no warning, no movement — -which is the single most common reason a first attempt appears to do nothing -at all. Each method returns the device, so they chain. +Forget `frame()` and the motion is usually lost: queued events that are never +framed go nowhere, with no exception, no warning and no movement — the most +common reason a first attempt appears to do nothing at all. The one exception +is a chain that ends in `stop_emulating()`, as above: libei frames what is +queued for you, the pointer moves, and it logs an error-level +`Bug: ei_device_stop_emulating: missing call to ei_device_frame()`. Do not rely +on that; call `frame()` and the log stays quiet. Each method returns the +device, so they chain. ## 3. The five words you need diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 370d99c..22c0e65 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -10,7 +10,10 @@ error messages. Work down it in order. The first three account for most cases. 1. **Did you call `frame()`?** Events queue until a frame commits them. - Without one, nothing is ever sent. No exception, no warning. + Without one they are never sent, with no exception and no warning — unless + you then called `stop_emulating()`, when libei frames them itself and logs + `Bug: ei_device_stop_emulating: missing call to ei_device_frame()` at error + level. If you see that line, add the `frame()`. 2. **Did you wait for `DEVICE_RESUMED`, not `DEVICE_ADDED`?** A device arrives paused. libei calls sending events before it resumes "a client bug", and diff --git a/pyproject.toml b/pyproject.toml index 7a32dd7..a5f408c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta" [project] name = "python-libei" -version = "0.6.0" -description = "Inject and receive input on Wayland from Python: ctypes bindings for libei, libeis and liboeffis" +version = "0.6.1" +description = "Inject, receive and capture input on Wayland from Python: ctypes bindings for libei, libeis and liboeffis, plus the RemoteDesktop and InputCapture portals" readme = "README.md" license = "MIT" requires-python = ">=3.10" @@ -18,6 +18,8 @@ keywords = [ "input", "input-emulation", "emulated-input", + "input-capture", + "eis", "portal", "xdg-desktop-portal", "remote-desktop", @@ -31,6 +33,7 @@ classifiers = [ "Intended Audience :: Developers", "Operating System :: POSIX :: BSD :: FreeBSD", "Operating System :: POSIX :: Linux", + "Operating System :: POSIX", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.10", @@ -62,6 +65,8 @@ dev = ["pytest>=7", "ruff>=0.6", "mypy>=1.11"] homepage = "https://github.com/ctrondlp/python-libei" repository = "https://github.com/ctrondlp/python-libei" issues = "https://github.com/ctrondlp/python-libei/issues" +documentation = "https://github.com/ctrondlp/python-libei/tree/main/docs" +pyguitest = "https://github.com/ctrondlp/pyguitest" changelog = "https://github.com/ctrondlp/python-libei/blob/main/CHANGELOG.md" [tool.setuptools.packages.find] diff --git a/src/libei/__init__.py b/src/libei/__init__.py index 5ce9336..9a48a72 100644 --- a/src/libei/__init__.py +++ b/src/libei/__init__.py @@ -31,6 +31,6 @@ Beta: the API is not frozen. """ -__version__ = "0.6.0" +__version__ = "0.6.1" __all__ = ["__version__"] diff --git a/src/libei/_capi/libei.py b/src/libei/_capi/libei.py index 151c3be..e6255a4 100644 --- a/src/libei/_capi/libei.py +++ b/src/libei/_capi/libei.py @@ -128,7 +128,7 @@ event_touch_get_id = lib.function("ei_event_touch_get_id", (c_void_p,), c_uint32) event_touch_get_x = lib.function("ei_event_touch_get_x", (c_void_p,), c_double) event_touch_get_y = lib.function("ei_event_touch_get_y", (c_void_p,), c_double) -event_touch_get_is_cancel = lib.function( +event_touch_get_is_cancel = lib.function( # libei 1.4+ "ei_event_touch_get_is_cancel", (c_void_p,), c_bool ) event_text_get_utf8 = lib.function( # libei 1.6+ @@ -141,7 +141,9 @@ "ei_event_text_get_keysym_is_press", (c_void_p,), c_bool ) # Borrowed reference -- the event still owns it, so wrap() rather than adopt(). -event_pong_get_ping = lib.function("ei_event_pong_get_ping", (c_void_p,), c_void_p) +event_pong_get_ping = lib.function( # libei 1.4+ + "ei_event_pong_get_ping", (c_void_p,), c_void_p +) device_ref = lib.function("ei_device_ref", (c_void_p,), c_void_p) device_unref = lib.function("ei_device_unref", (c_void_p,), c_void_p) @@ -236,7 +238,7 @@ touch_down = lib.function("ei_touch_down", (c_void_p, c_double, c_double), None) touch_motion = lib.function("ei_touch_motion", (c_void_p, c_double, c_double), None) touch_up = lib.function("ei_touch_up", (c_void_p,), None) -touch_cancel = lib.function("ei_touch_cancel", (c_void_p,), None) +touch_cancel = lib.function("ei_touch_cancel", (c_void_p,), None) # libei 1.4+ # ei_new_ping() returns an owned reference; ei_ping() then triggers the round # trip that comes back as an EI_EVENT_PONG. diff --git a/src/libei/_capi/libeis.py b/src/libei/_capi/libeis.py index 0562bfd..223b263 100644 --- a/src/libei/_capi/libeis.py +++ b/src/libei/_capi/libeis.py @@ -104,7 +104,7 @@ event_touch_get_id = lib.function("eis_event_touch_get_id", (c_void_p,), c_uint32) event_touch_get_x = lib.function("eis_event_touch_get_x", (c_void_p,), c_double) event_touch_get_y = lib.function("eis_event_touch_get_y", (c_void_p,), c_double) -event_touch_get_is_cancel = lib.function( +event_touch_get_is_cancel = lib.function( # libei 1.4+ "eis_event_touch_get_is_cancel", (c_void_p,), c_bool ) event_text_get_utf8 = lib.function( # libei 1.6+ @@ -117,14 +117,16 @@ "eis_event_text_get_keysym_is_press", (c_void_p,), c_bool ) # Borrowed reference -- the event still owns it, so wrap() rather than adopt(). -event_pong_get_ping = lib.function("eis_event_pong_get_ping", (c_void_p,), c_void_p) +event_pong_get_ping = lib.function( # libei 1.4+ + "eis_event_pong_get_ping", (c_void_p,), c_void_p +) client_ref = lib.function("eis_client_ref", (c_void_p,), c_void_p) client_unref = lib.function("eis_client_unref", (c_void_p,), c_void_p) client_is_sender = lib.function("eis_client_is_sender", (c_void_p,), c_bool) # pid_t, i.e. a 32-bit signed int on Linux. Socket backend only, and # negative errno on failure. -backend_socket_get_client_pid = lib.function( +backend_socket_get_client_pid = lib.function( # libei 1.5+ "eis_backend_socket_get_client_pid", (c_void_p,), c_int32 ) client_get_name = lib.function("eis_client_get_name", (c_void_p,), c_char_p) @@ -277,7 +279,7 @@ touch_down = lib.function("eis_touch_down", (c_void_p, c_double, c_double), None) touch_motion = lib.function("eis_touch_motion", (c_void_p, c_double, c_double), None) touch_up = lib.function("eis_touch_up", (c_void_p,), None) -touch_cancel = lib.function("eis_touch_cancel", (c_void_p,), None) +touch_cancel = lib.function("eis_touch_cancel", (c_void_p,), None) # libei 1.4+ ping = lib.function("eis_ping", (c_void_p,), None) # libei 1.4+ ping_get_id = lib.function("eis_ping_get_id", (c_void_p,), c_uint64) # libei 1.4+ diff --git a/src/libei/_capi/loader.py b/src/libei/_capi/loader.py index a3c421b..94695e7 100644 --- a/src/libei/_capi/loader.py +++ b/src/libei/_capi/loader.py @@ -30,6 +30,7 @@ def __init__(self, soname: str) -> None: self._lib: ctypes.CDLL | None = None self._load_error: OSError | None = None self._lock = threading.Lock() + self._declared: dict[str, tuple[tuple[type, ...], type | None]] = {} def _ensure_loaded(self) -> ctypes.CDLL: """Return the opened library, opening it on first call. @@ -75,6 +76,21 @@ def is_available(self) -> bool: return False return True + @property + def soname(self) -> str: + """The shared library this binds, as it is passed to ``dlopen``.""" + return self._soname + + @property + def declared(self) -> dict[str, tuple[tuple[type, ...], type | None]]: + """Every function bound so far: C name -> (argtypes, restype). + + Read by the ABI tests, which compare it with the library's exports and + with the upstream headers. Declaring a binding records it here and does + nothing else -- the library is still not opened until a call. + """ + return dict(self._declared) + def function( self, name: str, @@ -94,6 +110,7 @@ def function( # the dict is chosen only because "absent from the dict" already # means "not resolved yet", with no None sentinel to confuse with a # legitimately-None value. + self._declared[name] = (tuple(argtypes), restype) cache: dict[str, Any] = {} def call(*args: Any) -> Any: @@ -113,7 +130,23 @@ def call(*args: Any) -> Any: bound.argtypes = list(argtypes) bound.restype = restype cache["f"] = bound - return bound(*args) + try: + return bound(*args) + except ctypes.ArgumentError: + # ctypes turns *any* exception raised while converting an + # argument into an ArgumentError carrying only its text -- no + # __cause__, no __context__. For a released object that loses + # the RuntimeError its ``_as_parameter_`` raised, so a caller + # catching RuntimeError (as documented) would miss it. Ask the + # arguments again and re-raise the real one. + for arg in args: + try: + arg._as_parameter_ # noqa: B018 - evaluated for its error + except RuntimeError as released: + raise released from None + except AttributeError: + continue + raise call.__name__ = name return call diff --git a/src/libei/portal.py b/src/libei/portal.py index 4cacfc5..22ec6c4 100644 --- a/src/libei/portal.py +++ b/src/libei/portal.py @@ -1176,12 +1176,13 @@ class InputCaptureSession: about, and this cannot release on a caller's behalf during cleanup without risking racing a capture that only just started. - **Never live-tested.** Every other class in this module that talks to a - real portal carries a hand-verification note in its own docstring; this - one does not, because verifying it means a developer clicking through - the consent dialog *and* accepting that their pointer will be diverted - away from their own desktop for the length of the test -- not something - to trigger without asking first, unlike everything else here. Designed + **Only half live-tested.** The negotiation -- consent dialog, EIS fd, + zones, ``Session.Close()`` -- was run against a real GNOME session on + libei's own hand-verification terms (see + ``docs/developers/verification.md``); the *capture* half never has been, + because verifying it means a developer accepting that their pointer will + be diverted away from their own desktop for the length of the test -- not + something to trigger without asking first, unlike everything else here. Designed against ``/usr/share/dbus-1/interfaces/org.freedesktop.portal. InputCapture.xml`` (the shipped portal spec, not the header alone) and unit-tested against a fake connection reproducing that spec's documented diff --git a/tests/test_abi.py b/tests/test_abi.py new file mode 100644 index 0000000..58b6eea --- /dev/null +++ b/tests/test_abi.py @@ -0,0 +1,496 @@ +"""The ctypes bindings checked against the real library and the real headers. + +Everything here binds C functions by hand, with no compiler in the loop, so a +wrong argument count, a wrong width or a wrong enum value is invisible until +the one call that crosses it -- and then it is a corrupted argument or a +process-level crash rather than a Python exception. The mocked suites cannot +see any of it, because a mock agrees with whatever the binding says. + +There are no ``ctypes.Structure`` bindings in this package (every object is an +opaque pointer, and values cross as scalars), so the layout risk is narrower +than "struct offsets": it is **names, argument types and enum values**. Those +are what is checked, two ways: + +* against the installed shared library -- every declared function must be + exported, unless its declaration is marked as needing a newer libei than the + one installed; +* against the upstream public headers -- every declared function's argument + count and each argument's and the return's size class (pointer, 4-byte int, + 8-byte int, double, bool, void) must match the prototype, and every Python + enum member's value must match the C enumerator of the same name. + +The header half needs the headers, which distributions ship only in a -dev +package and which differ by release. Point ``LIBEI_SOURCE_DIR`` at an upstream +checkout or tarball (the directory holding ``meson.build`` and ``src/``) to run +it; with nothing set it looks for an installed ``libei-1.0`` include directory +and otherwise skips. Running it once per libei release is the version matrix: + + for v in 1.0.0 1.2.1 1.4.0 1.6.0; do + LIBEI_SOURCE_DIR=libei-$v pytest tests/test_abi.py + done +""" + +from __future__ import annotations + +import ctypes +import enum +import os +import re +import sys +from pathlib import Path + +import pytest + +from libei import ei, eis, oeffis +from libei._capi import libei as c_libei +from libei._capi import libeis as c_libeis +from libei._capi import liboeffis as c_liboeffis + +_LIBRARIES = { + "ei_": c_libei.lib, + "eis_": c_libeis.lib, + "oeffis_": c_liboeffis.lib, +} +_CAPI_SOURCES = { + "ei_": Path(c_libei.__file__), + "eis_": Path(c_libeis.__file__), + "oeffis_": Path(c_liboeffis.__file__), +} +_HEADER_FILES = {"ei_": "libei.h", "eis_": "libeis.h", "oeffis_": "liboeffis.h"} + + +# -- which declarations are marked as needing a newer libei ------------------ + + +def _version(text: str) -> tuple[int, ...]: + return tuple(int(part) for part in text.split(".")) + + +def _marked_versions(prefix: str) -> dict[str, tuple[int, ...]]: + """C name -> the libei version its declaration's comment says it needs. + + Read from the binding modules' own ``# libei 1.4+`` comments, on the + ``lib.function(`` line, so the marker and the declaration cannot drift + apart: a declaration with no marker is one every supported libei exports. + """ + marked: dict[str, tuple[int, ...]] = {} + lines = _CAPI_SOURCES[prefix].read_text(encoding="utf-8").splitlines() + for index, line in enumerate(lines): + if "lib.function(" not in line: + continue + found = re.search(r"#\s*libei\s+(\d+\.\d+(?:\.\d+)?)\+", line) + if not found: + continue + window = " ".join(lines[index : index + 2]) + name = re.search(r'"((?:ei|eis|oeffis)_\w+)"', window) + assert name, f"no C name near {line!r}" + marked[name.group(1)] = _version(found.group(1)) + return marked + + +def _declared(prefix: str) -> dict[str, tuple[tuple[type, ...], type | None]]: + # Importing the binding modules declares everything; nothing is opened. + return _LIBRARIES[prefix].declared + + +# -- the installed library --------------------------------------------------- + + +def _installed_version(soname: str) -> tuple[int, ...] | None: + """The version in the loaded library's file name (``libei.so.1.6.0``).""" + try: + maps = Path("/proc/self/maps").read_text() + except OSError: + return None + stem = soname.split(".so")[0] + for line in maps.splitlines(): + found = re.search(rf"/{re.escape(stem)}\.so\.(\d+\.\d+\.\d+)$", line) + if found: + return _version(found.group(1)) + return None + + +@pytest.mark.parametrize("prefix", sorted(_LIBRARIES)) +def test_every_declared_function_is_exported_by_the_installed_library( + prefix: str, +) -> None: + lib = _LIBRARIES[prefix] + if not lib.is_available(): + pytest.skip(f"{lib.soname} is not installed") + handle = lib._ensure_loaded() + marked = _marked_versions(prefix) + installed = _installed_version(lib.soname) + + missing = sorted(n for n in _declared(prefix) if not hasattr(handle, n)) + unmarked = [n for n in missing if n not in marked] + assert not unmarked, ( + f"{lib.soname} does not export {unmarked}, and none of them is marked as " + "needing a newer libei -- a misspelt name, or a missing version marker" + ) + if installed is not None: + # The other direction: a marker that says 1.4+ on a 1.6 library is a + # promise the library has to keep. + overdue = [n for n in missing if marked[n] <= installed] + assert not overdue, ( + f"{overdue} are marked as needing libei <= {installed} " + "yet this library lacks them" + ) + + +def test_the_marked_functions_really_are_absent_from_a_library_that_predates_them() -> ( + None +): + # Pins the marker comments to reality in the direction that matters on an + # old library: where libei is older than a marker, the function is missing + # and the binding says so by name rather than crashing. + if not c_libei.lib.is_available(): + pytest.skip("libei is not installed") + installed = _installed_version(c_libei.lib.soname) + if installed is None: + pytest.skip("cannot read the installed libei version here") + handle = c_libei.lib._ensure_loaded() + for name, needs in _marked_versions("ei_").items(): + if needs > installed: + assert not hasattr(handle, name), f"{name} is present on libei {installed}" + + +# -- the upstream headers ---------------------------------------------------- + + +def _header_dir() -> tuple[Path, tuple[int, ...] | None] | None: + configured = os.environ.get("LIBEI_SOURCE_DIR") + if configured: + root = Path(configured) + meson = root / "meson.build" + version = None + if meson.is_file(): + found = re.search(r"version:\s*'(\d+\.\d+\.\d+)'", meson.read_text()) + version = _version(found.group(1)) if found else None + return root / "src", version + for candidate in ("/usr/include/libei-1.0", "/usr/local/include/libei-1.0"): + if (Path(candidate) / "libei.h").is_file(): + return Path(candidate), None + return None + + +def _strip_comments(text: str) -> str: + text = re.sub(r"/\*.*?\*/", " ", text, flags=re.S) + return re.sub(r"//[^\n]*", " ", text) + + +_PROTOTYPE = re.compile( + r"(?m)^[ \t]*((?:const\s+|struct\s+|enum\s+|unsigned\s+)*[A-Za-z_]\w*[\s\*]*?)" + r"[ \t]*\n?[ \t]*\b((?:ei|eis|oeffis)_\w+)\s*\(([^()]*)\)\s*" + r"(?:__attribute__\(\([^;]*?\)\)|_\w+_(?:\([^)]*\))?)?\s*;" +) + + +def _size_class(ctype: str) -> str: + """Collapse a C type to what the calling convention sees.""" + ctype = " ".join(ctype.replace("const", " ").split()) + if "*" in ctype: + return "ptr" + if ctype == "void": + return "void" + if ctype == "bool": + return "bool" + if ctype == "double": + return "f64" + if ctype in ("uint64_t", "int64_t"): + return "i8" + if ctype in ("size_t", "ssize_t", "uintptr_t"): + # Pointer-sized, not fixed-width: 4 bytes on a 32-bit build. + return {4: "i4", 8: "i8"}[ctypes.sizeof(ctypes.c_size_t)] + if ctype.startswith("enum ") or ctype in ( + "int", + "uint32_t", + "int32_t", + "unsigned", + "unsigned int", + "pid_t", + "uid_t", + "gid_t", + ): + return "i4" + if ctype.startswith(("ei_", "eis_", "oeffis_")): + # A typedef'd callback (ei_log_handler, ei_clock_now_func). + return "ptr" + raise AssertionError(f"unclassified C type {ctype!r}") + + +def _ctypes_class(ctype: type | None) -> str: + if ctype is None: + return "void" + if ctype in (ctypes.c_void_p, ctypes.c_char_p) or isinstance( + ctype, type(ctypes.POINTER(ctypes.c_int)) + ): + return "ptr" + if isinstance(ctype, type) and issubclass(ctype, ctypes._CFuncPtr): # type: ignore[attr-defined] + return "ptr" + if ctype is ctypes.c_bool: + return "bool" + if ctype is ctypes.c_double: + return "f64" + size = ctypes.sizeof(ctype) # type: ignore[arg-type] + return {4: "i4", 8: "i8"}[size] + + +def _prototypes(prefix: str, directory: Path) -> dict[str, tuple[str, list[str], bool]]: + """C name -> (return class, fixed argument classes, is variadic).""" + text = _strip_comments(_header_text(directory, prefix)) + found: dict[str, tuple[str, list[str], bool]] = {} + for match in _PROTOTYPE.finditer(text): + returns, name, params = match.group(1), match.group(2), match.group(3) + if not name.startswith(prefix): + continue + params = " ".join(params.split()) + variadic = params.endswith("...") + pieces = [p.strip() for p in params.split(",") if p.strip() not in ("", "...")] + if pieces == ["void"]: + pieces = [] + classes = [] + for piece in pieces: + if "*" in piece: + classes.append("ptr") + continue + tokens = piece.replace("const", " ").split() + # `enum tag` alone is an unnamed parameter; `enum tag name` or + # `uint32_t name` carries one, which is not part of the type. + unnamed = tokens[0] in ("enum", "struct") and len(tokens) == 2 + if len(tokens) >= 2 and not unnamed: + tokens = tokens[:-1] + classes.append(_size_class(" ".join(tokens))) + found[name] = (_size_class(returns), classes, variadic) + return found + + +def _header_text(directory: Path, prefix: str) -> str: + """One public header's text, skipping where this install does not ship it. + + Distributions split them: Ubuntu's libei-dev has libei.h and libeis.h, and + liboeffis.h arrives with liboeffis-dev. + """ + path = directory / _HEADER_FILES[prefix] + if not path.is_file(): + pytest.skip(f"{path} is not installed") + return path.read_text() + + +@pytest.fixture(scope="module") +def headers() -> tuple[Path, tuple[int, ...] | None]: + located = _header_dir() + if located is None: + pytest.skip( + "no libei headers: set LIBEI_SOURCE_DIR to an upstream checkout " + "or install libei-devel" + ) + return located + + +@pytest.mark.parametrize("prefix", sorted(_LIBRARIES)) +def test_every_declared_function_matches_its_upstream_prototype( + prefix: str, headers: tuple[Path, tuple[int, ...] | None] +) -> None: + directory, version = headers + prototypes = _prototypes(prefix, directory) + assert len(prototypes) > 5, f"parsed almost nothing from {directory}" + marked = _marked_versions(prefix) + + problems: list[str] = [] + for name, (argtypes, restype) in _declared(prefix).items(): + if name not in prototypes: + # Legitimate only where the header predates the function -- or is of + # a version nothing here can read (an installed -dev package). + if name in marked and (version is None or marked[name] > version): + continue + problems.append(f"{name}: no prototype in {_HEADER_FILES[prefix]}") + continue + returns, params, variadic = prototypes[name] + declared_args = [_ctypes_class(a) for a in argtypes] + if variadic: + # Only the fixed prefix is declared: the trailing arguments go + # through ctypes' default conversion. + params = params[: len(declared_args)] + if declared_args != params: + problems.append(f"{name}: arguments {declared_args}, header says {params}") + if _ctypes_class(restype) != returns: + problems.append( + f"{name}: returns {_ctypes_class(restype)}, header says {returns}" + ) + assert not problems, "\n".join(problems) + + +# -- enums ------------------------------------------------------------------- + +# Python enum -> (C enum tag, prefix to strip from its enumerators). +_ENUMS: dict[str, tuple[type[enum.IntEnum] | type[enum.IntFlag], str, str, str]] = { + "ei.EventType": (ei.EventType, "ei_", "ei_event_type", "EI_EVENT_"), + "ei.DeviceCapability": ( + ei.DeviceCapability, + "ei_", + "ei_device_capability", + "EI_DEVICE_CAP_", + ), + "ei.DeviceType": (ei.DeviceType, "ei_", "ei_device_type", "EI_DEVICE_TYPE_"), + "ei.KeymapType": (ei.KeymapType, "ei_", "ei_keymap_type", "EI_KEYMAP_TYPE_"), + "ei._LogPriority": (ei._LogPriority, "ei_", "ei_log_priority", "EI_LOG_PRIORITY_"), + "eis.EventType": (eis.EventType, "eis_", "eis_event_type", "EIS_EVENT_"), + "eis.DeviceCapability": ( + eis.DeviceCapability, + "eis_", + "eis_device_capability", + "EIS_DEVICE_CAP_", + ), + "eis.DeviceType": (eis.DeviceType, "eis_", "eis_device_type", "EIS_DEVICE_TYPE_"), + "eis.KeymapType": (eis.KeymapType, "eis_", "eis_keymap_type", "EIS_KEYMAP_TYPE_"), + "eis._LogPriority": ( + eis._LogPriority, + "eis_", + "eis_log_priority", + "EIS_LOG_PRIORITY_", + ), + "eis.Flag": (eis.Flag, "eis_", "eis_flag", "EIS_FLAG_"), + "oeffis.DeviceType": ( + oeffis.DeviceType, + "oeffis_", + "oeffis_device", + "OEFFIS_DEVICE_", + ), + "oeffis._EventType": ( + oeffis._EventType, + "oeffis_", + "oeffis_event_type", + "OEFFIS_EVENT_", + ), +} + +# Members the Python enums carry that no released header has yet, on purpose +# (see the comments on each enum): they track upstream's main branch. +_AHEAD_OF_RELEASES = { + "ei.EventType": { + "SWIPE_BEGIN", + "SWIPE_UPDATE", + "SWIPE_END", + "SWIPE_ABORTED", + "PINCH_BEGIN", + "PINCH_UPDATE", + "PINCH_END", + "PINCH_ABORTED", + "HOLD_BEGIN", + "HOLD_END", + "HOLD_ABORTED", + "STYLUS_PROXIMITY_IN", + "STYLUS_PROXIMITY_OUT", + "STYLUS_ERASE_START", + "STYLUS_ERASE_STOP", + "STYLUS_TIP_DOWN", + "STYLUS_TIP_UP", + "STYLUS_AXIS", + }, + "ei.DeviceCapability": {"GESTURES", "STYLUS"}, +} + + +def _c_enums(text: str) -> dict[str, dict[str, int]]: + """Every ``enum tag { A = 1, B, ... }`` in the header, evaluated.""" + text = _strip_comments(text) + result: dict[str, dict[str, int]] = {} + for match in re.finditer(r"enum\s+(\w+)\s*\{([^}]*)\}", text): + tag, body = match.group(1), match.group(2) + values: dict[str, int] = {} + next_value = 0 + for item in body.split(","): + item = item.strip() + if not item: + continue + if "=" in item: + name, expression = (part.strip() for part in item.split("=", 1)) + next_value = eval( # noqa: S307 - header constants only + expression, {"__builtins__": {}}, dict(values) + ) + else: + name = item + values[name] = next_value + next_value += 1 + result[tag] = values + return result + + +@pytest.mark.parametrize("label", sorted(_ENUMS)) +def test_every_enum_member_has_the_value_the_header_gives_it( + label: str, headers: tuple[Path, tuple[int, ...] | None] +) -> None: + directory, _ = headers + python_enum, file_prefix, tag, prefix = _ENUMS[label] + c_values = _c_enums(_header_text(directory, file_prefix)).get(tag) + if c_values is None: + pytest.skip(f"this libei's header has no enum {tag}") + + wrong, absent = [], [] + for member in python_enum.__members__.values(): + name = str(member.name) + if name in _AHEAD_OF_RELEASES.get(label, set()): + assert prefix + name not in c_values, ( + f"{name} is now in a released header: it no longer belongs in the " + "ahead-of-releases list" + ) + continue + if prefix + name not in c_values: + absent.append(name) + elif c_values[prefix + name] != member.value: + wrong.append( + f"{name}: {member.value}, header says {c_values[prefix + name]}" + ) + # A member the header does not have is only legitimate where the header is + # older than the member -- the test cannot tell which, so it reports them + # rather than asserting, and the wrong values are what fail. + assert not wrong, "\n".join(wrong) + assert len(absent) < len(python_enum.__members__), ( + f"none of {label}'s members were found under {prefix}: wrong prefix?" + ) + + +@pytest.mark.parametrize("label", sorted(_ENUMS)) +def test_every_header_enumerator_is_covered_by_the_python_enum( + label: str, headers: tuple[Path, tuple[int, ...] | None] +) -> None: + """A value libei can send must not arrive as a bare, unnamed int.""" + directory, _ = headers + python_enum, file_prefix, tag, prefix = _ENUMS[label] + c_values = _c_enums(_header_text(directory, file_prefix)).get(tag) + if c_values is None: + pytest.skip(f"this libei's header has no enum {tag}") + known = set(python_enum.__members__) + uncovered = sorted( + name[len(prefix) :] + for name in c_values + if name.startswith(prefix) and name[len(prefix) :] not in known + ) + assert not uncovered, f"{label} lacks {uncovered}" + + +def test_the_header_parser_reads_a_prototype_and_an_enum() -> None: + # The parser is the instrument the two tests above rely on; if it silently + # returns nothing they pass vacuously, so it is pinned on a known text. + sample = """ + /** doc */ + struct ei * + ei_new_sender(void *user_data); + void + ei_seat_bind_capabilities(struct ei_seat *seat, ...) __attribute__((sentinel)); + uint64_t + ei_event_get_time(struct ei_event *event); + enum e { E_A = 1, E_B = (1 << 3), E_C }; + """ + text = _strip_comments(sample) + names = {m.group(2): m for m in _PROTOTYPE.finditer(text)} + assert set(names) == { + "ei_new_sender", + "ei_seat_bind_capabilities", + "ei_event_get_time", + } + assert _c_enums(sample)["e"] == {"E_A": 1, "E_B": 8, "E_C": 9} + assert _size_class("uint64_t") == "i8" + assert _size_class("const char *") == "ptr" + assert _size_class("enum ei_event_type") == "i4" + assert sys.version_info >= (3, 9) diff --git a/tests/test_event_accessors.py b/tests/test_event_accessors.py new file mode 100644 index 0000000..32fe198 --- /dev/null +++ b/tests/test_event_accessors.py @@ -0,0 +1,177 @@ +"""Every event accessor against every event type, on both sides of the protocol. + +libei's own accessors do not report a type mismatch: reading ``key_event`` off a +pointer event returns ``KeyEvent(key=0, is_press=False)``, which is +indistinguishable from a real key 0, and some accessors make libei log an +internal "Bug:" line while others say nothing. ``Event._require`` turns that +into a ``TypeError`` before the C call. The existing tests pin one wrong type +per library; this pins all of them, and -- because the accessor list is read +from the source rather than typed out here -- pins any accessor added later, +including one added *without* the guard. + +The C accessors are replaced with recorders, so nothing here needs libei +installed and a guard that let a wrong type through would show up as a C call +that should never have happened. +""" + +from __future__ import annotations + +import inspect +import re +from collections.abc import Callable +from typing import Any + +import pytest + +from libei import _capi, ei, eis + + +@pytest.fixture(autouse=True) +def _no_native_refcounting(monkeypatch: pytest.MonkeyPatch) -> None: + """Fake pointers must never reach a real ``*_unref`` at garbage collection. + + Same isolation as test_ei_objects.py: these tests wrap pointers like 0x1 + that no library returned, so where libei is installed a finalizer calling + the real unref would dereference garbage. Every CObject subclass on both + sides gets its ref/unref stubbed and a fresh instance cache. + """ + from libei._cobject import CObject + + for module in (ei, eis): + for cls in vars(module).values(): + if ( + isinstance(cls, type) + and issubclass(cls, CObject) + and cls is not CObject + ): + monkeypatch.setattr(cls, "_instances", type(cls._instances)()) + if cls._ref_func is not None: + monkeypatch.setattr(cls, "_ref_func", staticmethod(lambda p: None)) + if cls._unref_func is not None: + monkeypatch.setattr( + cls, "_unref_func", staticmethod(lambda p: None) + ) + + +# Properties on Event that read no type-specific payload, so need no guard. +_UNGUARDED = {"event_type", "time", "device", "seat", "client"} + +_SIDES: dict[str, Any] = { + "ei": (ei, _capi.libei), + "eis": (eis, _capi.libeis), +} + + +def _accessors(module: Any) -> dict[str, tuple[str, ...]]: + """Property name -> the event types its ``_require`` call allows.""" + found: dict[str, tuple[str, ...]] = {} + for name, member in inspect.getmembers(module.Event): + if name.startswith("_") or not isinstance(member, property): + continue + if name in _UNGUARDED: + continue + source = inspect.getsource(member.fget) # type: ignore[arg-type] + guard = re.search(r"self\._require\(\s*\"[\w]+\"\s*,([^)]*)\)", source) + found[name] = ( + tuple(re.findall(r"EventType\.(\w+)", guard.group(1))) if guard else () + ) + return found + + +@pytest.mark.parametrize("side", sorted(_SIDES)) +def test_every_payload_accessor_is_guarded(side: str) -> None: + module, _ = _SIDES[side] + unguarded = sorted(n for n, valid in _accessors(module).items() if not valid) + assert not unguarded, ( + f"{side}.Event.{unguarded} read a C payload with no _require() guard: the " + "wrong event type would return plausible zeros instead of raising" + ) + + +@pytest.mark.parametrize("side", sorted(_SIDES)) +def test_every_guard_names_event_types_that_exist(side: str) -> None: + module, _ = _SIDES[side] + for name, valid in _accessors(module).items(): + for type_name in valid: + assert hasattr(module.EventType, type_name), f"{side}.Event.{name}" + + +def _patch_c( + monkeypatch: pytest.MonkeyPatch, c_module: Any, event_type: int +) -> list[str]: + """Replace every bound C function; return the list its calls land in.""" + calls: list[str] = [] + + def recorder(name: str) -> Callable[..., int]: + def call(*_args: Any) -> int: + calls.append(name) + return 0 + + # The C name, so a later patch of the same module still finds it. + call.__name__ = name + return call + + for name in c_module.lib.declared: + python_name = next( + ( + attribute + for attribute, value in vars(c_module).items() + if getattr(value, "__name__", None) == name + ), + None, + ) + if python_name is not None: + monkeypatch.setattr(c_module, python_name, recorder(name)) + monkeypatch.setattr(c_module, "event_get_type", lambda _pointer: event_type) + return calls + + +@pytest.mark.parametrize("side", sorted(_SIDES)) +def test_a_wrong_event_type_raises_before_any_c_accessor_is_called( + side: str, monkeypatch: pytest.MonkeyPatch +) -> None: + module, c_module = _SIDES[side] + accessors = _accessors(module) + assert len(accessors) >= 8, "found almost no accessors: the discovery broke" + + wrong_combinations = 0 + for event_type in [*module.EventType, 0, 123456]: + value = int(event_type) + calls = _patch_c(monkeypatch, c_module, value) + event = module.Event.wrap(0x1) + assert event is not None + name_of = ( + event_type.name if isinstance(event_type, module.EventType) else str(value) + ) + for accessor, valid in accessors.items(): + if name_of in valid: + continue + calls.clear() + with pytest.raises(TypeError, match=f"Event.{accessor} is only valid for"): + getattr(event, accessor) + assert calls == [], ( + f"{side}.Event.{accessor} reached C ({calls}) for a {name_of} event" + ) + wrong_combinations += 1 + assert wrong_combinations > 100 + + +@pytest.mark.parametrize("side", sorted(_SIDES)) +def test_a_right_event_type_passes_the_guard( + side: str, monkeypatch: pytest.MonkeyPatch +) -> None: + module, c_module = _SIDES[side] + for accessor, valid in _accessors(module).items(): + for type_name in valid: + calls = _patch_c(monkeypatch, c_module, int(module.EventType[type_name])) + event = module.Event.wrap(0x1) + assert event is not None + try: + getattr(event, accessor) + except TypeError as exc: + assert "is only valid for" not in str(exc), ( + f"{side}.Event.{accessor} refused its own type {type_name}" + ) + except Exception: # noqa: BLE001 - what the fake C values make of it + pass + assert calls, f"{side}.Event.{accessor} never reached C for {type_name}" diff --git a/tests/test_integration_frame.py b/tests/test_integration_frame.py new file mode 100644 index 0000000..2a51a2f --- /dev/null +++ b/tests/test_integration_frame.py @@ -0,0 +1,104 @@ +"""What the real libei does with input that is queued but never framed. + +The docs used to say that forgetting ``frame()`` means nothing happens, with no +exception and no warning. That is a claim about libei, so it is checked against +libei rather than repeated -- and it was only half true. Measured on libei 1.2.1 +and 1.6.0 alike: + +============================= ================================================ +What the client does What the server sees +============================= ================================================ +motion, frame, stop the motion +motion, stop (no frame) the motion, in a FRAME libei adds itself, and an + ERROR log: "Bug: ei_device_stop_emulating: + missing call to ei_device_frame()" +motion, no frame, no stop nothing at all, and no log line +motion, not emulating nothing, and a "Bug: ... device is not emulating" +============================= ================================================ + +The framed control proves the harness can see a motion at all, so an empty +result in the others means something. +""" + +from __future__ import annotations + +import logging +import time +from collections.abc import Callable + +import pytest + +from conftest import requires_libei +from libei import ei, eis +from test_integration_extras import Pair + +pytestmark = [pytest.mark.integration, requires_libei] + +_SETTLE = 1.0 +"""Seconds to keep pumping after the client is done, so a late event would show.""" + + +def _run(send: Callable[[ei.Device], object]) -> list[eis.EventType | int]: + pair = Pair((eis.DeviceCapability.POINTER,)) + arrived: list[eis.EventType | int] = [] + sent_at: list[float] = [] + + def on_server_event(event: eis.Event) -> None: + arrived.append(event.event_type) + + def on_device(device: ei.Device) -> None: + send(device) + sent_at.append(time.monotonic()) + + pair.run( + lambda: bool(sent_at) and time.monotonic() - sent_at[0] > _SETTLE, + on_server_event=on_server_event, + on_device=on_device, + ) + return arrived + + +def _bug_lines(caplog: pytest.LogCaptureFixture) -> list[str]: + return [r.getMessage() for r in caplog.records if "Bug:" in r.getMessage()] + + +def test_a_framed_motion_reaches_the_server(caplog: pytest.LogCaptureFixture) -> None: + caplog.set_level(logging.DEBUG) + arrived = _run( + lambda d: d.start_emulating().pointer_motion(7, 3).frame().stop_emulating() + ) + assert eis.EventType.POINTER_MOTION in arrived + assert _bug_lines(caplog) == [] + + +def test_stopping_without_a_frame_is_framed_for_you_and_logged_as_a_bug( + caplog: pytest.LogCaptureFixture, +) -> None: + caplog.set_level(logging.DEBUG) + arrived = _run(lambda d: d.start_emulating().pointer_motion(7, 3).stop_emulating()) + assert eis.EventType.POINTER_MOTION in arrived + assert eis.EventType.FRAME in arrived + bugs = _bug_lines(caplog) + assert any("missing call to ei_device_frame" in line for line in bugs), bugs + # At ERROR, so Python's default last-resort handler prints it to stderr. + assert any( + r.levelno >= logging.ERROR and "frame" in r.getMessage() for r in caplog.records + ) + + +def test_a_motion_never_framed_or_stopped_is_dropped_silently( + caplog: pytest.LogCaptureFixture, +) -> None: + caplog.set_level(logging.DEBUG) + arrived = _run(lambda d: d.start_emulating().pointer_motion(7, 3)) + assert eis.EventType.POINTER_MOTION not in arrived + assert _bug_lines(caplog) == [], "libei now warns about this case: update the docs" + + +def test_a_motion_sent_while_not_emulating_is_dropped_and_logged( + caplog: pytest.LogCaptureFixture, +) -> None: + caplog.set_level(logging.DEBUG) + arrived = _run(lambda d: d.pointer_motion(7, 3).frame()) + assert eis.EventType.POINTER_MOTION not in arrived + assert any("not emulating" in line for line in _bug_lines(caplog)) diff --git a/tests/test_integration_lifetime.py b/tests/test_integration_lifetime.py new file mode 100644 index 0000000..a9fb165 --- /dev/null +++ b/tests/test_integration_lifetime.py @@ -0,0 +1,49 @@ +"""An event used after its loop iteration, through the real library. + +Each event is released as the loop moves on, and the docs promise a +``RuntimeError`` afterwards. test_ei_objects.py checks ``_as_parameter_`` in +isolation, which is not the path a caller takes: a real call converts its +arguments inside ctypes, and ctypes re-raises whatever that conversion raised as +``ctypes.ArgumentError`` carrying only the text. So the promise is checked here, +with a real event and a real C call. +""" + +from __future__ import annotations + +import select + +import pytest + +from conftest import requires_libei +from libei import ei, eis +from test_integration_extras import Pair + +pytestmark = [pytest.mark.integration, requires_libei] + + +def test_a_released_event_raises_runtime_error_from_a_real_call() -> None: + pair = Pair((eis.DeviceCapability.POINTER,)) + kept: list[eis.Event] = [] + + def on_server_event(event: eis.Event) -> None: + if event.event_type is eis.EventType.POINTER_MOTION: + kept.append(event) + + def on_device(device: ei.Device) -> None: + device.start_emulating().pointer_motion(7, 3).frame().stop_emulating() + + pair.run(lambda: bool(kept), on_server_event=on_server_event, on_device=on_device) + # The loop has moved on, so the event has been released. + if select.select([pair.server.fd], [], [], 0.2)[0]: + pair.server.dispatch() + list(pair.server.events) + + def event_type(event: eis.Event) -> object: + return event.event_type + + def pointer_event(event: eis.Event) -> object: + return event.pointer_event + + for read in (event_type, pointer_event): + with pytest.raises(RuntimeError, match="already been released"): + read(kept[0]) diff --git a/tests/test_loader.py b/tests/test_loader.py index 5427e70..8ae98ea 100644 --- a/tests/test_loader.py +++ b/tests/test_loader.py @@ -11,7 +11,8 @@ from __future__ import annotations -from ctypes import c_char_p, c_int, util +import sys +from ctypes import ArgumentError, c_char_p, c_int, c_void_p, util import pytest @@ -88,3 +89,110 @@ def test_two_lazy_libraries_are_independent() -> None: bad = LazyLibrary("this-library-definitely-does-not-exist.so.999") assert good.is_available() is True assert bad.is_available() is False + + +@_needs_libc +def test_a_missing_symbol_names_itself_and_leaves_the_rest_working() -> None: + # A library that loads but lacks a newer symbol (an old libei asked for a + # 1.6 function) must fail that one call, by name, and nothing else: the + # older functions keep working before and after, and asking again gives + # the same answer rather than a half-initialised state. + lib = LazyLibrary(_LIBC) + present = lib.function("abs", (c_int,), c_int) + absent = lib.function("symbol_added_in_a_newer_release", (c_int,), c_int) + + assert present(-3) == 3 + for _ in range(3): + with pytest.raises(LibraryNotFoundError) as caught: + absent(1) + assert "symbol_added_in_a_newer_release" in str(caught.value) + assert present(-4) == 4 + assert lib.is_available() is True + + +@_needs_libc +def test_a_missing_symbol_is_not_resolved_until_it_is_called() -> None: + lib = LazyLibrary(_LIBC) + absent = lib.function("symbol_added_in_a_newer_release", (c_int,), c_int) + # Declaring it, and calling something else, cost nothing and raised nothing. + assert lib.function("abs", (c_int,), c_int)(-1) == 1 + assert "symbol_added_in_a_newer_release" in lib.declared + with pytest.raises(LibraryNotFoundError): + absent(0) + + +def test_declarations_are_recorded_without_opening_the_library() -> None: + lib = LazyLibrary("this-library-definitely-does-not-exist.so.999") + lib.function("abs", (c_int,), c_int) + lib.function("puts", (c_char_p,), None) + assert lib.declared == {"abs": ((c_int,), c_int), "puts": ((c_char_p,), None)} + assert lib.soname == "this-library-definitely-does-not-exist.so.999" + # Only a call may fail; reading the registry must not have tried to load. + assert lib._lib is None and lib._load_error is None + + +@_needs_libc +def test_concurrent_first_calls_open_the_library_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The double-checked lock in _ensure_loaded is there for exactly this. + import ctypes + import threading + + opened: list[str] = [] + real = ctypes.CDLL + + def counting(name: str, *args: object, **kwargs: object) -> ctypes.CDLL: + opened.append(name) + return real(name, *args, **kwargs) # type: ignore[arg-type] + + monkeypatch.setattr(ctypes, "CDLL", counting) + lib = LazyLibrary(_LIBC) + abs_ = lib.function("abs", (c_int,), c_int) + start = threading.Barrier(8) + results: list[int] = [] + + def worker() -> None: + start.wait() + results.append(abs_(-5)) + + threads = [threading.Thread(target=worker) for _ in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert results == [5] * 8 + assert opened == [_LIBC] + + +class _Released: + """What a released CObject looks like to ctypes.""" + + @property + def _as_parameter_(self) -> int: + raise RuntimeError("Thing has already been released") + + +def _stand_in_library() -> str | None: + # msvcrt on Windows, where find_library("c") finds nothing: this test needs + # only *a* C function taking an int, and it is the one about ctypes itself. + return "msvcrt" if sys.platform == "win32" else _found_libc + + +def test_a_released_object_raises_runtime_error_not_ctypes_argument_error() -> None: + # ctypes wraps whatever _as_parameter_ raises in an ArgumentError that keeps + # only the message. The mocked suites never cross ctypes, so they passed + # while a real call with a released Event raised ArgumentError -- and the + # documented `except RuntimeError` missed it. + soname = _stand_in_library() + if soname is None: + pytest.skip("needs a real C library as a stand-in") + lib = LazyLibrary(soname) + abs_ = lib.function("abs", (c_void_p,), c_int) + with pytest.raises(RuntimeError, match="already been released"): + abs_(_Released()) + # An ordinary bad argument is still ctypes' own error, untouched. + with pytest.raises(ArgumentError): + abs_(object()) + # And a good call is unaffected. + assert abs_(0) == 0