diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 04fb7da..6584f1a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -79,6 +79,17 @@ jobs: - name: Type-check whole workspace for x86_64-pc-windows-gnu run: cargo check --workspace --all-targets --target x86_64-pc-windows-gnu + - name: Install cbindgen (pinned, generates the C header) + run: cargo install cbindgen --locked --version 0.29.4 + + # include/uda.h is generated from crates/uda-ffi by cbindgen; the Rust + # sources are the single source of truth. Regenerating here and diffing + # catches a Rust change whose header update was forgotten: this step + # fails until scripts/gen-header.sh has been run and its output + # committed. The version must stay in sync with scripts/gen-header.sh. + - name: Check the generated C header is up to date + run: ./scripts/gen-header.sh --check + # ========================================================================== # 3. Linux: unit tests, D-Bus mock fixtures, FFI build and Python example. # ========================================================================== @@ -112,6 +123,14 @@ jobs: - name: Test uda-ffi (C-ABI) run: cargo test --locked -p uda-ffi + # The generated header's numeric/typing contract (unsigned capability + # bits, no `UdaStatus` leaking into C) and the gen-header version gate, + # as C static asserts plus a stubbed-cbindgen run. Local regression + # script kept in CI so the guarantees never depend on someone running + # it by hand. + - name: Check the header's C-level contract + run: python3 -B scripts/test-header.py + - name: Build FFI shared library run: cargo build --locked -p uda-ffi @@ -180,10 +199,11 @@ jobs: # guard; these variables force UTF-8 for any child process too. PYTHONIOENCODING: utf-8 PYTHONUTF8: "1" - # `include/uda.h` is the single source of truth for the exported surface: - # every function it declares must be present in the DLL, so a missing - # `#[no_mangle]` fails the build. Hard-coding a symbol count here instead - # broke every release once Phase 2 added exports past the stale number. + # The generated `include/uda.h` is the reference for the exported + # surface: every function it declares must be present in the DLL, so a + # missing `#[no_mangle]` fails the build. Hard-coding a symbol count + # here instead broke every release once Phase 2 added exports past the + # stale number. run: python scripts/pe_exports.py target/debug/uda_ffi.dll --expect include/uda.h - name: Run Python example against the freshly built DLL @@ -259,12 +279,13 @@ jobs: sudo apt-get update sudo apt-get install -y zip - # `include/uda.h` is the source of truth for the exported surface. Both - # platforms are checked against it, so the expected symbol set can never - # drift from what the crate actually declares: a new `#[no_mangle]` - # export is picked up automatically, and a *missing* one fails the build. - # Hard-coding a symbol count here instead is what broke the release check - # once Phase 2 pushed the export list past the stale number. + # The generated `include/uda.h` is the reference for the exported + # surface. Both platforms are checked against it, so the expected symbol + # set can never drift from what the crate actually declares: a new + # `#[no_mangle]` export is picked up automatically, and a *missing* one + # fails the build. Hard-coding a symbol count here instead is what broke + # the release check once Phase 2 pushed the export list past the stale + # number. - name: Verify exported ABI symbols (Linux) run: | set -euo pipefail diff --git a/AGENTS.md b/AGENTS.md index 634b040..ffe530d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,11 +132,13 @@ Every code change must pass: 1. `cargo check --workspace --all-targets` 2. `./scripts/test-linux-mock.sh` 3. `cargo test -p uda-ffi` +4. `./scripts/gen-header.sh --check` (auto-installs the pinned cbindgen; the CI "Cross-Compile Hygiene" job runs the same gate) ### Verification Criteria 1. **Compilation Check:** `cargo check --workspace` must pass with zero warnings/errors. 2. **D-Bus Mock Tests:** Unit tests in `uda-platform-linux` must run inside `dbus-run-session` using `python3-dbusmock` fixtures. 3. **Cross-Compilation Hygiene:** The Linux agent must not break Windows compilation. Ensure all Windows code is gated behind `#[cfg(windows)]`. +4. **Header Sync:** If any C-ABI surface changed (exported function, signature, doc comment, constant), `include/uda.h` must be regenerated before committing. --- @@ -163,3 +165,4 @@ Every code change must pass: ``` 2. **Asynchronous Runtime:** When async is required (e.g., listening to D-Bus signals or registry events), use `tokio`. Provide synchronous wrapper methods where practical. 3. **Logging:** Use the `log` crate (`log::debug!`, `log::warn!`). Never use raw `println!` in library crates. +4. **Generated C Header:** `include/uda.h` is a build artifact generated by cbindgen (`crates/uda-ffi/cbindgen.toml`). The Rust sources are the single source of truth: exported function signatures **and their doc comments** live on the `#[no_mangle]` functions in `crates/uda-ffi/src/lib.rs`; every `UDA_*` constant and callback type lives in `crates/uda-ffi/src/abi.rs`. **NEVER edit `include/uda.h` by hand** - change the Rust side, run `./scripts/gen-header.sh`, and commit the regenerated header together with the Rust change. The cbindgen version is pinned in `scripts/gen-header.sh` and `.github/workflows/ci.yml`; bump it in both places in a dedicated, reviewed commit. diff --git a/CHANGELOG.md b/CHANGELOG.md index 59ace74..91964fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), > 对应 PR:交叉审查清单(issue #4,50 项)中 v0.2.1 未覆盖的 48 项全部在本节落地。 > Corresponds to the cross-review checklist (issue #4): the 48 findings not already > shipped in v0.2.1 all land in this section. +> 本节同时收录 cbindgen 生成 C 头文件(issue #6 / PR #7)带来的 ABI 契约收紧。 +> This section also covers the ABI-contract tightening from the cbindgen-generated +> C header (issue #6 / PR #7). ### ✨ Added @@ -34,6 +37,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 🛠️ **On the `unsafe extern "C"` FFI exports (compatibility note)**: nothing in this section flips an export's safety - every export that takes a raw pointer has been `unsafe extern "C"` since it was introduced (the tray, notification, accent-colour, media and session exports arrived that way with v0.2.0), and the new `uda_tray_capabilities` follows suit; the library has exactly eight plain `extern "C"` exports (the two message helpers, plus the tray / wakelock calls that take only numeric handles). The impact on callers, stated precisely: C callers are unaffected; Rust hosts that declare the functions in `extern "C" { ... }` blocks are unaffected **on every edition** (the definition-side `unsafe` keyword cannot break an extern-block declaration - block items already require the caller's own `unsafe` regardless); only a host consuming `uda-ffi` as an rlib sees an `unsafe` requirement on the pointer-taking exports, the same as since v0.2.0. The `unsafe` on pointer-taking exports is a sound classification, not a removable obstacle: a caller passing a dangling non-null pointer is UB, which a safe function cannot accept. The split is now pinned by the `export_safety_classification_is_pinned` test, so any future reclassification must update that list and the changelog deliberately. - 🛠️ **同步 API 桥的构建顺序**:`uda-platform-linux` 的 `run_async` 与 `uda-ffi` 的 `run_sync` 现在都是"先判定运行时上下文、后构建",环境运行时分支不再把runtime 搬去工作线程。 - 🛠️ **Sync-bridge build order**: `run_async` (`uda-platform-linux`) and `run_sync` (`uda-ffi`) both branch on the ambient runtime *before* building anything, so the nested branch no longer ships a runtime across threads. +- 🛠️ **C 头文件自动化生成**:`include/uda.h` 改为用 [cbindgen](https://github.com/mozilla/cbindgen) 从 `crates/uda-ffi` 的 Rust 源码生成([UniDesktop/SDK#6](https://github.com/UniDesktop/SDK/issues/6)),Rust 侧成为 C-ABI 签名、常量与文档的唯一事实源。 +- 🛠️ **Generated C header**: `include/uda.h` is now generated by [cbindgen](https://github.com/mozilla/cbindgen) from the Rust sources in `crates/uda-ffi` ([UniDesktop/SDK#6](https://github.com/UniDesktop/SDK/issues/6)), making the Rust side the single source of truth for C-ABI signatures, constants and documentation. + - 新增 `crates/uda-ffi/src/abi.rs`:全部 `UDA_*` 常量与托盘回调类型集中于此(顺带消除了 `lib.rs` 与 `error.rs` 之间的一份重复定义);头文件中的 API 文档全部合并进导出函数的 Rust doc comment。 + - A new `crates/uda-ffi/src/abi.rs` centralizes every `UDA_*` constant and tray callback type (also removing a duplicated definition between `lib.rs` and `error.rs`); the header's API documentation was folded into the Rust doc comments of the exported functions. + - 新增 `scripts/gen-header.sh`(支持 `--check`);CI 的 Cross-Compile Hygiene job 增加「重新生成 + diff」门禁,改了 Rust 侧忘记重新生成头文件会直接红灯。 + - A new `scripts/gen-header.sh` (with `--check`) adds a regenerate-and-diff gate to the Cross-Compile Hygiene CI job: a Rust change that forgets to regenerate the header now fails the build. + - **迁移本身不改变 ABI 签名与常量**:生成的 `include/uda.h` 逐项复刻此前的头文件——包括本版本先落地的 8 个 `UDA_TRAY_CAP_*`、3 个 `UDA_TRAY_SUPPORT_LEVEL_*` 常量与 `uda_tray_capabilities` / `uda_tray_support_level` / `uda_tray_support_reason` 三个导出;`scripts/header_symbols.py` 与 `pe_exports.py` 的「头文件 ↔ 动态库符号」校验保持不变。唯一的语义差异是下面 `uda_media_get_metadata` 的 NULL 回填,那是有意的行为修正,不在「签名与常量不变」的承诺范围内。 + - **The migration itself changes no ABI signatures or constants**: the generated `include/uda.h` reproduces the previous header item for item - including the eight `UDA_TRAY_CAP_*` and three `UDA_TRAY_SUPPORT_LEVEL_*` constants plus the `uda_tray_capabilities` / `uda_tray_support_level` / `uda_tray_support_reason` exports that landed earlier in this release; the `header_symbols.py` / `pe_exports.py` header-to-library symbol checks are unchanged. The one semantic difference is the `uda_media_get_metadata` NULL backfill below, which is a deliberate behaviour fix and therefore outside the "signatures and constants unchanged" promise. +- 🛠️ **`uda_media_get_metadata` 回填 NULL,`MediaMetadata` 区分「未发布」与「发布为空」**:未发布字段与「无播放器」现在稳定写回 NULL(时长 / 进度写 0,状态仍是 `UDA_OK`),与 `docs/internals/media_specs.md` 的 C-ABI 契约一致。此前 `MediaMetadata` 的字段是 `String`,C 侧根本无法表达「未发布」:本节前面按「空串即未发布」把空值折叠成 NULL,于是「播放器发布了一个空值」与「播放器没发布该字段」在 C-ABI 上不可区分。现在字符串字段改为 `Option`,Linux 上 `None` → NULL、`Some("")` → 空 C 串,两者可区分;Windows SMTC 线上没有「未发布」标记,空读取折叠为 `None`(即 NULL),可区分性仅 Linux 成立。因此「空串一律折叠为 NULL」的通用规则适用于壁纸路径、托盘降级原因等「空串没有独立语义」的导出,而媒体字段是其有意例外:只有未发布字段是 NULL。宿主在两个平台上都应把 NULL 当作「跳过该字段」;`uda_free_string(NULL)` 是空操作,三个出参可无条件释放。 +- 🛠️ **`uda_media_get_metadata` backfills NULL, and `MediaMetadata` tells "published empty" from "unpublished"**: unpublished fields and "no player" now reliably write NULL (duration / position write 0 and the status stays `UDA_OK`), matching the C-ABI contract in `docs/internals/media_specs.md`. `MediaMetadata`'s fields used to be `String`, which cannot express "unpublished" at all: the "empty means unpublished" rule earlier in this section folded every empty value to NULL, so "the player published an empty value" and "the player did not publish the field" were indistinguishable across the C ABI. The fields are now `Option`: on Linux `None` maps to NULL and `Some("")` to an empty C string, so the two cases differ; Windows SMTC has no "unpublished" marker on the wire, so an empty read folds to `None` (i.e. NULL) and the distinction holds on Linux only. The general "empty folds to NULL" rule therefore covers the exports where an empty string carries no separate meaning (a wallpaper path, a tray degradation reason), with the media fields the deliberate exception: only an unpublished field is NULL. A host must treat NULL as "skip this field" on both platforms; `uda_free_string(NULL)` is a no-op, so all three out-strings can be freed unconditionally. + +### ⚠️ Breaking + +- ⚠️ **`MediaMetadata` 字符串字段改为 `Option`(Rust API)**:`uda-core::media::MediaMetadata` 的 `title` / `artist` / `album` 由 `String` 变为 `Option`,`is_empty()` 相应改判 `is_none()`。外部 Rust 代码中 `metadata.title`(期望 `String`)、`metadata.title.clone()` 或 `format!("{}", metadata.title)` 等写法将编译失败,需改为 `metadata.title.as_deref().unwrap_or("")` 之类。C-ABI 不变;Python/Node 绑定仍把 NULL 与空 C 串一并解码成 `""`,其公开行为不受影响。动机:C 宿主需要区分「未发布」(NULL)与「发布为空」(空串),`String` 无法表达前者。 +- ⚠️ **`MediaMetadata` string fields become `Option` (Rust API)**: `uda-core::media::MediaMetadata`'s `title` / `artist` / `album` change from `String` to `Option`, with `is_empty()` now testing `is_none()`. External Rust code reading `metadata.title` as a `String`, cloning it or formatting it with `{}` will stop compiling; adapt with `metadata.title.as_deref().unwrap_or("")` and similar. The C-ABI is unchanged; the Python/Node bindings still decode both NULL and an empty C string to `""`, so their public behaviour does not change. Motivation: a C host must tell "not published" (NULL) from "published empty" (empty string), which a bare `String` cannot express. ### 🧰 Fixed @@ -63,8 +81,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 🧰 **Examples stop claiming unconditional success**: `07_session` (Python and Node) now probes `uda_session_capabilities` first and renders the six-action support matrix from that result, labelling unsupported actions "not supported in this environment (probed)" and never calling them; the Node binding gains a `UdaError` class (carrying the numeric `status`) plus exported status-code constants, so hosts can branch on `-1 / -2 / -5` exactly like the Python binding. - 🧰 **示例退出语义对齐**:Node 示例补齐与 Python `_bootstrap.run` 相同的顶层失败呈现——环境不可用时打印一行 `UDA 调用失败: …` 并以退出码 1 结束(此前为未捕获调用栈),07_session 的"探测抛错 → 1、全部不支持 → 0"两侧行为一致。 - 🧰 **Example exit semantics aligned**: the Node examples now render failures exactly like Python's `_bootstrap.run` - one `UDA 调用失败: …` line and exit code 1 when the environment cannot answer (previously an uncaught stack trace), with 07_session agreeing on "probe throws → 1, everything unsupported → 0" on both sides. -- 🧰 **杂项**:空壁纸路径未被拒绝;空字符串字段返回非 NULL 空串;Tier-3 壁纸探测不区分桌面环境;dbusmenu 根节点 `GetProperty(0)` 恒 `InvalidArgs` 且缺标准属性;点击回调 panic 后 `on_click` 永久失效;wakelock `expires_at` 死状态无回收;D-Bus 调用无超时上限(5 个模块);`GET_WALLPAPER` 能力位与实现错位;`uda-cli` 裸 unwrap / 硬编码路径 / 破坏性副作用;Node `new Uda(path)` 参数被丢弃、`_readWallpaper` 双调用、行添加失败泄漏 koffi 槽位;Python 兜底诊断写死状态码 0、非 NULL 空串跳过释放。 -- 🧰 **Assorted**: empty wallpaper paths not rejected; empty string fields returning non-NULL pointers; the Tier-3 wallpaper probe ignoring the desktop environment; `GetProperty(0)` always `InvalidArgs` with standard root properties missing; `on_click` gone for good after a panicking handler; the dead `expires_at` with no reaper; missing D-Bus timeouts across five modules; the `GET_WALLPAPER` capability/implementation mismatch; `uda-cli`'s bare unwraps, hardcoded path and destructive side effects; Node dropping the `new Uda(path)` argument, double-reading the wallpaper and leaking koffi slots on failed row adds; Python reporting status code 0 in fallback diagnostics and skipping the release of non-NULL empty strings. +- 🧰 **杂项**:空壁纸路径未被拒绝;空字符串字段返回非 NULL 空串(媒体元数据字段例外——本版本为它们保留了「已发布但为空」与「未发布」的可区分性,见 Changed 中的 NULL/空串契约);Tier-3 壁纸探测不区分桌面环境;dbusmenu 根节点 `GetProperty(0)` 恒 `InvalidArgs` 且缺标准属性;点击回调 panic 后 `on_click` 永久失效;wakelock `expires_at` 死状态无回收;D-Bus 调用无超时上限(5 个模块);`GET_WALLPAPER` 能力位与实现错位;`uda-cli` 裸 unwrap / 硬编码路径 / 破坏性副作用;Node `new Uda(path)` 参数被丢弃、`_readWallpaper` 双调用、行添加失败泄漏 koffi 槽位;Python 兜底诊断写死状态码 0、非 NULL 空串跳过释放。 +- 🧰 **Assorted**: empty wallpaper paths not rejected; empty string fields returning non-NULL pointers (the media metadata fields are the exception - this release keeps "published empty" distinguishable from "unpublished" for them, see the NULL/empty contract under Changed); the Tier-3 wallpaper probe ignoring the desktop environment; `GetProperty(0)` always `InvalidArgs` with standard root properties missing; `on_click` gone for good after a panicking handler; the dead `expires_at` with no reaper; missing D-Bus timeouts across five modules; the `GET_WALLPAPER` capability/implementation mismatch; `uda-cli`'s bare unwraps, hardcoded path and destructive side effects; Node dropping the `new Uda(path)` argument, double-reading the wallpaper and leaking koffi slots on failed row adds; Python reporting status code 0 in fallback diagnostics and skipping the release of non-NULL empty strings. - 🧰 **锁屏与注销探测按各自执行体拆分(终审轮)**:`LOCK` 与 `LOGOUT` 不再共用同一探测——`LOCK` 跟随 `GetSession("auto")`(logind 自带"回落到该用户 display 会话"语义,`loginctl lock-session` 的真实目标),`LOGOUT`/`SESSION_MANAGEMENT` 跟随 `GetSession("")`(只解析调用者自身会话,systemd 源码语义即如此);探测与执行从此一一对应,用户服务进程里"有 display 会话但无自身会话"的环境不再虚报注销能力。 - 🧰 **Lock and logout probes follow their own executors (final review round)**: `LOCK` and `LOGOUT` no longer share one probe - `LOCK` follows `GetSession("auto")` (logind's own "fall back to the user's display session" semantics, the true target of `loginctl lock-session`), while `LOGOUT`/`SESSION_MANAGEMENT` follow `GetSession("")` (which resolves only the caller's own session, per systemd's documented behaviour); probe and executor now agree one-to-one, so a user-service process with a display session but no session of its own no longer over-promises logout. - 🧰 **桌面注销探测覆盖按需激活的服务(终审轮)**:`desktop_logout_manager_present()` 现合并 `ListNames` 与 `ListActivatableNames`——Plasma 的 `org.kde.Shutdown` 是 D-Bus 可激活服务(`kdbusaddons` 生成的 service 文件),进程未启动时不会出现在已持有名单里,只查名单会把真实可用的 KDE 注销回退挡在核心能力门禁之外;两个列表各自失败独立降级,探测绝不主动激活服务。 @@ -79,6 +97,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 🧰 **Wallpaper reads and hyprpaper reply semantics (final review round)**: a successful `hyprctl` IPC transfer is not an accepted request (Hyprland v0.49 exits 0 even when hyprpaper replies with an error) - a dedicated caller now captures stdout and requires the `ok` reply, falling through to swww with the daemon's diagnosis on refusal; GNOME reads decode the GVariant string first (escapes, `\uXXXX`) and then resolve the local file URI (empty authority / `localhost`), rejecting remote authorities, malformed percent escapes and embedded NULs honestly; the FFI no longer re-runs the gsettings read the platform already performed (the old duplicate had no timeout and a lenient parser, bypassing the platform's boundaries), and Unity-session detection moved into the platform layer. - 🧰 **绑定侧托盘生命期与空回调(第二轮复审)**:Python 的 `TrayMenu.destroy` 失败时不再把整个菜单留在模块级集合里(菜单持有 `Uda`,曾使常亮锁与托盘图标永不释放),改为只钉住 ctypes 蹦床本身,重试成功后再按 identity 摘除;无回调行改传同 `CFUNCTYPE` 类型的空指针(直接传 `None` 会被 ctypes 以 `ArgumentError` 拒绝,"静默行"此前根本无法创建);Node 的 `TrayIcon.destroy` 失败时先置 `_stopped` 再抛出(`wait()` 不再永久挂起),`Uda.dispose()` 把销毁失败的图标/菜单钉进进程级数组(`keepalives` 是 koffi 蹦床的最后引用,丢掉即 UAF)。 - 🧰 **Binding-side tray lifetimes and null callbacks (second review round)**: a failed Python `TrayMenu.destroy` no longer parks the whole menu in a module-level set (the menu owns `Uda`, so one failed destroy kept wake locks and tray icons from ever being released) - only the ctypes trampolines are pinned, and they are removed by identity after a successful retry. Rows without a callback now pass a null pointer of the same `CFUNCTYPE` type (passing `None` directly is rejected by ctypes with `ArgumentError`, so "silent rows" could not be created at all). On the Node side, a failed `TrayIcon.destroy` sets `_stopped` before rethrowing (`wait()` no longer hangs forever), and `Uda.dispose()` pins icons/menus whose destroy failed in a process-lifetime array (`keepalives` is the last reference to the koffi trampolines; dropping it would be a UAF). +- 🧰 **`uda_tray_set_icon_rgba` 的畸形尺寸改为参数错误**:宽或高为 0、`stride < width * 4`、`width * 4` 溢出这三种调用方违约现在返回 `UDA_ERR_INVALID_ARGUMENT`(`-1`),不再透传 `uda-core` 的 `TrayIcon::set_icon` 返回的 `UDA_ERR_NOT_SUPPORTED`(`-2`);`len < stride * height` 此前已由 FFI 层返回 `-1`。这些校验同时保留在 `uda-core` 的 `TrayIconSource::validate` 中,FFI 侧这层只负责给出正确的状态码与诊断信息;头文件也不再声称 `data` 可在 `len == 0` 时为 NULL(实现一贯拒绝 NULL)。 +- 🧰 **`uda_tray_set_icon_rgba` reports malformed geometry as an argument error**: a zero width or height, `stride < width * 4`, or a `width * 4` overflow now returns `UDA_ERR_INVALID_ARGUMENT` (`-1`) instead of surfacing `UDA_ERR_NOT_SUPPORTED` (`-2`) from `uda-core`'s `TrayIcon::set_icon`; `len < stride * height` already returned `-1` from the FFI layer. The same checks remain in `uda-core`'s `TrayIconSource::validate`, with the FFI layer owning only the status code and the diagnosis; the header also no longer claims `data` may be NULL when `len == 0` (the implementation has always rejected NULL). + +### 🧪 Testing + +- 🧪 **生成头文件的 C/C++ 回归脚本与符号门禁**:新增 `scripts/test-header.py`,用真实的 C11 / C++11 编译器把生成头文件的契约钉死:`UDA_SESSION_CAP_*` 必须是 32 位无符号移位常量(`UdaStatus` 不得泄漏到 C 侧)、能力位与 `crates/uda-ffi/src/abi.rs` 的规范位图逐位一致、两个回调 typedef 在 C++ 下可直接赋值,以及 `scripts/gen-header.sh` 在 cbindgen 版本不符时于生成前退出且不改动头文件;该脚本已接入 CI 的 Linux job。`cargo test -p uda-ffi` 另有 `the_generated_header_declares_exactly_the_exported_symbols` 门禁:每个 `#[no_mangle]` 导出、`pub UDA_*` 常量与回调 typedef 都必须与 `include/uda.h` 双向一致,因此漏跑 `gen-header.sh` 在本地测试就会红灯,而不只依赖 CI 的重新生成 diff。 +- 🧪 **A C/C++ regression script and a symbol gate for the generated header**: a new `scripts/test-header.py` compiles real C11 / C++11 assertions against the generated header - `UDA_SESSION_CAP_*` must stay 32-bit unsigned shift constants (`UdaStatus` must not leak into C), the capability bits must match the canonical map in `crates/uda-ffi/src/abi.rs` bit for bit, both callback typedefs must be assignable from C++, and `scripts/gen-header.sh` must exit before generating (leaving the header untouched) when the cbindgen version does not match; it runs in the Linux CI job. `cargo test -p uda-ffi` also carries `the_generated_header_declares_exactly_the_exported_symbols`, which compares the header against the crate's sources in both directions - every `#[no_mangle]` export, `pub UDA_*` constant and callback typedef must appear on both sides - so forgetting `gen-header.sh` fails a plain local test run, not only the CI regenerate-and-diff step. --- diff --git a/README.md b/README.md index 1947689..fbf6b3d 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ The per-cell backend, the ⚠️ behaviour and what each environment reports: ** ## 🚀 Quickstart in 3 Languages -Three entry points: the native Rust crates, and a stable C-ABI (`include/uda.h`) reachable from Python and Node.js. +Three entry points: the native Rust crates, and a stable C-ABI (`include/uda.h`, generated from the Rust sources by cbindgen) reachable from Python and Node.js. ```rust // Rust — native traits, no FFI layer diff --git a/README_CN.md b/README_CN.md index aaf823c..feaa289 100644 --- a/README_CN.md +++ b/README_CN.md @@ -54,7 +54,7 @@ ## 🚀 三种语言快速上手 -三个入口:原生 Rust crate,以及可从 Python 与 Node.js 调用的稳定 C-ABI(`include/uda.h`)。 +三个入口:原生 Rust crate,以及可从 Python 与 Node.js 调用的稳定 C-ABI(`include/uda.h`,由 cbindgen 从 Rust 源码生成)。 ```rust // Rust —— 直接用原生 Trait,无需 FFI 层 diff --git a/crates/uda-core/src/media.rs b/crates/uda-core/src/media.rs index f90a4cd..c917672 100644 --- a/crates/uda-core/src/media.rs +++ b/crates/uda-core/src/media.rs @@ -58,14 +58,20 @@ impl PlaybackStatus { /// Every field is owned and pre-joined for display: an MPRIS `xesam:artist` is a /// list, but a UI wants one string, so the backend does the join and the struct /// stays free of the wire types. +/// +/// A string field is `None` when the player does not publish it at all, and +/// `Some("")` when the player publishes it as an empty string, so the two stay +/// distinguishable all the way to the C-ABI (which hands out NULL versus an +/// empty string). On Windows SMTC cannot tell an absent property from an empty +/// one, so the Windows backend maps an empty read to `None`. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct MediaMetadata { - /// Track title. Empty when the player publishes none. - pub title: String, - /// Artist(s), already joined for display. - pub artist: String, - /// Album name. - pub album: String, + /// Track title; `None` when the player publishes none. + pub title: Option, + /// Artist(s), already joined for display; `None` when unpublished. + pub artist: Option, + /// Album name; `None` when unpublished. + pub album: Option, /// Track length in milliseconds, or `None` when unknown or unbounded /// (a live stream). pub duration_ms: Option, @@ -75,13 +81,16 @@ pub struct MediaMetadata { } impl MediaMetadata { - /// Whether this snapshot carries no usable information at all, turning "the - /// player answered but said nothing" into the same `Ok(None)` a host with no - /// player gets. + /// Whether this snapshot carries no usable information at all: every string + /// field is unpublished (`None`) and both numeric fields are unknown + /// (`None`). A field published as an empty string is published - `Some("")` + /// therefore keeps the snapshot non-empty - so this predicate must not be + /// read as "all values are blank". Used to turn an all-unpublished read into + /// the same `Ok(None)` a host with no player gets. pub fn is_empty(&self) -> bool { - self.title.is_empty() - && self.artist.is_empty() - && self.album.is_empty() + self.title.is_none() + && self.artist.is_none() + && self.album.is_none() && self.duration_ms.is_none() && self.position_ms.is_none() } @@ -145,10 +154,25 @@ pub trait MediaManager { /// be read rather than an error. fn playback_status(&self) -> Result; - /// Send `command` to the active player. A player that refuses the command - /// (pausing an already-paused stream, for instance) is still a successful - /// call: the platform cannot distinguish "declined" from "done", and an error - /// would make a normal toggle look like a failure. + /// Send `command` to the active player. + /// + /// Failures before any player is addressed keep their own types, so a + /// non-`Ok` result does not always mean "the player declined": no player to + /// address, a missing SMTC manager, or a manager acquisition await that + /// fails is [`UdaError::NotSupported`]; a Linux session-bus connection + /// failure or a Windows SMTC manager `RequestAsync` failure is + /// [`UdaError::DetectionFailed`]; and runtime/proxy setup can be + /// [`UdaError::Internal`]. + /// + /// Once a player has been selected, an explicit refusal (an MPRIS error + /// reply, an SMTC `Try*Async()` returning `false`) is + /// [`UdaError::NotSupported`] - `include/uda.h` promises + /// `UDA_ERR_NOT_SUPPORTED` for a player that declines a command - while a + /// transport failure (a D-Bus timeout, a failed SMTC call) is + /// [`UdaError::CommandFailed`]. After a timeout or communication failure + /// the player may already have executed the command, so callers must treat + /// a non-`Ok` result as "success was not confirmed" rather than retrying + /// blindly. See `docs/internals/media_specs.md` §3.4. fn send_command(&self, command: MediaCommand) -> Result<(), UdaError>; /// The capabilities this platform's media backend can honour. @@ -225,7 +249,20 @@ mod tests { #[test] fn a_title_alone_is_enough_to_be_non_empty() { let metadata = MediaMetadata { - title: "Song".to_string(), + title: Some("Song".to_string()), + ..MediaMetadata::default() + }; + assert!(!metadata.is_empty()); + } + + #[test] + fn a_published_empty_title_is_published_not_empty() { + // `is_empty` asks "all fields unpublished", not "all values blank": a + // player that publishes an empty title has still published something. + // On Linux the C ABI keeps that distinction as an empty string vs NULL; + // Windows SMTC has no unpublished marker and folds empty reads to NULL. + let metadata = MediaMetadata { + title: Some(String::new()), ..MediaMetadata::default() }; assert!(!metadata.is_empty()); diff --git a/crates/uda-ffi/cbindgen.toml b/crates/uda-ffi/cbindgen.toml new file mode 100644 index 0000000..33cb6aa --- /dev/null +++ b/crates/uda-ffi/cbindgen.toml @@ -0,0 +1,101 @@ +# Regenerates include/uda.h from this crate's C-ABI surface. +# +# include/uda.h is a GENERATED file: never edit it by hand. Edit the Rust +# doc comments on the exported functions and the constants/callback types in +# src/abi.rs, then run scripts/gen-header.sh (CI re-runs it in --check mode +# and fails on drift). +# +# The cbindgen version is pinned in scripts/gen-header.sh and in the CI +# workflow; bumping it can reflow the output and must be a deliberate, +# reviewed change. + +language = "c" + +# The hand-written header this replaces always wrapped the declarations in +# `#ifdef __cplusplus extern "C"`, and C++ consumers of the released header +# rely on it; keep that guarantee. +# +# NOTE: cbindgen emits the two callback typedefs (UdaTrayTextCallback and +# UdaTrayCheckboxCallback) *before* that `extern "C"` block, because they are +# ordinary C typedefs rather than function declarations. The placement is valid +# C and C++ and does not change any exported symbol; scripts/test-header.py +# compiles the header as C++11 and assigns an `extern "C"` function to each +# typedef, which keeps the typedefs usable from C++. The placement itself is an +# accepted cbindgen property, not something this repository post-processes - +# rewriting generated output to move the typedefs would be fragile and buys +# nothing. +cpp_compat = true + +# The header stays self-contained: only the two standard includes the ABI +# actually needs (size_t via stddef.h, the fixed-width integers via +# stdint.h). +no_includes = true +sys_includes = ["stddef.h", "stdint.h"] + +# `len`-style parameters are byte counts, so render usize as the C length +# type rather than the address-integer type uintptr_t. +usize_is_size_t = true + +include_guard = "UDA_H_" +documentation = true + +# `doxy` emits `/** ... */` blocks, matching the hand-written header's +# comment style and keeping the API docs visible to Doxygen tooling. +documentation_style = "doxy" + +autogen_warning = """/* Generated by cbindgen from crates/uda-ffi - DO NOT EDIT. + * Regenerate with scripts/gen-header.sh after changing the Rust sources. */""" + +header = """/* + * uda.h - UniDesktop API (UDA) C-ABI header. + * + * This header describes the stable C interface exported by `crates/uda-ffi`: + * - Linux -> libuda_ffi.so + * - Windows -> uda_ffi.dll + * + * DO NOT EDIT: this file is generated by cbindgen from the Rust sources in + * crates/uda-ffi (the constants and callback types in src/abi.rs and the + * exported functions in src/lib.rs). Regenerate it with + * scripts/gen-header.sh and commit the result; hand edits are overwritten + * on the next regeneration. + * + * Every function returns an `int32_t` status code (`0` = success, negative + * = failure) except `uda_free_string`, which returns nothing, and the two + * string-returning helpers, `uda_last_error_message()` (human-readable + * diagnostics for the most recent failure on this thread) and + * `uda_status_message()` (renders any status code without a second FFI + * round-trip). + * + * Memory ownership + * ---------------- + * - Strings RETURNED by UDA are allocated by the library and must be + * released with `uda_free_string()`. Passing NULL to + * `uda_free_string()` is a no-op, so callers may free unconditionally. + * The one exception is `uda_status_message()`, whose static return must + * not be freed. + * - Strings PASSED IN are borrowed for the duration of the call only; the + * caller keeps ownership and must keep them alive until the call + * returns. + * - Wake-lock handles are plain `uint64_t` values owned by this process. + * Release each one exactly once with `uda_wakelock_release()`. + * - Tray icons and menus are opaque handles into process-local tables; + * the caller owns the handle and must destroy it exactly once with + * `uda_tray_destroy()` / `uda_tray_menu_destroy()`. Callback pointers + * registered on a menu row are retained by UDA for the lifetime of + * that row, and the menu (not the callback) is the unit of + * destruction. + * + * Thread safety + * ------------- + * All functions are free of global state apart from the wake-lock registry, + * the tray handle registry (both internally synchronised) and the + * thread-local last-error slot, so they may be called concurrently from + * several threads. The last-error message is per-thread: one thread's + * failure never overwrites another's diagnosis. + * + * ABI stability + * ------------- + * The exported symbol set is append-only. New capabilities are added as + * new functions; existing signatures, constants and status codes do not + * change. + */""" diff --git a/crates/uda-ffi/src/abi.rs b/crates/uda-ffi/src/abi.rs new file mode 100644 index 0000000..c84cfcf --- /dev/null +++ b/crates/uda-ffi/src/abi.rs @@ -0,0 +1,498 @@ +//! The C-ABI surface of this crate, in one place. +//! +//! Every constant and callback type that `include/uda.h` exposes is declared +//! here, so the Rust side stays the single source of truth and the header is a +//! generated artifact (see `cbindgen.toml` and `scripts/gen-header.sh`). +//! Declaring a constant here is all it takes to publish it in the header on +//! the next regeneration; nothing else needs updating. +//! +//! The doc comments on this module's items are carried verbatim into the +//! generated C header, so they are written for the C caller: ASCII prose, no +//! Rust intra-doc links, no markdown tables. + +use std::os::raw::c_void; + +// --------------------------------------------------------------------------- +// Status codes (returned by every exported function) +// --------------------------------------------------------------------------- + +/// The call succeeded. +pub const UDA_OK: i32 = 0; +/// Null pointer, invalid UTF-8, or an out-of-range enum code. +pub const UDA_ERR_INVALID_ARGUMENT: i32 = -1; +/// The current platform or session cannot provide the feature. +pub const UDA_ERR_NOT_SUPPORTED: i32 = -2; +/// Detecting the environment or OS release failed. +pub const UDA_ERR_DETECTION_FAILED: i32 = -3; +/// A filesystem or process-spawn error occurred. +pub const UDA_ERR_IO: i32 = -4; +/// An unexpected internal failure occurred. +pub const UDA_ERR_INTERNAL: i32 = -5; +/// A panic was contained at the FFI boundary (should never be observed). +pub const UDA_ERR_PANIC: i32 = -6; + +// --------------------------------------------------------------------------- +// Theme codes (uda_detect_theme) +// --------------------------------------------------------------------------- + +/// The theme could not be determined. +pub const UDA_THEME_UNKNOWN: i32 = 0; +/// Dark appearance. +pub const UDA_THEME_DARK: i32 = 1; +/// Light appearance. +pub const UDA_THEME_LIGHT: i32 = 2; + +// --------------------------------------------------------------------------- +// Fill modes (uda_set_wallpaper) +// --------------------------------------------------------------------------- + +/// Crop to fill while preserving the aspect ratio. +pub const UDA_FILL_CROP: i32 = 0; +/// Fill the screen, ignoring the aspect ratio. +pub const UDA_FILL_FILL: i32 = 1; +/// Fit inside the screen while preserving the aspect ratio. +pub const UDA_FILL_FIT: i32 = 2; +/// Stretch to fill the screen. +pub const UDA_FILL_STRETCH: i32 = 3; + +// --------------------------------------------------------------------------- +// Wake-lock types (uda_wakelock_acquire) +// --------------------------------------------------------------------------- + +/// Prevent the display from sleeping. +pub const UDA_WAKELOCK_DISPLAY: i32 = 0; +/// Prevent the system from idling or suspending. +pub const UDA_WAKELOCK_SYSTEM: i32 = 1; + +// --------------------------------------------------------------------------- +// Media playback status (uda_media_get_status) +// --------------------------------------------------------------------------- + +/// Media playback is progressing. +pub const UDA_MEDIA_PLAYING: i32 = 0; +/// A track is loaded and halted. +pub const UDA_MEDIA_PAUSED: i32 = 1; +/// Nothing is loaded, or playback reached the end. +pub const UDA_MEDIA_STOPPED: i32 = 2; +/// The state could not be determined. This is ALSO the code for "no media +/// player is running", which is not an error: `uda_media_get_status()` reports +/// it with a `UDA_OK` status. Never render it as a paused track. +pub const UDA_MEDIA_UNKNOWN: i32 = 3; + +// --------------------------------------------------------------------------- +// Media transport commands (uda_media_send_command) +// --------------------------------------------------------------------------- + +/// Start or resume playback. +pub const UDA_MEDIA_CMD_PLAY: i32 = 0; +/// Halt playback, keeping the position. +pub const UDA_MEDIA_CMD_PAUSE: i32 = 1; +/// Switch between playing and paused. +pub const UDA_MEDIA_CMD_TOGGLE: i32 = 2; +/// Advance to the next track. +pub const UDA_MEDIA_CMD_NEXT: i32 = 3; +/// Return to the previous track. +pub const UDA_MEDIA_CMD_PREVIOUS: i32 = 4; +/// Stop playback and unload the track. +pub const UDA_MEDIA_CMD_STOP: i32 = 5; + +// --------------------------------------------------------------------------- +// Session & power capability bitmask (uda_session_capabilities) +// --------------------------------------------------------------------------- + +/// A session backend exists on this platform. +/// +/// This bit says nothing by itself: it only means at least one of the six +/// actions below is reachable. Test the action's own bit before offering it. +pub const UDA_SESSION_CAP_MANAGEMENT: u32 = 1u32 << 16; +/// The session can be locked - the only action safe to automate. +pub const UDA_SESSION_CAP_LOCK: u32 = 1u32 << 17; +/// The calling user's session can be ended. +pub const UDA_SESSION_CAP_LOGOUT: u32 = 1u32 << 18; +/// The machine can be suspended to RAM. +pub const UDA_SESSION_CAP_SUSPEND: u32 = 1u32 << 19; +/// The machine can be hibernated to disk. +pub const UDA_SESSION_CAP_HIBERNATE: u32 = 1u32 << 20; +/// The machine can be rebooted. +pub const UDA_SESSION_CAP_REBOOT: u32 = 1u32 << 21; +/// The machine can be powered off. +pub const UDA_SESSION_CAP_SHUTDOWN: u32 = 1u32 << 22; + +// --------------------------------------------------------------------------- +// Tray capability bits (uda_tray_capabilities) +// --------------------------------------------------------------------------- + +/// Capability bit: a tray backend exists at all (`SYSTEM_TRAY` in `uda-core`). +pub const UDA_TRAY_CAP_SYSTEM_TRAY: u32 = 1 << 7; +/// Capability bit: the icon can be shown, hidden and swapped at runtime. +pub const UDA_TRAY_CAP_ICON: u32 = 1 << 8; +/// Capability bit: the tray exposes hover text. +pub const UDA_TRAY_CAP_TOOLTIP: u32 = 1 << 9; +/// Capability bit: the tray reports a single primary click. +/// +/// Reserved: the C ABI has no click-callback registration, so +/// `uda_tray_capabilities` always clears this bit. It stays defined for a +/// future click API; do not infer click events from the bitmask today. +pub const UDA_TRAY_CAP_CLICK: u32 = 1 << 10; +/// Capability bit: the tray reports a native double click (never true on Linux +/// SNI, where it would have to be synthesised). +/// +/// Reserved for the same reason as [`UDA_TRAY_CAP_CLICK`]: the C ABI cannot +/// register a click callback, so `uda_tray_capabilities` always clears it. +pub const UDA_TRAY_CAP_DOUBLE_CLICK: u32 = 1 << 11; +/// Capability bit: the tray exposes a context menu. +pub const UDA_TRAY_CAP_CONTEXT_MENU: u32 = 1 << 12; +/// Capability bit: menu rows can render a checkbox state. +pub const UDA_TRAY_CAP_CHECKBOX: u32 = 1 << 13; +/// Capability bit: menu rows can be added at runtime; the C ABI does not +/// expose removal or relabelling (the Rust core supports both). +pub const UDA_TRAY_CAP_DYNAMIC_MENU: u32 = 1 << 14; + +// --------------------------------------------------------------------------- +// Tray support levels (uda_tray_support_level) +// --------------------------------------------------------------------------- + +/// Support-level code: the backend never claimed a tray at all. +/// +/// Unreachable through handles `uda_tray_create` handed out - every created +/// icon publishes the backend's capability set - but the mapping stays total, +/// so a fabricated or half-registered icon cannot be read as healthy. +pub const UDA_TRAY_SUPPORT_LEVEL_NONE: i32 = 0; +/// Support-level code: the icon is live, but registration recorded a +/// degradation (on Linux: no `StatusNotifierWatcher`, so the shell may never +/// display the item). `uda_tray_support_reason` explains it. +pub const UDA_TRAY_SUPPORT_LEVEL_PARTIAL: i32 = 1; +/// Support-level code: the icon is live and nothing degraded. +pub const UDA_TRAY_SUPPORT_LEVEL_FULL: i32 = 2; + +/// Every tray capability bit the C ABI documents. +/// +/// Used by the drift tests in this crate (here and in `tray.rs`), so the list +/// exists once. Private on purpose: it is not part of the header. +#[cfg(test)] +pub(crate) const DOCUMENTED_TRAY_CAPABILITIES: u32 = UDA_TRAY_CAP_SYSTEM_TRAY + | UDA_TRAY_CAP_ICON + | UDA_TRAY_CAP_TOOLTIP + | UDA_TRAY_CAP_CLICK + | UDA_TRAY_CAP_DOUBLE_CLICK + | UDA_TRAY_CAP_CONTEXT_MENU + | UDA_TRAY_CAP_CHECKBOX + | UDA_TRAY_CAP_DYNAMIC_MENU; + +// --------------------------------------------------------------------------- +// Tray callbacks +// --------------------------------------------------------------------------- + +/// Callback type for a plain text menu row, or NULL for a silent row. +/// +/// `item_id` is the row's id, as returned by `uda_tray_menu_add_text()`; +/// `user_data` is the pointer registered alongside this callback. +pub type UdaTrayTextCallback = Option; + +/// Callback type for a checkbox menu row, or NULL for a silent row. +/// +/// `item_id` is the row's id, as returned by `uda_tray_menu_add_checkbox()`; +/// `checked` is the NEW state after the toggle (`0` or `1`): the row's own +/// stored value has already been updated, so this is what the shell renders +/// next; `user_data` is the pointer registered alongside this callback. +pub type UdaTrayCheckboxCallback = Option; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_codes_match_the_documented_values() { + assert_eq!(UDA_OK, 0); + assert_eq!(UDA_ERR_INVALID_ARGUMENT, -1); + assert_eq!(UDA_ERR_NOT_SUPPORTED, -2); + assert_eq!(UDA_ERR_DETECTION_FAILED, -3); + assert_eq!(UDA_ERR_IO, -4); + assert_eq!(UDA_ERR_INTERNAL, -5); + assert_eq!(UDA_ERR_PANIC, -6); + } + + #[test] + fn theme_codes_match_the_documented_values() { + // Literals, not the constants against themselves: `dispatch.rs` maps + // `Theme` onto these constants, so only pinning the numbers here proves + // the mapping still lands on the values `include/uda.h` documents. + assert_eq!(UDA_THEME_UNKNOWN, 0); + assert_eq!(UDA_THEME_DARK, 1); + assert_eq!(UDA_THEME_LIGHT, 2); + } + + /// Pull the identifier after a marker out of one source/header line. + fn identifier_after(line: &str, marker: &str) -> Option { + let start = line.find(marker)? + marker.len(); + let rest = &line[start..]; + let name: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + if name.is_empty() { + None + } else { + Some(name) + } + } + + /// The exported C-ABI names this crate's sources declare, gathered by + /// scanning `src/*.rs` for the two-line `#[no_mangle]` + `fn` convention. + /// This is the Rust-side leg of the parity check; CI's symbol gates + /// (`scripts/header_symbols.py`, `scripts/pe_exports.py`) cover the + /// header-to-built-library side. + fn exported_names_from_sources() -> (Vec, Vec, Vec) { + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut functions = Vec::new(); + let mut constants = Vec::new(); + let mut callbacks = Vec::new(); + let mut pending_no_mangle = false; + + for entry in std::fs::read_dir(&src).expect("the crate's src directory") { + let path = entry.expect("src entry").path(); + if path.extension().and_then(|e| e.to_str()) != Some("rs") { + continue; + } + let source = std::fs::read_to_string(&path).expect("readable Rust source"); + // Only abi.rs's `pub type` aliases are C callback typedefs; other + // files define Rust-side type aliases (error.rs's `UdaStatus`, + // say) that never reach the header. + let is_abi = path.file_name().and_then(|n| n.to_str()) == Some("abi.rs"); + for line in source.lines() { + if line.trim() == "#[no_mangle]" { + pending_no_mangle = true; + continue; + } + if pending_no_mangle { + pending_no_mangle = false; + match identifier_after(line, " fn ") { + Some(name) => functions.push(name), + None => { + // The scanner reads the two-line `#[no_mangle]` + + // `pub ... fn` convention. Anything between them + // (another attribute, a doc comment, a wrapped + // signature) would silently drop a real export + // and fail the parity test with a misleading + // "re-run gen-header.sh"; fail with the actual + // cause instead. + panic!( + "a `#[no_mangle]` in {path:?} is not immediately \ + followed by its `fn` line; keep them adjacent or \ + extend this scanner: {line:?}" + ); + } + } + } + if let Some(name) = identifier_after(line, "pub const UDA_") { + constants.push(format!("UDA_{name}")); + } + if is_abi { + if let Some(name) = identifier_after(line, "pub type ") { + callbacks.push(name); + } + } + } + } + (functions, constants, callbacks) + } + + #[test] + fn the_generated_header_declares_exactly_the_exported_symbols() { + // `gen-header.sh --check` pins the header's *content* against a fresh + // cbindgen run, but only inside CI; a plain `cargo test` must catch a + // Rust-side export whose header counterpart went missing (or a hand + // edit that invented one) without any script running. Sets compare in + // both directions: adding an export without regenerating fails here, + // and so does deleting one the header still declares. + // + // Known limitations of the hand-rolled parsing, all verified absent + // from the current cbindgen 0.29.4 output and all failing LOUDLY here + // (never as a silent pass): a comment line starting with `#define` or + // `typedef` would inflate the header sets, a `//` comment containing + // `/*` would swallow real declarations into the block-comment state, + // and an identifier ending in `_uda_x(` would be counted as a function + // named `uda_x`. If a cbindgen upgrade ever emits any of those shapes, + // harden the scanner then - the failure mode is a red test, not drift. + let header_path = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../include/uda.h"); + let header = std::fs::read_to_string(&header_path).expect( + "include/uda.h sits at the repository root; run the tests from a full checkout", + ); + + let mut header_defines = Vec::new(); + let mut header_callbacks = Vec::new(); + // Function declarations can wrap across lines, so the function scan + // runs over the header with every comment stripped (doc mentions like + // `uda_free_string()` must not count as declarations) instead of over + // individual lines. + let mut code = String::new(); + let mut in_block_comment = false; + for line in header.lines() { + let trimmed = line.trim_start(); + if trimmed.starts_with("#define UDA_") { + if let Some(name) = identifier_after(trimmed, "#define ") { + // The include guard is header plumbing, not an ABI item. + if name != "UDA_H_" { + header_defines.push(name); + } + } + } + if trimmed.starts_with("typedef") { + if let Some(name) = identifier_after(trimmed, "(*") { + header_callbacks.push(name); + } + } + + let mut rest = trimmed; + if in_block_comment { + match rest.find("*/") { + Some(end) => { + in_block_comment = false; + rest = &rest[end + 2..]; + } + None => continue, + } + } + loop { + match rest.find("/*") { + Some(start) => { + code.push_str(&rest[..start]); + let after = &rest[start + 2..]; + match after.find("*/") { + Some(end) => rest = &after[end + 2..], + None => { + in_block_comment = true; + break; + } + } + } + None => { + if let Some(start) = rest.find("//") { + code.push_str(&rest[..start]); + } else { + code.push_str(rest); + } + code.push('\n'); + break; + } + } + } + } + + // Every `uda_name(` outside a comment is a declaration; the header + // contains no calls. + let mut header_functions = Vec::new(); + let mut search_from = 0; + while let Some(found) = code[search_from..].find("uda_") { + let absolute = search_from + found; + if let Some(name) = identifier_after(&code[absolute..], "uda_") { + let after_identifier = code[absolute + 4 + name.len()..].trim_start(); + if after_identifier.starts_with('(') { + header_functions.push(format!("uda_{name}")); + } + } + search_from = absolute + 4; + } + + let (mut functions, mut constants, mut callbacks) = exported_names_from_sources(); + functions.sort(); + constants.sort(); + callbacks.sort(); + header_functions.sort(); + header_defines.sort(); + header_callbacks.sort(); + + assert_eq!( + functions, header_functions, + "the header's function declarations and this crate's #[no_mangle] \ + exports disagree; re-run scripts/gen-header.sh" + ); + assert_eq!( + constants, header_defines, + "the header's UDA_* defines and abi.rs's pub constants disagree; \ + re-run scripts/gen-header.sh" + ); + assert_eq!( + callbacks, header_callbacks, + "the header's callback typedefs and abi.rs's pub types disagree; \ + re-run scripts/gen-header.sh" + ); + } + + #[test] + fn capability_bits_are_distinct_powers_of_two() { + let bits = [ + UDA_SESSION_CAP_MANAGEMENT, + UDA_SESSION_CAP_LOCK, + UDA_SESSION_CAP_LOGOUT, + UDA_SESSION_CAP_SUSPEND, + UDA_SESSION_CAP_HIBERNATE, + UDA_SESSION_CAP_REBOOT, + UDA_SESSION_CAP_SHUTDOWN, + ]; + for (index, bit) in bits.iter().enumerate() { + assert_eq!(bit.count_ones(), 1, "capability bits must be powers of two"); + assert_eq!( + *bit, + 1 << (16 + index), + "bit positions are part of the C ABI" + ); + for other in &bits[index + 1..] { + assert_ne!(bit, other, "capability bits must be distinct"); + } + } + } + + #[test] + fn tray_capability_bits_match_the_documented_values() { + // Literal values, not the constants against themselves: these numbers + // are part of the C ABI and the header carries them verbatim. + assert_eq!(UDA_TRAY_CAP_SYSTEM_TRAY, 1 << 7); + assert_eq!(UDA_TRAY_CAP_ICON, 1 << 8); + assert_eq!(UDA_TRAY_CAP_TOOLTIP, 1 << 9); + assert_eq!(UDA_TRAY_CAP_CLICK, 1 << 10); + assert_eq!(UDA_TRAY_CAP_DOUBLE_CLICK, 1 << 11); + assert_eq!(UDA_TRAY_CAP_CONTEXT_MENU, 1 << 12); + assert_eq!(UDA_TRAY_CAP_CHECKBOX, 1 << 13); + assert_eq!(UDA_TRAY_CAP_DYNAMIC_MENU, 1 << 14); + } + + #[test] + fn tray_capability_bits_are_distinct_powers_of_two() { + let bits = [ + UDA_TRAY_CAP_SYSTEM_TRAY, + UDA_TRAY_CAP_ICON, + UDA_TRAY_CAP_TOOLTIP, + UDA_TRAY_CAP_CLICK, + UDA_TRAY_CAP_DOUBLE_CLICK, + UDA_TRAY_CAP_CONTEXT_MENU, + UDA_TRAY_CAP_CHECKBOX, + UDA_TRAY_CAP_DYNAMIC_MENU, + ]; + for (index, bit) in bits.iter().enumerate() { + assert_eq!(bit.count_ones(), 1, "capability bits must be powers of two"); + assert_eq!( + *bit, + 1 << (7 + index), + "bit positions are part of the C ABI" + ); + for other in &bits[index + 1..] { + assert_ne!(bit, other, "capability bits must be distinct"); + } + } + // The documented mask must be exhaustive: a new bit added above but + // forgotten here would silently stop being drift-checked. + assert_eq!( + DOCUMENTED_TRAY_CAPABILITIES, + bits.iter().fold(0u32, |acc, bit| acc | bit) + ); + } + + #[test] + fn tray_support_levels_match_the_documented_values() { + assert_eq!(UDA_TRAY_SUPPORT_LEVEL_NONE, 0); + assert_eq!(UDA_TRAY_SUPPORT_LEVEL_PARTIAL, 1); + assert_eq!(UDA_TRAY_SUPPORT_LEVEL_FULL, 2); + } +} diff --git a/crates/uda-ffi/src/dispatch.rs b/crates/uda-ffi/src/dispatch.rs index 7a898dc..babbca5 100644 --- a/crates/uda-ffi/src/dispatch.rs +++ b/crates/uda-ffi/src/dispatch.rs @@ -23,6 +23,7 @@ use uda_core::tray::{TrayIcon, TrayIconConfig}; use uda_core::wakelock::WakeLockType; use uda_core::wallpaper::{FillMode, WallpaperManager, WallpaperOptions}; +use crate::abi::{UDA_THEME_DARK, UDA_THEME_LIGHT, UDA_THEME_UNKNOWN}; use crate::error::Failure; /// Opaque wake-lock handle handed to the caller. @@ -75,14 +76,14 @@ pub(crate) fn accent_color() -> Option { /// Translate a [`Theme`] into the C ABI code. fn theme_code(theme: Theme) -> i32 { match theme { - Theme::Dark => 1, - Theme::Light => 2, + Theme::Dark => UDA_THEME_DARK, + Theme::Light => UDA_THEME_LIGHT, // Neither an "auto" preference nor an undeterminable one has a positive // answer in the C ABI, so both report `UDA_THEME_UNKNOWN`. - Theme::Auto | Theme::Unknown => 0, + Theme::Auto | Theme::Unknown => UDA_THEME_UNKNOWN, // `Theme` is `#[non_exhaustive]`: a future appearance maps to the // same "no positive answer" code instead of breaking this crate. - _ => 0, + _ => UDA_THEME_UNKNOWN, } } @@ -201,6 +202,7 @@ struct UnsupportedBackend; #[cfg(not(any(target_os = "linux", target_os = "windows")))] impl UnsupportedBackend { + /// cbindgen:ignore const REASON: &'static str = "no backend for this target"; fn not_supported() -> UdaError { @@ -258,11 +260,14 @@ mod tests { #[test] fn theme_codes_match_the_c_header() { - assert_eq!(theme_code(Theme::Dark), 1); - assert_eq!(theme_code(Theme::Light), 2); + // Verifies the mapping uses the ABI constants; the numeric values of + // those constants are pinned as literals in `abi.rs`, so renumbering one + // cannot pass by comparing a constant to itself. + assert_eq!(theme_code(Theme::Dark), UDA_THEME_DARK); + assert_eq!(theme_code(Theme::Light), UDA_THEME_LIGHT); // Neither "auto" nor "undeterminable" has a positive C representation. - assert_eq!(theme_code(Theme::Auto), 0); - assert_eq!(theme_code(Theme::Unknown), 0); + assert_eq!(theme_code(Theme::Auto), UDA_THEME_UNKNOWN); + assert_eq!(theme_code(Theme::Unknown), UDA_THEME_UNKNOWN); } #[test] diff --git a/crates/uda-ffi/src/error.rs b/crates/uda-ffi/src/error.rs index 6e7e8a8..d730c30 100644 --- a/crates/uda-ffi/src/error.rs +++ b/crates/uda-ffi/src/error.rs @@ -14,34 +14,20 @@ //! //! Human-readable diagnostics for the failing call are available through //! `uda_last_error_message()`, which returns a fresh, caller-owned allocation -//! that must be released with `uda_free_string()`. +//! that must be released with `uda_free_string()`. Reading it consumes the +//! message: the next call returns null until a new failure is recorded on the +//! same thread. use uda_core::error::UdaError; +use crate::abi::{ + UDA_ERR_DETECTION_FAILED, UDA_ERR_INTERNAL, UDA_ERR_INVALID_ARGUMENT, UDA_ERR_IO, + UDA_ERR_NOT_SUPPORTED, UDA_ERR_PANIC, UDA_OK, +}; + /// Status code returned by every exported C function. pub type UdaStatus = i32; -/// The call succeeded. -pub const UDA_OK: UdaStatus = 0; - -/// A caller-supplied argument was null, not UTF-8, or out of range. -pub const UDA_ERR_INVALID_ARGUMENT: UdaStatus = -1; - -/// The current platform or session cannot provide the requested feature. -pub const UDA_ERR_NOT_SUPPORTED: UdaStatus = -2; - -/// Detecting the environment or OS release failed. -pub const UDA_ERR_DETECTION_FAILED: UdaStatus = -3; - -/// An I/O or process-spawn error occurred. -pub const UDA_ERR_IO: UdaStatus = -4; - -/// An unexpected internal failure occurred. -pub const UDA_ERR_INTERNAL: UdaStatus = -5; - -/// A panic escaped the Rust implementation and was contained by the boundary. -pub const UDA_ERR_PANIC: UdaStatus = -6; - /// A failure that the C ABI can describe without borrowing [`UdaError`]. /// /// Keeping the invalid-argument case separate from [`UdaError`] matters: a diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index 6f2e45d..942dbbe 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -2,8 +2,10 @@ //! //! This crate builds the shared library every non-Rust language links against: //! `libuda_ffi.so` on Linux, `uda_ffi.dll` on Windows. The matching C header is -//! [`include/uda.h`](../../include/uda.h); ready-made bindings live under -//! `examples/` (Python `ctypes`, Node.js `koffi`). +//! [`include/uda.h`](../../include/uda.h), **generated** by cbindgen from the +//! exported functions below and the surface types in [`abi`] - never edit the +//! header by hand, run `scripts/gen-header.sh` instead. Ready-made bindings +//! live under `examples/` (Python `ctypes`, Node.js `koffi`). //! //! # Contract //! @@ -32,8 +34,10 @@ //! # Thread safety //! //! The exports are free functions with no global mutable state except the -//! wake-lock registry (internally synchronised) and the thread-local -//! last-error slot. +//! wake-lock registry, the tray handle registry (both internally +//! synchronised) and the thread-local last-error slot. + +pub mod abi; mod dispatch; mod error; @@ -44,83 +48,24 @@ mod tray; mod util; mod wakelocks; -use std::os::raw::{c_char, c_int, c_void}; +use std::os::raw::{c_char, c_void}; use uda_core::session::SessionAction; +pub use abi::*; pub use error::{status_message, UdaStatus}; -// These numbers appear verbatim in include/uda.h and are part of the C ABI. -pub use media::{ - UDA_MEDIA_CMD_NEXT, UDA_MEDIA_CMD_PAUSE, UDA_MEDIA_CMD_PLAY, UDA_MEDIA_CMD_PREVIOUS, - UDA_MEDIA_CMD_STOP, UDA_MEDIA_CMD_TOGGLE, UDA_MEDIA_PAUSED, UDA_MEDIA_PLAYING, - UDA_MEDIA_STOPPED, UDA_MEDIA_UNKNOWN, -}; - -// Part of the C ABI, so a caller can ask which actions exist *before* drawing a -// menu that could shut the machine down. -pub use session::{ - UDA_SESSION_CAP_HIBERNATE, UDA_SESSION_CAP_LOCK, UDA_SESSION_CAP_LOGOUT, - UDA_SESSION_CAP_MANAGEMENT, UDA_SESSION_CAP_REBOOT, UDA_SESSION_CAP_SHUTDOWN, - UDA_SESSION_CAP_SUSPEND, -}; - -// Part of the C ABI, so a caller can ask what the tray backend offers *before* -// registering an icon, and what an icon's registration actually achieved after. -pub use tray::{ - UDA_TRAY_CAP_CHECKBOX, UDA_TRAY_CAP_CLICK, UDA_TRAY_CAP_CONTEXT_MENU, - UDA_TRAY_CAP_DOUBLE_CLICK, UDA_TRAY_CAP_DYNAMIC_MENU, UDA_TRAY_CAP_ICON, - UDA_TRAY_CAP_SYSTEM_TRAY, UDA_TRAY_CAP_TOOLTIP, UDA_TRAY_SUPPORT_LEVEL_FULL, - UDA_TRAY_SUPPORT_LEVEL_NONE, UDA_TRAY_SUPPORT_LEVEL_PARTIAL, -}; - -/// Status code for "success". -pub const UDA_OK: c_int = 0; -/// Status code for "invalid argument". -pub const UDA_ERR_INVALID_ARGUMENT: c_int = -1; -/// Status code for "feature not supported". -pub const UDA_ERR_NOT_SUPPORTED: c_int = -2; -/// Status code for "environment detection failed". -pub const UDA_ERR_DETECTION_FAILED: c_int = -3; -/// Status code for "I/O error". -pub const UDA_ERR_IO: c_int = -4; -/// Status code for "internal error". -pub const UDA_ERR_INTERNAL: c_int = -5; -/// Status code for "a panic was contained at the boundary". -pub const UDA_ERR_PANIC: c_int = -6; - -/// Theme code for "unknown / not detected". -pub const UDA_THEME_UNKNOWN: c_int = 0; -/// Theme code for "dark". -pub const UDA_THEME_DARK: c_int = 1; -/// Theme code for "light". -pub const UDA_THEME_LIGHT: c_int = 2; - -/// Fill-mode code for "crop to fill, preserving aspect ratio". -pub const UDA_FILL_CROP: c_int = 0; -/// Fill-mode code for "fill, ignoring aspect ratio". -pub const UDA_FILL_FILL: c_int = 1; -/// Fill-mode code for "fit, preserving aspect ratio". -pub const UDA_FILL_FIT: c_int = 2; -/// Fill-mode code for "stretch to fill". -pub const UDA_FILL_STRETCH: c_int = 3; - -/// Wake-lock code for "prevent the display from sleeping". -pub const UDA_WAKELOCK_DISPLAY: c_int = 0; -/// Wake-lock code for "prevent the system from idling". -pub const UDA_WAKELOCK_SYSTEM: c_int = 1; - /// Detect the current system colour scheme. /// -/// Writes one of [`UDA_THEME_UNKNOWN`], [`UDA_THEME_DARK`] or -/// [`UDA_THEME_LIGHT`] to `*out_theme`. On failure a negative status code is -/// returned and `*out_theme` is left untouched. +/// Writes `UDA_THEME_UNKNOWN`, `UDA_THEME_DARK` or `UDA_THEME_LIGHT` to +/// `*out_theme`. On failure a negative status code is returned and +/// `*out_theme` is left untouched. /// /// # Safety /// -/// `out_theme` must be a valid, writable, non-null `int32_t` location. +/// `out_theme` must point to a writable, non-null `int32_t` location. #[no_mangle] -pub unsafe extern "C" fn uda_detect_theme(out_theme: *mut c_int) -> c_int { +pub unsafe extern "C" fn uda_detect_theme(out_theme: *mut i32) -> i32 { if out_theme.is_null() { util::set_last_message("`out_theme` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -156,7 +101,7 @@ pub unsafe extern "C" fn uda_detect_theme(out_theme: *mut c_int) -> c_int { /// /// `path` must be a valid, readable, null-terminated UTF-8 string. #[no_mangle] -pub unsafe extern "C" fn uda_set_wallpaper(path: *const c_char, fill_mode: c_int) -> c_int { +pub unsafe extern "C" fn uda_set_wallpaper(path: *const c_char, fill_mode: i32) -> i32 { if path.is_null() { util::set_last_message("`path` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -166,6 +111,11 @@ pub unsafe extern "C" fn uda_set_wallpaper(path: *const c_char, fill_mode: c_int // SAFETY: null was rejected above; the conversion walks to the null // terminator and rejects invalid UTF-8 instead of reading past it. let path = unsafe { util::owned_string_from(path, "path") }?; + if path.is_empty() { + return Err(error::Failure::InvalidArgument( + "`path` must not be empty".to_string(), + )); + } let fill_mode = fill_mode_from_c(fill_mode)?; dispatch::set_wallpaper(&path, fill_mode) }) @@ -174,11 +124,13 @@ pub unsafe extern "C" fn uda_set_wallpaper(path: *const c_char, fill_mode: c_int /// Read the metadata of the active media player. /// /// The three strings are allocated by Rust and must be released with -/// [`uda_free_string`]. An unpublished field - including a field the player -/// publishes as an empty string - is written as a null pointer, or zero for a -/// duration, so each pointer must be checked before it is read. With no player -/// running every out-parameter is set to null/zero and [`UDA_OK`] is still -/// returned. +/// [`uda_free_string`]. An unpublished field is written as a null pointer, or +/// zero for a duration, so each pointer must be checked before it is read. A +/// field published as an empty string stays an empty C string where the backend +/// can tell the two apart (Linux); on Windows an empty read also surfaces as +/// null, because SMTC has no "unset" marker on the wire, so a host must treat +/// null as "skip this field" everywhere. With no player running every +/// out-parameter is set to null/zero and [`UDA_OK`] is still returned. /// /// `out_position_ms` is optional: pass null to skip it. /// @@ -194,7 +146,7 @@ pub unsafe extern "C" fn uda_media_get_metadata( out_album: *mut *mut c_char, out_duration_ms: *mut u64, out_position_ms: *mut u64, -) -> c_int { +) -> i32 { if out_title.is_null() || out_artist.is_null() || out_album.is_null() @@ -209,9 +161,16 @@ pub unsafe extern "C" fn uda_media_get_metadata( util::catch_boundary(|| { let metadata = media::active_metadata()?.unwrap_or_default(); - let title = util::c_string_from(&metadata.title); - let artist = util::c_string_from(&metadata.artist); - let album = util::c_string_from(&metadata.album); + // The documented empty answer: an unpublished field is NULL rather + // than an empty C string, "no player" (which the backends already + // normalize into `None`) is NULL everywhere, and a zero duration + // means "unknown" - all with a UDA_OK status, so a now-playing card + // renders as empty instead of as a failure. + let title = c_string_or_null(metadata.title.as_deref()); + let artist = c_string_or_null(metadata.artist.as_deref()); + let album = c_string_or_null(metadata.album.as_deref()); + let duration_ms = metadata.duration_ms.unwrap_or(0); + let position_ms = metadata.position_ms.unwrap_or(0); // SAFETY: all four pointers were validated non-null and writable above; // `out_position_ms` is checked before the optional write. @@ -219,9 +178,9 @@ pub unsafe extern "C" fn uda_media_get_metadata( *out_title = title; *out_artist = artist; *out_album = album; - *out_duration_ms = metadata.duration_ms.unwrap_or(0); + *out_duration_ms = duration_ms; if !out_position_ms.is_null() { - *out_position_ms = metadata.position_ms.unwrap_or(0); + *out_position_ms = position_ms; } } Ok(()) @@ -230,18 +189,23 @@ pub unsafe extern "C" fn uda_media_get_metadata( /// Read the playback status of the active media player. /// -/// Writes one of [`UDA_MEDIA_PLAYING`], [`UDA_MEDIA_PAUSED`], -/// [`UDA_MEDIA_STOPPED`] or [`UDA_MEDIA_UNKNOWN`] to `*out_status`. -/// -/// [`UDA_MEDIA_UNKNOWN`] covers both "no player is running" and "the state -/// could not be determined"; it is never an error. A negative status means the -/// platform has no media backend at all. +/// Writes `UDA_MEDIA_PLAYING`, `UDA_MEDIA_PAUSED`, `UDA_MEDIA_STOPPED` or +/// `UDA_MEDIA_UNKNOWN` to `*out_status`. `UDA_MEDIA_UNKNOWN` covers both "no +/// player is running" and "the state could not be determined", and is +/// reported with [`UDA_OK`]: it is an answer, not a failure. A negative status +/// code means the backend itself could not be reached: on Linux, connecting to +/// the session bus or building the player proxy fails with +/// `UDA_ERR_DETECTION_FAILED`; on Windows, acquiring the SMTC session manager +/// fails with `UDA_ERR_NOT_SUPPORTED` or `UDA_ERR_DETECTION_FAILED`. A player +/// session that *is* selected but whose state cannot be read is not a +/// failure: that reports [`UDA_OK`] with `UDA_MEDIA_UNKNOWN`. On any negative +/// status `*out_status` is left untouched. /// /// # Safety /// -/// `out_status` must point at a writable `int32_t` location. +/// `out_status` must point to a writable, non-null `int32_t` location. #[no_mangle] -pub unsafe extern "C" fn uda_media_get_status(out_status: *mut c_int) -> c_int { +pub unsafe extern "C" fn uda_media_get_status(out_status: *mut i32) -> i32 { if out_status.is_null() { util::set_last_message("`out_status` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -270,7 +234,7 @@ pub unsafe extern "C" fn uda_media_get_status(out_status: *mut c_int) -> c_int { /// /// This function takes no pointers; there is nothing to validate. #[no_mangle] -pub unsafe extern "C" fn uda_media_send_command(command: c_int) -> c_int { +pub unsafe extern "C" fn uda_media_send_command(command: i32) -> i32 { util::catch_boundary(|| { let command = media::command_from_c(command)?; media::send_command(command) @@ -309,7 +273,7 @@ pub unsafe extern "C" fn uda_media_send_command(command: c_int) -> c_int { /// /// `out_capabilities` must point at a writable `uint32_t` location. #[no_mangle] -pub unsafe extern "C" fn uda_session_capabilities(out_capabilities: *mut u32) -> c_int { +pub unsafe extern "C" fn uda_session_capabilities(out_capabilities: *mut u32) -> i32 { if out_capabilities.is_null() { util::set_last_message("`out_capabilities` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -336,7 +300,7 @@ pub unsafe extern "C" fn uda_session_capabilities(out_capabilities: *mut u32) -> /// /// This function takes no pointers; there is nothing to validate. #[no_mangle] -pub unsafe extern "C" fn uda_session_lock() -> c_int { +pub unsafe extern "C" fn uda_session_lock() -> i32 { util::catch_boundary(|| session::perform(SessionAction::Lock)) } @@ -349,7 +313,7 @@ pub unsafe extern "C" fn uda_session_lock() -> c_int { /// /// This function takes no pointers; there is nothing to validate. #[no_mangle] -pub unsafe extern "C" fn uda_session_logout() -> c_int { +pub unsafe extern "C" fn uda_session_logout() -> i32 { util::catch_boundary(|| session::perform(SessionAction::Logout)) } @@ -365,7 +329,7 @@ pub unsafe extern "C" fn uda_session_logout() -> c_int { /// /// This function takes no pointers; there is nothing to validate. #[no_mangle] -pub unsafe extern "C" fn uda_session_suspend() -> c_int { +pub unsafe extern "C" fn uda_session_suspend() -> i32 { util::catch_boundary(|| session::perform(SessionAction::Suspend)) } @@ -378,7 +342,7 @@ pub unsafe extern "C" fn uda_session_suspend() -> c_int { /// /// This function takes no pointers; there is nothing to validate. #[no_mangle] -pub unsafe extern "C" fn uda_session_hibernate() -> c_int { +pub unsafe extern "C" fn uda_session_hibernate() -> i32 { util::catch_boundary(|| session::perform(SessionAction::Hibernate)) } @@ -395,7 +359,7 @@ pub unsafe extern "C" fn uda_session_hibernate() -> c_int { /// /// This function takes no pointers; there is nothing to validate. #[no_mangle] -pub unsafe extern "C" fn uda_session_reboot() -> c_int { +pub unsafe extern "C" fn uda_session_reboot() -> i32 { util::catch_boundary(|| session::perform(SessionAction::Reboot)) } @@ -410,7 +374,7 @@ pub unsafe extern "C" fn uda_session_reboot() -> c_int { /// /// This function takes no pointers; there is nothing to validate. #[no_mangle] -pub unsafe extern "C" fn uda_session_shutdown() -> c_int { +pub unsafe extern "C" fn uda_session_shutdown() -> i32 { util::catch_boundary(|| session::perform(SessionAction::Shutdown)) } @@ -425,9 +389,9 @@ pub unsafe extern "C" fn uda_session_shutdown() -> c_int { /// /// # Safety /// -/// `out_path` must be a valid, writable, non-null pointer location. +/// `out_path` must point to a writable, non-null pointer location. #[no_mangle] -pub unsafe extern "C" fn uda_get_wallpaper(out_path: *mut *mut c_char) -> c_int { +pub unsafe extern "C" fn uda_get_wallpaper(out_path: *mut *mut c_char) -> i32 { if out_path.is_null() { util::set_last_message("`out_path` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -448,6 +412,8 @@ pub unsafe extern "C" fn uda_get_wallpaper(out_path: *mut *mut c_char) -> c_int }) } +/// Release a string previously returned by this library. +/// /// # Safety /// /// `s` must be null or a pointer obtained from an export that transfers string @@ -466,9 +432,18 @@ pub unsafe extern "C" fn uda_free_string(s: *mut c_char) { /// Acquire a wake lock. /// -/// `lock_type` is [`UDA_WAKELOCK_DISPLAY`] or [`UDA_WAKELOCK_SYSTEM`]. On -/// success `*out_handle` receives a non-zero handle to pass to -/// [`uda_wakelock_release`]; on failure it is left untouched. +/// `lock_type` is `UDA_WAKELOCK_DISPLAY` or `UDA_WAKELOCK_SYSTEM`; `reason` +/// is a null-terminated UTF-8 description used for diagnostics. On success +/// `*out_handle` receives a non-zero handle to pass to +/// `uda_wakelock_release()`; on failure it is left untouched. +/// +/// On Linux, when the native IPC tiers are unavailable, the fallback holds +/// the lock by running `systemd-inhibit` for at most 3600 seconds. That +/// fallback lock expires silently at the cap and must be re-acquired; the +/// native tiers are not capped. A successful acquire records no error message +/// of its own, but it does not clear an unread message left by an earlier +/// failure on the same thread; read `uda_last_error_message()` only after a +/// non-`UDA_OK` status. /// /// A lock acquired through the CLI fallback (no native IPC available) is /// bounded to roughly one hour: past that deadline the lock is retired and its @@ -477,14 +452,14 @@ pub unsafe extern "C" fn uda_free_string(s: *mut c_char) { /// /// # Safety /// -/// `out_handle` must be a valid, writable, non-null `uint64_t` location and -/// `reason` a readable, null-terminated UTF-8 string. +/// `out_handle` must point to a writable, non-null `uint64_t` location and +/// `reason` must be a readable, null-terminated UTF-8 string. #[no_mangle] pub unsafe extern "C" fn uda_wakelock_acquire( - lock_type: c_int, + lock_type: i32, reason: *const c_char, out_handle: *mut u64, -) -> c_int { +) -> i32 { if out_handle.is_null() { util::set_last_message("`out_handle` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -505,13 +480,13 @@ pub unsafe extern "C" fn uda_wakelock_acquire( }) } -/// Release a wake lock previously obtained from [`uda_wakelock_acquire`]. +/// Release a wake lock previously obtained from `uda_wakelock_acquire()`. /// /// Returns `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live lock in /// this process (already released, never issued here, or a fallback lock /// retired after its bounded lifetime elapsed). #[no_mangle] -pub extern "C" fn uda_wakelock_release(handle: u64) -> c_int { +pub extern "C" fn uda_wakelock_release(handle: u64) -> i32 { util::catch_boundary(|| { let handle = dispatch::WakeLockHandle::from_raw(handle) .ok_or_else(|| error::Failure::InvalidArgument("`handle` must not be 0".to_string()))?; @@ -521,22 +496,37 @@ pub extern "C" fn uda_wakelock_release(handle: u64) -> c_int { /// Send a system notification. /// -/// The five strings are the app's `app_name`, a one-line `title`, a multi-line -/// `body`, an optional `icon` (path or URI; empty means none), and `actions` as -/// a flat newline-separated list of `key\nlabel` records. Any string may be -/// null, which is treated as the empty string. -/// -/// `app_name` is the AppUserModelID on Windows, where UDA registers it for an -/// unpackaged process; empty (or null) selects the generic -/// `UniDesktop.Notification` identity. -/// -/// On success `*out_id` receives the id the notification server assigned; it is -/// left untouched on failure. +/// The five strings cover what a notification needs: the sending app's +/// `app_name`, a one-line `title`, a multi-line `body`, an optional `icon` +/// (path or URI; empty means none), and `actions` as a flat newline-separated +/// list of `key\nlabel` records. Any string may be NULL, which is treated as +/// the empty string. +/// +/// `app_name` is not cosmetic: on Windows it is the AppUserModelID the toast +/// is addressed to, and an unpackaged process has none. UDA registers it as +/// the process's explicit AUMID before the first toast is shown, which is +/// what lets a plain `node script.js` display a native toast. Passing NULL +/// or "" selects the generic "UniDesktop.Notification" identity. +/// +/// On Windows, toast *buttons* still require a packaged (MSIX) identity, so +/// `actions` is accepted for parity but not surfaced; the toast itself +/// displays normally. Rust callers can probe further with +/// `WindowsNotificationManager::availability()`; the C-ABI surface has no +/// notification-availability probe. +/// +/// A trailing `key` without its `label` is dropped rather than rendered as a +/// blank button. The remaining FreeDesktop fields keep their defaults: +/// `replaces_id` is 0 (a new notification), the expiry is the server +/// default, and the urgency is normal. Callers needing those must use the +/// Rust API. +/// +/// On success `*out_id` receives the id the notification server assigned; it +/// is left untouched on failure. /// /// # Safety /// -/// `out_id` must be a valid, writable, non-null `uint32_t` location. The five -/// strings must each be null or readable, null-terminated UTF-8. +/// `out_id` must point to a writable, non-null `uint32_t` location. The five +/// strings must each be NULL or readable, null-terminated UTF-8. #[no_mangle] pub unsafe extern "C" fn uda_notify( app_name: *const c_char, @@ -545,7 +535,7 @@ pub unsafe extern "C" fn uda_notify( icon: *const c_char, actions: *const c_char, out_id: *mut u32, -) -> c_int { +) -> i32 { if out_id.is_null() { util::set_last_message("`out_id` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -566,18 +556,18 @@ pub unsafe extern "C" fn uda_notify( }) } -/// Read the system accent colour. +/// Read the system accent colour as four channels. /// -/// Writes the four 0..=255 channels to `*out_rgba` as R, G, B, A. A platform -/// that exposes no accent colour (most Linux desktops) leaves the slot -/// untouched and still returns [`UDA_OK`], so treat a zeroed slot as -/// "no accent" rather than a failure. +/// Writes R, G, B, A (each in the 0-255 range) to the four bytes at +/// `out_rgba`. A platform that exposes no accent colour - most Linux +/// desktops - leaves the bytes untouched and still returns `UDA_OK`, so a +/// zeroed slot means "no accent", not failure. /// /// # Safety /// -/// `out_rgba` must point at four writable `uint8_t` values. +/// `out_rgba` must point to four writable `uint8_t` values. #[no_mangle] -pub unsafe extern "C" fn uda_get_accent_color(out_rgba: *mut u8) -> c_int { +pub unsafe extern "C" fn uda_get_accent_color(out_rgba: *mut u8) -> i32 { if out_rgba.is_null() { util::set_last_message("`out_rgba` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -618,16 +608,11 @@ pub extern "C" fn uda_last_error_message() -> *mut c_char { /// Describe a status code with a static string. /// -/// Convenience for bindings that want to render a failure without a second FFI -/// round-trip. The returned pointer stays valid for the lifetime of the library -/// and must **not** be freed. -/// -/// The text is copied into a null-terminated buffer before it crosses the -/// boundary: a Rust `&str` is *not* null-terminated, so handing out -/// `str::as_ptr()` would let a C caller read past the message. One `CString` per -/// code is cached and reused. +/// The returned pointer is valid for the lifetime of the library and must +/// not be freed. Useful for rendering a failure without a second FFI +/// round-trip. #[no_mangle] -pub extern "C" fn uda_status_message(status: c_int) -> *const c_char { +pub extern "C" fn uda_status_message(status: i32) -> *const c_char { STATUS_MESSAGES.with(|cache| { let mut cache = cache.borrow_mut(); if let Some(pointer) = cache.get(&status) { @@ -647,9 +632,9 @@ pub extern "C" fn uda_status_message(status: c_int) -> *const c_char { // The C caller cannot hold an `Arc`, so every tray icon and context menu lives // in a process-wide table keyed by an opaque `uint64_t`. Handles start at `1`; -// `0` means "no handle". A handle is single-use: a second destroy of the same -// value is `UDA_ERR_INVALID_ARGUMENT` rather than a silent no-op, so a host -// cannot double-release a shell resource. +// `0` means "no handle". A handle can be destroyed exactly once: a second +// destroy of the same value is `UDA_ERR_INVALID_ARGUMENT` rather than a silent +// no-op, so a host cannot double-release a shell resource. /// Report which tray features the active platform backend advertises. /// @@ -669,7 +654,7 @@ pub extern "C" fn uda_status_message(status: c_int) -> *const c_char { /// /// `out_capabilities` must point at a writable `uint32_t` location. #[no_mangle] -pub unsafe extern "C" fn uda_tray_capabilities(out_capabilities: *mut u32) -> c_int { +pub unsafe extern "C" fn uda_tray_capabilities(out_capabilities: *mut u32) -> i32 { if out_capabilities.is_null() { util::set_last_message("`out_capabilities` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -678,8 +663,8 @@ pub unsafe extern "C" fn uda_tray_capabilities(out_capabilities: *mut u32) -> c_ util::catch_boundary(|| { // The C ABI cannot deliver click callbacks, so the backend's click bits // are masked off rather than advertised. See the doc comment above. - const UNDELIVERABLE_BY_C_ABI: u32 = - tray::UDA_TRAY_CAP_CLICK | tray::UDA_TRAY_CAP_DOUBLE_CLICK; + // The bit values live in `crate::abi` with the rest of the C ABI. + const UNDELIVERABLE_BY_C_ABI: u32 = UDA_TRAY_CAP_CLICK | UDA_TRAY_CAP_DOUBLE_CLICK; // SAFETY: null was rejected above, and the caller guarantees a writable // `uint32_t` at this address. unsafe { *out_capabilities = tray::capabilities().bits() & !UNDELIVERABLE_BY_C_ABI }; @@ -709,7 +694,7 @@ pub unsafe extern "C" fn uda_tray_capabilities(out_capabilities: *mut u32) -> c_ /// /// `out_level` must point at a writable `int32_t` location. #[no_mangle] -pub unsafe extern "C" fn uda_tray_support_level(handle: u64, out_level: *mut i32) -> c_int { +pub unsafe extern "C" fn uda_tray_support_level(handle: u64, out_level: *mut i32) -> i32 { if out_level.is_null() { util::set_last_message("`out_level` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -737,10 +722,7 @@ pub unsafe extern "C" fn uda_tray_support_level(handle: u64, out_level: *mut i32 /// /// `out_reason` must point at a writable pointer location. #[no_mangle] -pub unsafe extern "C" fn uda_tray_support_reason( - handle: u64, - out_reason: *mut *mut c_char, -) -> c_int { +pub unsafe extern "C" fn uda_tray_support_reason(handle: u64, out_reason: *mut *mut c_char) -> i32 { if out_reason.is_null() { util::set_last_message("`out_reason` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -772,18 +754,20 @@ pub unsafe extern "C" fn uda_tray_support_reason( /// and registration still succeeds either way. /// /// On success `*out_handle` receives a non-zero handle for every other -/// `uda_tray_*` call. On failure it is left untouched. +/// `uda_tray_*` call. On failure it is left untouched. The icon has no image +/// until `uda_tray_set_icon_path()` or `uda_tray_set_icon_rgba()` supplies +/// one, so it can be prepared and only made visible once built. /// /// # Safety /// -/// `out_handle` must be a valid, writable, non-null `uint64_t` slot. -/// `name` and `tooltip` must be null or readable, null-terminated UTF-8 strings. +/// `out_handle` must point to a writable, non-null `uint64_t` slot. `name` +/// and `tooltip` must be NULL or readable, null-terminated UTF-8 strings. #[no_mangle] pub unsafe extern "C" fn uda_tray_create( name: *const c_char, tooltip: *const c_char, out_handle: *mut u64, -) -> c_int { +) -> i32 { if out_handle.is_null() { util::set_last_message("`out_handle` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -813,28 +797,31 @@ pub unsafe extern "C" fn uda_tray_create( /// Replace a tray icon's tooltip. /// +/// `tooltip` is null-terminated UTF-8 text, or NULL to clear it. +/// /// # Safety /// -/// `tooltip` must be a readable, null-terminated UTF-8 string, or null for the -/// empty string. +/// `tooltip` must be a readable, null-terminated UTF-8 string, or NULL for +/// the empty string. #[no_mangle] -pub unsafe extern "C" fn uda_tray_set_tooltip(handle: u64, tooltip: *const c_char) -> c_int { +pub unsafe extern "C" fn uda_tray_set_tooltip(handle: u64, tooltip: *const c_char) -> i32 { util::catch_boundary(|| { let tooltip = owned_or_empty(tooltip, "tooltip")?; tray::set_tooltip(handle, &tooltip) }) } -/// Replace a tray icon's image from a filesystem path or icon-theme name. +/// Replace a tray icon's image from a file or icon-theme name. /// -/// On Linux the value is also accepted as a freedesktop icon-theme name; on -/// Windows it must be a file path (`.ico`, `.png`, `.bmp`). +/// `path` is a null-terminated UTF-8 path. Linux also accepts a freedesktop +/// icon-theme name here; Windows requires a file path (`.ico`, `.cur`, +/// `.bmp`). /// /// # Safety /// /// `path` must be a readable, null-terminated UTF-8 string. #[no_mangle] -pub unsafe extern "C" fn uda_tray_set_icon_path(handle: u64, path: *const c_char) -> c_int { +pub unsafe extern "C" fn uda_tray_set_icon_path(handle: u64, path: *const c_char) -> i32 { if path.is_null() { util::set_last_message("`path` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -846,16 +833,17 @@ pub unsafe extern "C" fn uda_tray_set_icon_path(handle: u64, path: *const c_char }) } -/// Replace a tray icon's image from raw RGBA pixels. +/// Replace a tray icon's image from raw pixels. /// -/// The buffer is **borrowed**: only `stride * height` bytes are copied, and the -/// caller keeps ownership of `data`. Pixels are top-down, four bytes per pixel -/// (red, green, blue, alpha). A buffer shorter than `stride * height` is -/// rejected with `UDA_ERR_INVALID_ARGUMENT` before a pixel is read. +/// The buffer is borrowed: only `stride * height` bytes are copied and the +/// caller keeps ownership of `data`. Pixels are top-down RGBA, four bytes +/// each. A zero `width` or `height`, a `stride` smaller than `width * 4`, or +/// a `len` smaller than `stride * height` is rejected with +/// `UDA_ERR_INVALID_ARGUMENT` before any pixel is read. /// /// # Safety /// -/// `data` must point to `len` readable bytes. +/// `data` must not be null and must point to `len` readable bytes. #[no_mangle] pub unsafe extern "C" fn uda_tray_set_icon_rgba( handle: u64, @@ -864,7 +852,7 @@ pub unsafe extern "C" fn uda_tray_set_icon_rgba( stride: u32, data: *const u8, len: usize, -) -> c_int { +) -> i32 { if data.is_null() { util::set_last_message("`data` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -875,32 +863,34 @@ pub unsafe extern "C" fn uda_tray_set_icon_rgba( /// Show or hide the icon without unregistering it. /// -/// `visible` is a C boolean: `0` hides, any other value shows. +/// `visible` is a C boolean: 0 hides, any other value shows. #[no_mangle] -pub extern "C" fn uda_tray_set_visible(handle: u64, visible: c_int) -> c_int { +pub extern "C" fn uda_tray_set_visible(handle: u64, visible: i32) -> i32 { util::catch_boundary(|| tray::set_visible(handle, visible != 0)) } /// Destroy a tray icon and unregister it from the shell. /// -/// Returns `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live icon in this -/// process. Destroying is terminal: the handle cannot be reused. A menu attached -/// to the icon survives it, because the icon keeps its own `Arc`. +/// Terminal: the handle cannot be reused afterwards. Menus previously +/// attached keep their own handles and stay valid. Returns +/// `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live tray icon in +/// this process. #[no_mangle] -pub extern "C" fn uda_tray_destroy(handle: u64) -> c_int { +pub extern "C" fn uda_tray_destroy(handle: u64) -> i32 { util::catch_boundary(|| tray::destroy_icon(handle)) } /// Create an empty context menu. /// -/// On success `*out_menu_handle` receives a non-zero handle for -/// `uda_tray_menu_add_*` and [`uda_tray_set_menu`]. +/// On success `*out_menu_handle` receives a non-zero handle for the +/// `uda_tray_menu_add_*` functions and `uda_tray_set_menu()`. On failure it +/// is left untouched. /// /// # Safety /// -/// `out_menu_handle` must be a valid, writable, non-null `uint64_t` slot. +/// `out_menu_handle` must point to a writable, non-null `uint64_t` slot. #[no_mangle] -pub unsafe extern "C" fn uda_tray_menu_create(out_menu_handle: *mut u64) -> c_int { +pub unsafe extern "C" fn uda_tray_menu_create(out_menu_handle: *mut u64) -> i32 { if out_menu_handle.is_null() { util::set_last_message("`out_menu_handle` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -921,8 +911,9 @@ pub unsafe extern "C" fn uda_tray_menu_create(out_menu_handle: *mut u64) -> c_in /// API to read a row's state. `user_data` is handed back to the callback /// untouched and is never dereferenced by UDA. /// -/// On success `*out_item_id` receives the row's stable, non-zero id, which the -/// callback also receives so a host does not need its own table. +/// On success `*out_item_id` receives the row's stable, non-zero id; the +/// callback receives the same value, so a host does not need a table of its +/// own. /// /// # Safety /// @@ -934,10 +925,10 @@ pub unsafe extern "C" fn uda_tray_menu_create(out_menu_handle: *mut u64) -> c_in pub unsafe extern "C" fn uda_tray_menu_add_text( menu_handle: u64, label: *const c_char, - callback: Option, + callback: UdaTrayTextCallback, user_data: *mut c_void, out_item_id: *mut u64, -) -> c_int { +) -> i32 { if out_item_id.is_null() { util::set_last_message("`out_item_id` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -957,9 +948,10 @@ pub unsafe extern "C" fn uda_tray_menu_add_text( /// Append a visual separator to a menu. /// -/// A separator has no label, no callback and no id, so nothing is returned. +/// A separator has no label, no callback and no id, so there is no +/// out-parameter. #[no_mangle] -pub extern "C" fn uda_tray_menu_add_separator(menu_handle: u64) -> c_int { +pub extern "C" fn uda_tray_menu_add_separator(menu_handle: u64) -> i32 { util::catch_boundary(|| tray::menu_add_separator(menu_handle)) } @@ -973,17 +965,17 @@ pub extern "C" fn uda_tray_menu_add_separator(menu_handle: u64) -> c_int { /// /// # Safety /// -/// `out_item_id` must be a valid, writable, non-null `uint64_t` slot. `label` -/// must be a readable, null-terminated UTF-8 string. +/// `out_item_id` must point to a writable, non-null `uint64_t` slot and +/// `label` must be a readable, null-terminated UTF-8 string. #[no_mangle] pub unsafe extern "C" fn uda_tray_menu_add_checkbox( menu_handle: u64, label: *const c_char, - checked: c_int, - callback: Option, + checked: i32, + callback: UdaTrayCheckboxCallback, user_data: *mut c_void, out_item_id: *mut u64, -) -> c_int { +) -> i32 { if out_item_id.is_null() { util::set_last_message("`out_item_id` must not be null"); return UDA_ERR_INVALID_ARGUMENT; @@ -1011,7 +1003,7 @@ pub unsafe extern "C" fn uda_tray_menu_add_checkbox( /// later. Destroying the handle (see [`uda_tray_menu_destroy`]) detaches the /// menu from every icon still showing it. #[no_mangle] -pub extern "C" fn uda_tray_set_menu(tray_handle: u64, menu_handle: u64) -> c_int { +pub extern "C" fn uda_tray_set_menu(tray_handle: u64, menu_handle: u64) -> i32 { util::catch_boundary(|| tray::set_menu(tray_handle, menu_handle)) } @@ -1028,7 +1020,7 @@ pub extern "C" fn uda_tray_set_menu(tray_handle: u64, menu_handle: u64) -> c_int /// its own callback to return and retries will succeed; the host may free its /// callback trampolines only after this call reports success. #[no_mangle] -pub extern "C" fn uda_tray_menu_destroy(menu_handle: u64) -> c_int { +pub extern "C" fn uda_tray_menu_destroy(menu_handle: u64) -> i32 { util::catch_boundary(|| tray::destroy_menu(menu_handle)) } @@ -1046,15 +1038,37 @@ fn owned_or_empty(pointer: *const c_char, parameter: &str) -> Result) -> *mut c_char { + match text { + // The only failure is an interior NUL, which no backend can produce; + // reporting it as "not published" is still the correct C answer. + Some(text) => match std::ffi::CString::new(text) { + Ok(c_string) => c_string.into_raw(), + Err(_) => std::ptr::null_mut(), + }, + None => std::ptr::null_mut(), + } +} + thread_local! { /// Cache of the leaked status-message strings, so repeated calls with the /// same code reuse a single allocation instead of leaking one per call. - static STATUS_MESSAGES: std::cell::RefCell> = + static STATUS_MESSAGES: std::cell::RefCell> = std::cell::RefCell::new(std::collections::HashMap::new()); } /// Map a C fill-mode code onto the cross-platform [`FillMode`](uda_core::wallpaper::FillMode). -fn fill_mode_from_c(code: c_int) -> Result { +fn fill_mode_from_c(code: i32) -> Result { use uda_core::wallpaper::FillMode; let fill_mode = match code { UDA_FILL_CROP => FillMode::Crop, @@ -1071,7 +1085,7 @@ fn fill_mode_from_c(code: c_int) -> Result Result { +fn wake_lock_type_from_c(code: i32) -> Result { use uda_core::wakelock::WakeLockType; let lock_type = match code { UDA_WAKELOCK_DISPLAY => WakeLockType::PreventDisplaySleep, @@ -1091,11 +1105,83 @@ mod tests { use std::ffi::CString; #[test] - fn status_constants_match_the_error_module() { - assert_eq!(UDA_OK, error::UDA_OK); - assert_eq!(UDA_ERR_INVALID_ARGUMENT, error::UDA_ERR_INVALID_ARGUMENT); - assert_eq!(UDA_ERR_NOT_SUPPORTED, error::UDA_ERR_NOT_SUPPORTED); - assert_eq!(UDA_ERR_PANIC, error::UDA_ERR_PANIC); + fn metadata_fields_distinguish_published_empty_from_unpublished() { + // Unpublished -> NULL, the documented "skip this field" answer. + assert!(c_string_or_null(None).is_null()); + // Published as an empty string -> a real, empty C string, so a host + // that cares can tell the two apart; the caller frees it like any + // other library string. + let pointer = c_string_or_null(Some("")); + assert!(!pointer.is_null()); + // SAFETY: the pointer came from `c_string_or_null` in this test. + let text = unsafe { std::ffi::CStr::from_ptr(pointer) } + .to_str() + .expect("empty string is valid UTF-8"); + assert_eq!(text, ""); + // SAFETY: same pointer, freed exactly once. + unsafe { util::free_c_string(pointer) }; + // Published text -> the text, read back verbatim. + let pointer = c_string_or_null(Some("/music/track.flac")); + assert!(!pointer.is_null()); + // SAFETY: the pointer came from `c_string_or_null` in this test. + let text = unsafe { std::ffi::CStr::from_ptr(pointer) } + .to_str() + .expect("the path is valid UTF-8"); + assert_eq!(text, "/music/track.flac"); + // SAFETY: same pointer, freed exactly once. + unsafe { util::free_c_string(pointer) }; + } + + #[test] + fn media_get_metadata_rejects_a_null_out_parameter() { + // Every string slot and the duration slot are mandatory (the position + // slot is the only optional one). Validation runs before any backend + // call, so this needs no player. + // + // The slots start at sentinels rather than NULL/0: a rejected call must + // write nothing, and the documented empty answer is itself NULL/0, so a + // zeroed slot could not distinguish "untouched" from "overwritten". + // The sentinel pointer is only ever compared by address, never + // dereferenced, so it does not have to point at valid memory. + let sentinel: *mut c_char = std::ptr::NonNull::::dangling().as_ptr(); + let mut title = sentinel; + let mut artist = sentinel; + let mut album = sentinel; + let mut duration: u64 = 99; + + // SAFETY: the pointers are live locals; `out_title` is deliberately + // null, which is exactly the case under test. + let status = unsafe { + uda_media_get_metadata( + std::ptr::null_mut(), + &mut artist, + &mut album, + &mut duration, + std::ptr::null_mut(), + ) + }; + assert_eq!(status, UDA_ERR_INVALID_ARGUMENT); + assert!(util::take_last_message().is_some()); + + // SAFETY: `out_duration_ms` is deliberately null this time. + let status = unsafe { + uda_media_get_metadata( + &mut title, + &mut artist, + &mut album, + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + assert_eq!(status, UDA_ERR_INVALID_ARGUMENT); + + // A rejected call writes nothing into the slots it was given: had the + // null check fallen through into the body, these would be NULL/0 (the + // "no player" answer) instead of the sentinels. + assert_eq!(title, sentinel); + assert_eq!(artist, sentinel); + assert_eq!(album, sentinel); + assert_eq!(duration, 99); } #[test] @@ -1123,7 +1209,7 @@ mod tests { #[test] fn detect_theme_writes_into_the_out_parameter() { - let mut theme: c_int = -100; + let mut theme: i32 = -100; // SAFETY: `theme` is a live, writable `int32_t` on this stack frame. let status = unsafe { uda_detect_theme(&mut theme) }; if status == UDA_ERR_NOT_SUPPORTED { @@ -1167,7 +1253,7 @@ mod tests { let path = CString::new("").expect("empty string is valid"); // SAFETY: `path` is a valid, empty C string. let status = unsafe { uda_set_wallpaper(path.as_ptr(), UDA_FILL_FILL) }; - assert!(status < 0, "an empty path must fail, got {status}"); + assert_eq!(status, UDA_ERR_INVALID_ARGUMENT); } #[test] @@ -1356,8 +1442,7 @@ mod tests { // The C ABI has no click-callback registration, so those bits are // deliberately cleared even when the platform backend can measure // clicks. - const UNDELIVERABLE_BY_C_ABI: u32 = - tray::UDA_TRAY_CAP_CLICK | tray::UDA_TRAY_CAP_DOUBLE_CLICK; + const UNDELIVERABLE_BY_C_ABI: u32 = UDA_TRAY_CAP_CLICK | UDA_TRAY_CAP_DOUBLE_CLICK; assert_eq!( bits & UNDELIVERABLE_BY_C_ABI, 0, @@ -1367,7 +1452,7 @@ mod tests { // Every other bit must forward the backend's answer verbatim. assert_eq!(bits, tray::capabilities().bits() & !UNDELIVERABLE_BY_C_ABI); assert_eq!( - bits & !tray::DOCUMENTED_TRAY_CAPABILITIES, + bits & !abi::DOCUMENTED_TRAY_CAPABILITIES, 0, "undocumented tray capability bits: {bits:#x}" ); diff --git a/crates/uda-ffi/src/media.rs b/crates/uda-ffi/src/media.rs index b6eb1cc..f44f0b1 100644 --- a/crates/uda-ffi/src/media.rs +++ b/crates/uda-ffi/src/media.rs @@ -13,7 +13,7 @@ //! returning the code, so the return value stays free to report *hard* failures //! (status `-2` when the platform has no media backend at all). A "no player is //! running" is **not** a failure: it is reported as `UDA_MEDIA_UNKNOWN` (3) with -//! status [`UDA_OK`](crate::error::UDA_OK). A caller must therefore treat code 3 +//! status [`UDA_OK`](crate::abi::UDA_OK). A caller must therefore treat code 3 //! as "nothing playing", never as a paused track. //! //! # Ownership @@ -24,7 +24,7 @@ //! for a player that publishes only a title. //! //! A refused command (an app that disables `Next`, for example) returns -//! [`UDA_ERR_NOT_SUPPORTED`](crate::error::UDA_ERR_NOT_SUPPORTED) so a caller can +//! [`UDA_ERR_NOT_SUPPORTED`](crate::abi::UDA_ERR_NOT_SUPPORTED) so a caller can //! tell "there was nobody to command" from "the player declined it". use uda_core::media::{MediaCommand, MediaMetadata, PlaybackStatus}; @@ -36,28 +36,6 @@ use uda_core::media::MediaManager as _; use crate::error::Failure; -/// Playback-status code for "audio or video is actively progressing". -pub const UDA_MEDIA_PLAYING: i32 = 0; -/// Playback-status code for "a track is selected and halted". -pub const UDA_MEDIA_PAUSED: i32 = 1; -/// Playback-status code for "nothing is loaded". -pub const UDA_MEDIA_STOPPED: i32 = 2; -/// Playback-status code for "cannot tell" (includes "no player"). -pub const UDA_MEDIA_UNKNOWN: i32 = 3; - -/// Command code for "start or resume playback". -pub const UDA_MEDIA_CMD_PLAY: i32 = 0; -/// Command code for "halt playback but keep the track". -pub const UDA_MEDIA_CMD_PAUSE: i32 = 1; -/// Command code for "play/pause". -pub const UDA_MEDIA_CMD_TOGGLE: i32 = 2; -/// Command code for "next track". -pub const UDA_MEDIA_CMD_NEXT: i32 = 3; -/// Command code for "previous track". -pub const UDA_MEDIA_CMD_PREVIOUS: i32 = 4; -/// Command code for "stop playback". -pub const UDA_MEDIA_CMD_STOP: i32 = 5; - /// Resolve a command code into the core enum. /// /// An unknown code is rejected here rather than silently mapped, because sending @@ -144,6 +122,11 @@ pub(crate) fn send_command(command: MediaCommand) -> Result<(), Failure> { #[cfg(test)] mod tests { use super::*; + use crate::abi::{ + UDA_MEDIA_CMD_NEXT, UDA_MEDIA_CMD_PAUSE, UDA_MEDIA_CMD_PLAY, UDA_MEDIA_CMD_PREVIOUS, + UDA_MEDIA_CMD_STOP, UDA_MEDIA_CMD_TOGGLE, UDA_MEDIA_PAUSED, UDA_MEDIA_PLAYING, + UDA_MEDIA_STOPPED, UDA_MEDIA_UNKNOWN, + }; use uda_core::error::UdaError; #[test] diff --git a/crates/uda-ffi/src/session.rs b/crates/uda-ffi/src/session.rs index 4c4d820..e009408 100644 --- a/crates/uda-ffi/src/session.rs +++ b/crates/uda-ffi/src/session.rs @@ -15,7 +15,7 @@ //! - `session_capabilities`, a side-effect-free query returning a bitmask, so //! a UI can be built *before* the user asks for anything; and //! - the six action functions, each of which performs an irreversible operation -//! the moment it returns [`UDA_OK`](crate::error::UDA_OK). +//! the moment it returns [`UDA_OK`](crate::abi::UDA_OK). //! //! Only `uda_session_lock` is safe to automate. Everything else must be gated //! behind a confirmation in the host application - the same rule the demo under @@ -33,21 +33,6 @@ use uda_core::session::{SessionAction, SessionManager}; use crate::error::Failure; -/// Capability bit: a session backend exists at all. -pub const UDA_SESSION_CAP_MANAGEMENT: u32 = 1 << 16; -/// Capability bit: the session can be locked (the only safe-to-automate one). -pub const UDA_SESSION_CAP_LOCK: u32 = 1 << 17; -/// Capability bit: the calling user's session can be logged out. -pub const UDA_SESSION_CAP_LOGOUT: u32 = 1 << 18; -/// Capability bit: the machine can be suspended to RAM. -pub const UDA_SESSION_CAP_SUSPEND: u32 = 1 << 19; -/// Capability bit: the machine can be hibernated to disk. -pub const UDA_SESSION_CAP_HIBERNATE: u32 = 1 << 20; -/// Capability bit: the machine can be rebooted. -pub const UDA_SESSION_CAP_REBOOT: u32 = 1 << 21; -/// Capability bit: the machine can be powered off. -pub const UDA_SESSION_CAP_SHUTDOWN: u32 = 1 << 22; - /// The actions the current platform's backend can deliver, as a bitmask. /// /// The bitmask is made of the `UDA_SESSION_CAP_*` constants and never @@ -119,6 +104,11 @@ fn run(manager: &M, action: SessionAction) -> Result<(), Fail #[cfg(test)] mod tests { use super::*; + use crate::abi::{ + UDA_SESSION_CAP_HIBERNATE, UDA_SESSION_CAP_LOCK, UDA_SESSION_CAP_LOGOUT, + UDA_SESSION_CAP_MANAGEMENT, UDA_SESSION_CAP_REBOOT, UDA_SESSION_CAP_SHUTDOWN, + UDA_SESSION_CAP_SUSPEND, + }; use uda_core::error::UdaError; /// A manager that refuses everything and records nothing. diff --git a/crates/uda-ffi/src/tray.rs b/crates/uda-ffi/src/tray.rs index 918ca14..7f8b8ec 100644 --- a/crates/uda-ffi/src/tray.rs +++ b/crates/uda-ffi/src/tray.rs @@ -58,21 +58,21 @@ use uda_core::tray::{ #[cfg(any(target_os = "linux", target_os = "windows"))] use uda_core::tray::TrayManager as _; +use crate::abi::{ + UdaTrayCheckboxCallback, UdaTrayTextCallback, UDA_TRAY_SUPPORT_LEVEL_FULL, + UDA_TRAY_SUPPORT_LEVEL_NONE, UDA_TRAY_SUPPORT_LEVEL_PARTIAL, +}; +// The capability bits are part of the header, so their literal values live in +// `crate::abi`; this module only consumes them, and only in tests. +#[cfg(test)] +use crate::abi::{ + DOCUMENTED_TRAY_CAPABILITIES, UDA_TRAY_CAP_CHECKBOX, UDA_TRAY_CAP_CLICK, + UDA_TRAY_CAP_CONTEXT_MENU, UDA_TRAY_CAP_DOUBLE_CLICK, UDA_TRAY_CAP_DYNAMIC_MENU, + UDA_TRAY_CAP_ICON, UDA_TRAY_CAP_SYSTEM_TRAY, UDA_TRAY_CAP_TOOLTIP, +}; use crate::dispatch; use crate::error::Failure; -/// Raw C callback invoked when a plain text row is activated. -/// -/// Arguments are the row's item id as returned by `uda_tray_menu_add_text` and -/// the `user_data` pointer registered alongside it. -pub type TextCallback = extern "C" fn(u64, *mut c_void); - -/// Raw C callback invoked when a checkbox row is toggled. -/// -/// Arguments are the row's item id, the **new** checked state (`0` or `1`) after -/// the toggle has been applied, and the `user_data` pointer. -pub type CheckboxCallback = extern "C" fn(u64, i32, *mut c_void); - /// A `*mut c_void` opaque payload that may cross a thread boundary. /// /// `TrayAction` requires `FnMut + Send`, but the host's `user_data` pointer is @@ -100,59 +100,6 @@ impl SendVoidPtr { } } -/// Capability bit: a tray backend exists at all (`SYSTEM_TRAY` in `uda-core`). -pub const UDA_TRAY_CAP_SYSTEM_TRAY: u32 = 1 << 7; -/// Capability bit: the icon can be shown, hidden and swapped at runtime. -pub const UDA_TRAY_CAP_ICON: u32 = 1 << 8; -/// Capability bit: the tray exposes hover text. -pub const UDA_TRAY_CAP_TOOLTIP: u32 = 1 << 9; -/// Capability bit: the tray reports a single primary click. -/// -/// Reserved: the C ABI has no click-callback registration, so -/// `uda_tray_capabilities` always clears this bit. It stays defined for a -/// future click API; do not infer click events from the bitmask today. -pub const UDA_TRAY_CAP_CLICK: u32 = 1 << 10; -/// Capability bit: the tray reports a native double click (never true on Linux -/// SNI, where it would have to be synthesised). -/// -/// Reserved for the same reason as [`UDA_TRAY_CAP_CLICK`]: the C ABI cannot -/// register a click callback, so `uda_tray_capabilities` always clears it. -pub const UDA_TRAY_CAP_DOUBLE_CLICK: u32 = 1 << 11; -/// Capability bit: the tray exposes a context menu. -pub const UDA_TRAY_CAP_CONTEXT_MENU: u32 = 1 << 12; -/// Capability bit: menu rows can render a checkbox state. -pub const UDA_TRAY_CAP_CHECKBOX: u32 = 1 << 13; -/// Capability bit: menu rows can be added at runtime; the C ABI does not -/// expose removal or relabelling (the Rust core supports both). -pub const UDA_TRAY_CAP_DYNAMIC_MENU: u32 = 1 << 14; - -/// Support-level code: the backend never claimed a tray at all. -/// -/// Unreachable through handles `uda_tray_create` handed out - every created -/// icon publishes the backend's capability set - but the mapping stays total, -/// so a fabricated or half-registered icon cannot be read as healthy. -pub const UDA_TRAY_SUPPORT_LEVEL_NONE: i32 = 0; -/// Support-level code: the icon is live, but registration recorded a -/// degradation (on Linux: no `StatusNotifierWatcher`, so the shell may never -/// display the item). `uda_tray_support_reason` explains it. -pub const UDA_TRAY_SUPPORT_LEVEL_PARTIAL: i32 = 1; -/// Support-level code: the icon is live and nothing degraded. -pub const UDA_TRAY_SUPPORT_LEVEL_FULL: i32 = 2; - -/// Every tray capability bit the C ABI documents. -/// -/// Used by the drift tests in this module and in [`crate::tests`], so the list -/// exists once. -#[cfg(test)] -pub(crate) const DOCUMENTED_TRAY_CAPABILITIES: u32 = UDA_TRAY_CAP_SYSTEM_TRAY - | UDA_TRAY_CAP_ICON - | UDA_TRAY_CAP_TOOLTIP - | UDA_TRAY_CAP_CLICK - | UDA_TRAY_CAP_DOUBLE_CLICK - | UDA_TRAY_CAP_CONTEXT_MENU - | UDA_TRAY_CAP_CHECKBOX - | UDA_TRAY_CAP_DYNAMIC_MENU; - /// The tray features the active platform backend advertises, as a bitmask. /// /// Mirrors [`crate::session::capabilities`]: constructing the manager is cheap @@ -542,6 +489,27 @@ pub(crate) fn set_icon_rgba( "`data` must not be null".to_string(), )); } + // Validate the geometry here so a malformed icon is an invalid-argument + // status (-1) rather than the "not supported" (-2) that uda-core's + // TrayIcon::set_icon would return: the caller violated the contract, the + // platform is fine. These checks mirror + // `TrayIconSource::validate` in uda-core, which re-validates before the OS + // sees any pixels, so the two copies must stay in sync; the duplication is + // deliberate (this one owns the -1 vs -2 status and the message), not an + // oversight to refactor away. + if width == 0 || height == 0 { + return Err(Failure::InvalidArgument( + "icon width and height must both be non-zero".to_string(), + )); + } + let row_bytes = width + .checked_mul(4) + .ok_or_else(|| Failure::InvalidArgument("icon width * 4 overflows".to_string()))?; + if stride < row_bytes { + return Err(Failure::InvalidArgument(format!( + "icon stride is smaller than width * 4: {stride} < {row_bytes} bytes" + ))); + } let needed = stride .checked_mul(height) .ok_or_else(|| Failure::InvalidArgument("icon stride * height overflows".to_string()))? @@ -605,7 +573,7 @@ pub(crate) fn create_menu() -> Result { pub(crate) fn menu_add_text( menu_handle: u64, label: &str, - callback: Option, + callback: UdaTrayTextCallback, user_data: *mut c_void, ) -> Result { let (menu, callbacks) = TrayRegistry::global().menu(menu_handle)?; @@ -685,7 +653,7 @@ pub(crate) fn menu_add_checkbox( menu_handle: u64, label: &str, checked: bool, - callback: Option, + callback: UdaTrayCheckboxCallback, user_data: *mut c_void, ) -> Result { let (menu, callbacks) = TrayRegistry::global().menu(menu_handle)?; @@ -819,7 +787,7 @@ mod tests { fn registry_text( menu: u64, label: &str, - callback: Option, + callback: UdaTrayTextCallback, user_data: *mut c_void, ) -> Result { menu_add_text(menu, label, callback, user_data) @@ -830,7 +798,7 @@ mod tests { menu: u64, label: &str, checked: bool, - callback: Option, + callback: UdaTrayCheckboxCallback, user_data: *mut c_void, ) -> Result { menu_add_checkbox(menu, label, checked, callback, user_data) @@ -1064,6 +1032,36 @@ mod tests { ); } + #[test] + fn malformed_icon_geometry_is_rejected_as_invalid_argument() { + let _guard = registry_guard(); + let pixels = [0u8; 16]; + // Handle 0 would also be rejected as an unknown handle with the same + // `InvalidArgument` status, so checking the status alone would pass + // even if the geometry checks never ran. Each case therefore also pins + // the geometry-specific fragment of the message, which the + // unknown-handle path cannot produce. + for (width, height, stride, len, fragment) in [ + (0, 1, 4, 16, "width and height"), // zero width + (1, 0, 4, 16, "width and height"), // zero height + (2, 1, 4, 16, "stride is smaller"), // stride < width * 4 + (1, 1, 4, 3, "shorter than"), // len < stride * height + ] { + let result = set_icon_rgba(0, width, height, stride, pixels.as_ptr(), len); + let failure = result.expect_err("malformed icon geometry must be rejected"); + assert!( + matches!(&failure, Failure::InvalidArgument(_)), + "({width}x{height}, stride {stride}, len {len}) must be invalid: {failure:?}" + ); + assert!( + failure.message().contains(fragment), + "({width}x{height}, stride {stride}, len {len}) must fail the geometry check \ + ({fragment:?}), not some other validation; got: {}", + failure.message() + ); + } + } + #[test] fn an_empty_label_is_rejected_before_the_row_exists() { let _guard = registry_guard(); diff --git a/crates/uda-ffi/src/util.rs b/crates/uda-ffi/src/util.rs index 21b96ce..56a2dc6 100644 --- a/crates/uda-ffi/src/util.rs +++ b/crates/uda-ffi/src/util.rs @@ -10,7 +10,7 @@ //! turned into owned Rust values (`&str`, `String`) by the helpers here, and //! the conversion functions never assume the buffer is well formed: they walk //! to a null terminator and bail out with -//! [`UDA_ERR_INVALID_ARGUMENT`](crate::error::UDA_ERR_INVALID_ARGUMENT) when +//! [`UDA_ERR_INVALID_ARGUMENT`](crate::abi::UDA_ERR_INVALID_ARGUMENT) when //! the bytes are not valid UTF-8. //! 3. **Errors survive the return.** Rust's error type cannot be represented in //! C, so the message is parked in a thread-local slot that @@ -20,7 +20,8 @@ use std::cell::RefCell; use std::ffi::CString; use std::os::raw::c_char; -use crate::error::{Failure, UdaStatus, UDA_ERR_PANIC}; +use crate::abi::{UDA_ERR_PANIC, UDA_OK}; +use crate::error::{Failure, UdaStatus}; thread_local! { /// Message of the most recent failure on the calling thread. @@ -156,7 +157,7 @@ where let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)); match outcome { - Ok(Ok(())) => crate::error::UDA_OK, + Ok(Ok(())) => UDA_OK, Ok(Err(failure)) => { set_last_message(&failure.message()); failure.status() @@ -201,7 +202,7 @@ fn panic_description(payload: &(dyn std::any::Any + Send)) -> String { #[cfg(test)] mod tests { use super::*; - use crate::error::{UDA_ERR_INVALID_ARGUMENT, UDA_ERR_NOT_SUPPORTED, UDA_OK}; + use crate::abi::{UDA_ERR_INVALID_ARGUMENT, UDA_ERR_NOT_SUPPORTED, UDA_OK}; use std::ffi::CString; /// Read a NUL-terminated C string the way a C caller would. diff --git a/crates/uda-ffi/src/wakelocks.rs b/crates/uda-ffi/src/wakelocks.rs index 7da9687..17579a3 100644 --- a/crates/uda-ffi/src/wakelocks.rs +++ b/crates/uda-ffi/src/wakelocks.rs @@ -51,6 +51,7 @@ use uda_core::wakelock::{WakeLockGuard, WakeLockType}; use crate::dispatch::WakeLockHandle; use crate::error::Failure; +/// cbindgen:ignore /// Lifetime, in seconds, granted to a CLI-tier lock. /// /// `systemd-inhibit --mode=block` returns as soon as its child exits, so the @@ -58,14 +59,21 @@ use crate::error::Failure; /// indefinite; the cap is documented on `uda_wakelock_acquire` (a success /// return writes no `uda_last_error_message`). The constant stays available on /// every target because the reaper's retirement log names it there too. +/// +/// Implementation detail, not C-ABI surface: the `cbindgen:ignore` above keeps +/// cbindgen from scanning (and warning about) a private constant it would +/// otherwise visit. +/// cbindgen:ignore const CLI_LOCK_SECONDS: u64 = 3600; /// Bound authorization and startup before exposing a CLI lock handle. +/// cbindgen:ignore #[cfg(target_os = "linux")] const CLI_START_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); // systemd-inhibit starts this command only after acquiring its inhibition FD. // The shell acknowledges that boundary, then becomes the bounded lock holder. +/// cbindgen:ignore #[cfg(target_os = "linux")] const CLI_HOLDER: &str = "printf R; exec sleep \"$1\""; @@ -409,7 +417,7 @@ fn register(handle: WakeLockHandle, entry: LockEntry) -> Result Result<(), Failure> { let raw = handle.raw(); diff --git a/crates/uda-ffi/tests/public_api.rs b/crates/uda-ffi/tests/public_api.rs new file mode 100644 index 0000000..5a3be51 --- /dev/null +++ b/crates/uda-ffi/tests/public_api.rs @@ -0,0 +1,9 @@ +use uda_ffi::{status_message, UdaStatus, UDA_OK}; + +#[test] +fn status_alias_remains_available_to_rust_callers() { + let status: UdaStatus = UDA_OK; + let describe: fn(UdaStatus) -> &'static str = status_message; + let _: i32 = status; + assert_eq!(describe(status), "success"); +} diff --git a/crates/uda-platform-linux/src/media.rs b/crates/uda-platform-linux/src/media.rs index 1fccfbb..55c7ef6 100644 --- a/crates/uda-platform-linux/src/media.rs +++ b/crates/uda-platform-linux/src/media.rs @@ -372,26 +372,32 @@ fn dict_get<'d>( /// Build the metadata snapshot from an MPRIS `Metadata` dictionary. /// -/// Every field is optional on the wire, and a missing one is an empty string -/// rather than an error. `duration_ms` uses [`duration_from_micros`], which -/// performs the microseconds -> milliseconds conversion and rejects unbounded -/// streams. +/// Every string field is optional on the wire: a missing key maps to `None` +/// ("not published") and a present key to `Some(value)`, even when the value +/// is an empty string, so the two cases stay distinguishable downstream. +/// `duration_ms` uses [`duration_from_micros`], which performs the +/// microseconds -> milliseconds conversion and rejects unbounded streams. /// /// [`dict_get`] is a helper rather than [`zbus::zvariant::Dict::get`] because the /// dictionary keys arrive as variants and the lookup must not fail the whole /// parse when one key is absent. pub(crate) fn metadata_from_dict(dictionary: &zbus::zvariant::Dict<'_, '_>) -> MediaMetadata { - // `dict_get` hands back an owned `Value`; the field readers deref-friendly - // signatures accept it directly, so no explicit borrow is needed. - let title = dict_get(dictionary, "xesam:title") - .map(title_from_value) - .unwrap_or_default(); - let artist = dict_get(dictionary, "xesam:artist") - .map(|value| join_artists(&artists_from_value(value))) - .unwrap_or_default(); - let album = dict_get(dictionary, "xesam:album") - .and_then(|value| value.downcast_ref::().ok()) - .unwrap_or_default(); + // `dict_get` hands back a reference into the dictionary, and the field + // readers take `&Value`, so `.map(...)` needs no explicit re-borrow. + // + // `title` / `artist` go through tolerant readers (`.map(...)`) because the + // MPRIS spec allows those keys to arrive as arrays (Chromium-family + // players have shipped `xesam:title` as one), so a present key must keep + // converting into `Some` even when the value shape varies. `album` is a + // single string per spec, so a present key with an unexpected type folds + // to `None` (`.and_then(...)`) - a wrongly-typed album is not a value + // worth coercing. This asymmetry is deliberate; keep the two paths + // distinct when touching the readers. + let title = dict_get(dictionary, "xesam:title").map(title_from_value); + let artist = + dict_get(dictionary, "xesam:artist").map(|value| join_artists(&artists_from_value(value))); + let album = + dict_get(dictionary, "xesam:album").and_then(|value| value.downcast_ref::().ok()); // The duration is a signed i64: the spec permits negative sentinels, and a // player that reports one must not be turned into a huge positive number. @@ -456,11 +462,12 @@ async fn read_metadata( return Ok(None); }; - let metadata = metadata_from_dict(&dictionary); - if metadata.is_empty() { - return Ok(None); - } - Ok(Some(metadata)) + // No all-empty check here: the outer `active_metadata` path already unwraps + // an `Ok(None)` to a default snapshot before merging in the separately-read + // position and normalising once afterwards. An inner check is therefore + // redundant; the outer merge preserves a position-only snapshot either way, + // so removing it leaves behavior unchanged. + Ok(Some(metadata_from_dict(&dictionary))) } /// Read the playback position in milliseconds. @@ -748,21 +755,33 @@ mod tests { ("mpris:length", 240_000_000i64.into()), ])); - assert_eq!(metadata.title, "Song"); - assert_eq!(metadata.artist, "A, B"); - assert_eq!(metadata.album, "Album"); + assert_eq!(metadata.title, Some("Song".to_string())); + assert_eq!(metadata.artist, Some("A, B".to_string())); + assert_eq!(metadata.album, Some("Album".to_string())); assert_eq!(metadata.duration_ms, Some(240_000)); // The position is a separate, continuously changing property. assert_eq!(metadata.position_ms, None); } #[test] - fn an_empty_dictionary_yields_empty_fields_not_an_error() { + fn an_empty_dictionary_yields_unpublished_fields_not_an_error() { let metadata = metadata_from_dict(&dictionary(Vec::new())); - assert!(metadata.title.is_empty()); - assert!(metadata.artist.is_empty()); - assert!(metadata.album.is_empty()); + // Absent keys mean "not published" (None), not an empty string. + assert_eq!(metadata.title, None); + assert_eq!(metadata.artist, None); + assert_eq!(metadata.album, None); assert_eq!(metadata.duration_ms, None); + assert!(metadata.is_empty()); + } + + #[test] + fn a_published_but_empty_title_stays_distinguishable_from_unpublished() { + // A player that publishes `xesam:title` as an empty string has said + // something different from a player that omits the key entirely; the + // parse must preserve the distinction instead of collapsing both. + let metadata = metadata_from_dict(&dictionary(vec![("xesam:title", "".into())])); + assert_eq!(metadata.title, Some(String::new())); + assert!(!metadata.is_empty()); } #[test] diff --git a/crates/uda-platform-windows/src/media.rs b/crates/uda-platform-windows/src/media.rs index 2591c62..59daef2 100644 --- a/crates/uda-platform-windows/src/media.rs +++ b/crates/uda-platform-windows/src/media.rs @@ -189,28 +189,45 @@ fn command_refused(command: MediaCommand) -> UdaError { /// /// `Ok(None)` covers both "no session is playing" and "the session published no /// usable fields", so a caller cannot distinguish them - and does not need to, -/// because neither is a failure. +/// because neither is a failure. A property read that fails after the session +/// was selected (the `TryGetMediaPropertiesAsync` request or its awaited +/// result) also reports `Ok(None)`: the session stopped answering mid-call, +/// which is a normal race rather than a backend failure. +/// +/// These read-failure branches cannot be injected from a unit test - they need +/// a live SMTC session that fails between selection and the read - so they are +/// verified by inspection only; the tests below cover the pure mapping helpers. async fn active_metadata_async() -> Result, UdaError> { let Some(session) = WindowsMediaManager::current_session().await? else { return Ok(None); }; - let properties = session - .TryGetMediaPropertiesAsync() - .map_err(|e| UdaError::DetectionFailed(format!("SMTC media properties: {e}")))? - .get() - .map_err(|e| UdaError::DetectionFailed(format!("SMTC media properties: {e}")))?; + let properties = match session.TryGetMediaPropertiesAsync() { + Ok(operation) => match operation.get() { + Ok(properties) => properties, + Err(e) => { + log::debug!( + "SMTC media properties could not be read ({e}); treating as no metadata" + ); + return Ok(None); + } + }, + Err(e) => { + log::debug!( + "SMTC media properties could not be requested ({e}); treating as no metadata" + ); + return Ok(None); + } + }; // `Artist` is a single string on Windows (MPRIS publishes a list, which is - // joined on the Linux side); no post-processing is needed here. - let title = string_from_hstring(properties.Title()); - let artist = string_from_hstring(properties.Artist()); - let album = string_from_hstring(properties.AlbumTitle()); - + // joined on the Linux side); no post-processing is needed here. An absent + // property arrives as an empty string - the wire has no separate "unset" + // value - so an empty read maps to `None` ("not published"). let mut metadata = MediaMetadata { - title, - artist, - album, + title: published_or_none(string_from_hstring(properties.Title())), + artist: published_or_none(string_from_hstring(properties.Artist())), + album: published_or_none(string_from_hstring(properties.AlbumTitle())), duration_ms: None, position_ms: None, }; @@ -236,6 +253,19 @@ fn string_from_hstring(value: windows::core::Result) -> .unwrap_or_default() } +/// Map an SMTC string property onto the core's published/unpublished model. +/// +/// SMTC has no "unset" marker: a property the session does not publish reads +/// back as an empty string, so empty is the wire's only spelling of "not +/// published" and maps to `None`. +fn published_or_none(text: String) -> Option { + if text.is_empty() { + None + } else { + Some(text) + } +} + /// Read the tick count of a timeline value, tolerating a failed read. /// /// A session that fails to publish a timeline value reports zero ticks, which @@ -247,19 +277,36 @@ fn ticks_of(timespan: windows::core::Result) -> i /// Read the playback status of the current session. /// /// With no session the status is `Unknown` rather than `Stopped`: nothing is -/// loaded, which is exactly what `Stopped` would claim to know. +/// loaded, which is exactly what `Stopped` would claim to know. A selected +/// session whose `GetPlaybackInfo()` or `PlaybackStatus()` read fails also +/// reports `Unknown` with `Ok`: the session stopped answering mid-call, which +/// is a normal race, not a backend failure. Those branches cannot be injected +/// from a unit test without a live SMTC session that fails mid-read, so they +/// are verified by inspection; the tests below cover `status_from_smtc`. async fn playback_status_async() -> Result { let Some(session) = WindowsMediaManager::current_session().await? else { return Ok(PlaybackStatus::Unknown); }; - let info = session - .GetPlaybackInfo() - .map_err(|e| UdaError::DetectionFailed(format!("SMTC playback info: {e}")))?; + // A session that stops answering between the two calls has not published a + // readable state; report "cannot tell" (`Unknown`) with a successful call + // rather than turning a normal race into a failure. Only the absence of the + // SMTC backend itself (in `session_manager`) is `NotSupported`. + let info = match session.GetPlaybackInfo() { + Ok(info) => info, + Err(e) => { + log::debug!("SMTC playback info could not be read ({e}); reporting Unknown"); + return Ok(PlaybackStatus::Unknown); + } + }; - let status = info - .PlaybackStatus() - .map_err(|e| UdaError::DetectionFailed(format!("SMTC playback status: {e}")))?; + let status = match info.PlaybackStatus() { + Ok(status) => status, + Err(e) => { + log::debug!("SMTC playback status could not be read ({e}); reporting Unknown"); + return Ok(PlaybackStatus::Unknown); + } + }; Ok(status_from_smtc(status)) } @@ -352,21 +399,23 @@ mod tests { } } - #[test] - fn a_command_with_no_session_to_address_is_an_error() { - // The asymmetry: a read has nothing to say, but a command has nothing to - // send *to*. Reporting success there would let a caller believe it paused - // something. - let outcome: Result<(), UdaError> = Err(UdaError::NotSupported( - "no media session is currently playing".to_string(), - )); + // No unit test covers the "no session to address" branch of + // `send_smtc_command`: exercising it needs a live SMTC manager, and on a + // machine with a player the call would execute the command instead of + // taking that branch. The branch itself is a direct + // `Err(UdaError::NotSupported(..))`; its contract is stated in the + // function's doc. - match outcome { - Err(UdaError::NotSupported(message)) => { - assert!(message.contains("no media session"), "message: {message}"); - } - other => panic!("expected NotSupported, got {other:?}"), - } + #[test] + fn an_empty_smtc_property_reads_as_unpublished() { + // SMTC has no "unset" marker: a property the session does not publish + // reads back as an empty string, which must become `None` (NULL on the + // C ABI) rather than an empty string. + assert_eq!(published_or_none(String::new()), None); + assert_eq!( + published_or_none("Album".to_string()), + Some("Album".to_string()) + ); } #[test] diff --git a/docs/internals/media_specs.md b/docs/internals/media_specs.md index 5fa22fa..0074bf0 100644 --- a/docs/internals/media_specs.md +++ b/docs/internals/media_specs.md @@ -70,16 +70,24 @@ org.freedesktop.DBus -> ListNames() 毫秒会让一首 3 分钟的歌唱成 50 小时。 - `xesam:title` 可能是 **数组**(Chromium 系历史上这么发过)。取首个元素即可, 否则标题整段丢失。 -- 任何键都可能缺席(直播流、无元数据的本地文件)。缺席 == 空字符串,不是错误。 +- 任何键都可能缺席(直播流、无元数据的本地文件)。缺席映射为 `None`(C-ABI + 上是 NULL),不是错误;已发布但为空的值保持空字符串,两者可区分。这一 + 可区分性**仅 Linux 成立**:Windows 章节的 SMTC 没有线上"未发布"标记, + 空读取同样折叠为 `None`(见 §3.4)。 - `mpris:length` <= 0 表示直播或未知时长,映射为 `None` 而不是 0。 ### 2.4 错误分层 `zbus` 调用失败要分开对待:`ServiceUnknown`(播放器刚好退出)与 `UnknownProperty`(该播放器没实现那个属性)都是**可预期的竞态**,降级为 -`Ok(None)` 或该字段为空;只有连 session bus 都连不上才是 +`Ok(None)` 或该字段未发布(`None`);只有连 session bus 都连不上才是 `UdaError::DetectionFailed`。 +命令路径同理:MPRIS 方法返回错误回复是播放器**显式拒绝**(单曲队列上按 +Next 就是典型场景),映射为 `UdaError::NotSupported`(`player_refused`), +C-ABI 上即 `UDA_ERR_NOT_SUPPORTED`(-2);只有等待超时才映射为 +`UdaError::CommandFailed`(-5)。 + ## 3. Windows:WinRT SMTC `GlobalSystemMediaTransportControlsSessionManager` 是 Windows 10 1703+ 的系统级 @@ -113,10 +121,10 @@ let session = manager.GetCurrentSession()?; // Option { @@ -993,10 +1000,13 @@ class MediaController { const durationMs = Number(this._uda._lib.readSlot(this._uda._types.uint64, durationSlot)); const positionMs = Number(this._uda._lib.readSlot(this._uda._types.uint64, positionSlot)); - // 库端已把"元数据全空"归一成与"无播放器"完全相同的返回值(三个 NULL + - // 时长 0),SDK 必须同样归一成 null:否则调用方拿到一个空壳对象,无法与 - // "没有播放器"区分,示例里就会打印出一堆"(未发布)"。 - if (!title && !artist && !album && durationMs === 0) { + // "无播放器"与"所有字段(含进度)都未发布"在库端都是三个 NULL + 时长/进度 + // 0;播放器把每个字段都发布成空串时,库端会保留空 C 串以便与 NULL 区分, + // 但这仅 Linux 成立;Windows 上 SMTC 无法区分,库端已折叠为 NULL。绑定层 + // 仍把"全空"归一成 null:示例只关心"有没有可展示的元数据",否则调用方拿 + // 到一个空壳对象,打印出一堆"(未发布)";只有进度(positionMs)非 0 的快照 + // 仍是播放器快照,不能因为标题等字段为空就判定为无播放器。 + if (!title && !artist && !album && durationMs === 0 && positionMs === 0) { return null; } @@ -1019,9 +1029,17 @@ class MediaController { /** * 发送一条播控指令。 * + * 失败时抛出携带状态码的 `UdaError`: + * - `ERR_INVALID_ARGUMENT`(-1):指令名无法识别,什么都没发送; + * - `ERR_NOT_SUPPORTED`(-2):没有播放器可接收,或已选中的播放器明确拒绝 + * 执行;Windows 上 SMTC 会话管理器不可用同样报此码; + * - `ERR_DETECTION_FAILED`(-3):后端整体不可达——Linux 连不上 session bus, + * Windows 的 SMTC 管理器请求本身失败; + * - `ERR_INTERNAL`(-5):已选中播放器后的传输失败,例如代理构建失败、调用 + * 超时或 WinRT 调用失败。 + * * @param {'play' | 'pause' | 'toggle' | 'next' | 'previous' | 'stop'} command - * @throws {UdaError} 指令名无法识别(-1),或没有播放器可接收、播放器拒绝 - * 执行(-2)。 + * @throws {UdaError} 见上,状态码取自 `err.status`。 */ send(command) { const code = MEDIA_COMMAND_CODES[command]; diff --git a/examples/python/uda.py b/examples/python/uda.py index 62e3e23..8e57a15 100644 --- a/examples/python/uda.py +++ b/examples/python/uda.py @@ -982,10 +982,13 @@ def __del__(self) -> None: # pragma: no cover - 仅在忘记释放时兜底 def _decode_or_empty(pointer: ctypes.c_char_p) -> str: - """把库返回的 ``char *`` 解成 Python 字符串;``NULL`` 视为空串。 + """把库返回的 ``char *`` 解成 Python 字符串;``NULL`` 与空串都得到空串。 - 媒体元数据的每个字段都是独立分配的可空指针:播放器没发布该字段(例如电台 - 流没有专辑)时是 ``NULL``,而不是空字符串。业务侧判断 ``if track.album`` + 媒体元数据的每个字段都是独立分配的可空指针,C-ABI 契约(见 + ``docs/internals/media_specs.md``)区分两种情况:播放器没发布该字段(例如 + 电台流没有专辑)时是 ``NULL``;播放器发布了一个空值则是空 C 串。该区分 + 仅在 Linux 成立——Windows SMTC 线上没有"未发布"标记,空读取由库折叠成 + ``NULL``——且本绑定把两者一并呈现为空串:业务侧判断 ``if track.album`` 即可,不必关心指针是否为空。 """ if not pointer.value: @@ -1044,6 +1047,11 @@ def __init__(self, uda: "Uda") -> None: def now_playing(self) -> MediaTrack | None: """当前播放的曲目快照;没有播放器运行时返回 ``None``。 + 每个字段按 C-ABI 的 NULL/空串契约解码:未发布字段(``NULL``)与发布为 + 空的字段都表现为空串。三个字段都为空、时长与进度都是 0 的快照与"没有 + 播放器"在绑定层无法区分,因此也归一成 ``None``;只要进度非 0,返回的 + 就是真实的播放器快照。 + 示例:: track = uda.media.now_playing @@ -1072,14 +1080,19 @@ def now_playing(self) -> MediaTrack | None: artist_text = _decode_or_empty(artist) album_text = _decode_or_empty(album) - # 库端已把"元数据全空"归一成与"无播放器"完全相同的返回值(三个 - # NULL + 时长 0),SDK 必须同样归一成 None:否则调用方拿到一个空壳 - # 对象,无法与"没有播放器"区分,示例里就会打印出一堆"(未发布)"。 + # "无播放器"与"所有字段(含进度)都未发布"在库端都是三个 NULL + + # 时长/进度 0。播放器把每个字段都发布成空串时,库端会保留空 C 串 + # 以便与 NULL 区分,但这仅 Linux 成立;Windows 上 SMTC 无法区分, + # 库端已折叠为 NULL。绑定层仍把"全空"归一成 None:示例只关心"有 + # 没有可展示的元数据",否则调用方拿到一个空壳对象,打印出一堆 + # "(未发布)";只有进度(position_ms)非 0 的快照仍是播放器快照, + # 不能因为标题等字段为空就判定为无播放器。 if ( not title_text and not artist_text and not album_text and duration.value == 0 + and position.value == 0 ): return None @@ -1116,8 +1129,13 @@ def send(self, command: str) -> None: command: :class:`MediaCommand` 常量之一。 Raises: - UdaError: 指令名无法识别(状态码 -1),或没有播放器可接收、播放器 - 拒绝执行(状态码 -2)。 + UdaError: 指令名无法识别(状态码 -1,``ERR_INVALID_ARGUMENT``); + 没有播放器可接收,或已选中的播放器明确拒绝执行(状态码 -2, + ``ERR_NOT_SUPPORTED``;Windows 上 SMTC 会话管理器不可用同样报 + 此码);后端整体不可达——Linux 连不上 session bus,或 Windows 的 + SMTC 管理器请求本身失败(状态码 -3,``ERR_DETECTION_FAILED``); + 已选中播放器后的传输失败,例如代理构建失败、调用超时或 WinRT + 调用失败(状态码 -5,``ERR_INTERNAL``)。 """ try: code = _MEDIA_COMMAND_CODES[command] diff --git a/include/uda.h b/include/uda.h index 458eee5..2fd0e19 100644 --- a/include/uda.h +++ b/include/uda.h @@ -5,399 +5,373 @@ * - Linux -> libuda_ffi.so * - Windows -> uda_ffi.dll * - * Every function returns an `int32_t` status code (`0` = success, negative = - * failure) except `uda_free_string`, which returns nothing. Human-readable - * diagnostics for the most recent failure are available from - * `uda_last_error_message()`. + * DO NOT EDIT: this file is generated by cbindgen from the Rust sources in + * crates/uda-ffi (the constants and callback types in src/abi.rs and the + * exported functions in src/lib.rs). Regenerate it with + * scripts/gen-header.sh and commit the result; hand edits are overwritten + * on the next regeneration. + * + * Every function returns an `int32_t` status code (`0` = success, negative + * = failure) except `uda_free_string`, which returns nothing, and the two + * string-returning helpers, `uda_last_error_message()` (human-readable + * diagnostics for the most recent failure on this thread) and + * `uda_status_message()` (renders any status code without a second FFI + * round-trip). * * Memory ownership * ---------------- - * - Strings RETURNED by UDA are allocated by the library and must be released - * with `uda_free_string()`, including `uda_last_error_message()`. Passing - * null to `uda_free_string()` is a no-op, so callers may free - * unconditionally. The only exception is `uda_status_message()` (a static - * string), which must NOT be freed. - * - Reading `uda_last_error_message()` consumes the stored message: the slot - * is emptied before the string is built, so a second call without an - * intervening failure returns NULL. Copy the text (or keep the returned - * allocation) if it is needed twice. + * - Strings RETURNED by UDA are allocated by the library and must be + * released with `uda_free_string()`. Passing NULL to + * `uda_free_string()` is a no-op, so callers may free unconditionally. + * The one exception is `uda_status_message()`, whose static return must + * not be freed. * - Strings PASSED IN are borrowed for the duration of the call only; the - * caller keeps ownership and must keep them alive until the call returns. + * caller keeps ownership and must keep them alive until the call + * returns. * - Wake-lock handles are plain `uint64_t` values owned by this process. * Release each one exactly once with `uda_wakelock_release()`. + * - Tray icons and menus are opaque handles into process-local tables; + * the caller owns the handle and must destroy it exactly once with + * `uda_tray_destroy()` / `uda_tray_menu_destroy()`. Callback pointers + * registered on a menu row are retained by UDA for the lifetime of + * that row, and the menu (not the callback) is the unit of + * destruction. * * Thread safety * ------------- - * All functions are free of global state apart from the wake-lock registry - * (internally synchronised) and the thread-local last-error slot, so they may - * be called concurrently from several threads. The last-error message is - * per-thread: one thread's failure never overwrites another's diagnosis. + * All functions are free of global state apart from the wake-lock registry, + * the tray handle registry (both internally synchronised) and the + * thread-local last-error slot, so they may be called concurrently from + * several threads. The last-error message is per-thread: one thread's + * failure never overwrites another's diagnosis. * * ABI stability * ------------- - * The exported symbol set is append-only. New capabilities are added as new - * functions; existing functions remain ABI-compatible (a source-level change - * such as adding or removing `const` on a pointer is called out in the - * CHANGELOG), and existing constants and status codes keep their values. + * The exported symbol set is append-only. New capabilities are added as + * new functions; existing signatures, constants and status codes do not + * change. */ #ifndef UDA_H_ #define UDA_H_ +/* Generated by cbindgen from crates/uda-ffi - DO NOT EDIT. + * Regenerate with scripts/gen-header.sh after changing the Rust sources. */ + #include #include -#ifdef __cplusplus -extern "C" { -#endif - /** - * @file uda.h - * - * C-ABI surface of the UniDesktop API. - * - * @section ownership Ownership in one paragraph - * - * String handles returned by this library are allocated by Rust and must be - * released with uda_free_string(); that includes uda_last_error_message(). The - * only exception is uda_status_message(), a static string documented on its own - * declaration. Every string passed *into* a call is borrowed for the duration - * of that call only: the caller keeps ownership and may free it immediately - * afterwards. Tray icons and menus are opaque handles into process-local - * tables; the caller owns the *handle* and must destroy it exactly once with - * uda_tray_destroy() / uda_tray_menu_destroy(). Callback pointers registered on - * a menu row are retained by UDA for the lifetime of that row, and the menu - * (not the callback) is the unit of destruction. + * The call succeeded. */ - -/* ------------------------------------------------------------------------- */ -/* Status codes */ -/* ------------------------------------------------------------------------- */ - -/** The call succeeded. */ #define UDA_OK 0 -/** Null pointer, invalid UTF-8, or an out-of-range enum code. */ + +/** + * Null pointer, invalid UTF-8, or an out-of-range enum code. + */ #define UDA_ERR_INVALID_ARGUMENT (-1) -/** The current platform or session cannot provide the feature. */ + +/** + * The current platform or session cannot provide the feature. + */ #define UDA_ERR_NOT_SUPPORTED (-2) -/** Detecting the environment or OS release failed. */ + +/** + * Detecting the environment or OS release failed. + */ #define UDA_ERR_DETECTION_FAILED (-3) -/** A filesystem or process-spawn error occurred. */ + +/** + * A filesystem or process-spawn error occurred. + */ #define UDA_ERR_IO (-4) -/** An unexpected internal failure occurred. */ + +/** + * An unexpected internal failure occurred. + */ #define UDA_ERR_INTERNAL (-5) -/** A panic was contained at the FFI boundary (should never be observed). */ -#define UDA_ERR_PANIC (-6) -/* ------------------------------------------------------------------------- */ -/* Theme codes (uda_detect_theme) */ -/* ------------------------------------------------------------------------- */ +/** + * A panic was contained at the FFI boundary (should never be observed). + */ +#define UDA_ERR_PANIC (-6) -/** The theme could not be determined. */ +/** + * The theme could not be determined. + */ #define UDA_THEME_UNKNOWN 0 -/** Dark appearance. */ + +/** + * Dark appearance. + */ #define UDA_THEME_DARK 1 -/** Light appearance. */ -#define UDA_THEME_LIGHT 2 -/* ------------------------------------------------------------------------- */ -/* Fill modes (uda_set_wallpaper) */ -/* ------------------------------------------------------------------------- */ +/** + * Light appearance. + */ +#define UDA_THEME_LIGHT 2 -/** Crop to fill while preserving the aspect ratio. */ +/** + * Crop to fill while preserving the aspect ratio. + */ #define UDA_FILL_CROP 0 -/** Fill the screen, ignoring the aspect ratio. */ + +/** + * Fill the screen, ignoring the aspect ratio. + */ #define UDA_FILL_FILL 1 -/** Fit inside the screen while preserving the aspect ratio. */ + +/** + * Fit inside the screen while preserving the aspect ratio. + */ #define UDA_FILL_FIT 2 -/** Stretch to fill the screen. */ -#define UDA_FILL_STRETCH 3 -/* ------------------------------------------------------------------------- */ -/* Wake-lock types (uda_wakelock_acquire) */ -/* ------------------------------------------------------------------------- */ +/** + * Stretch to fill the screen. + */ +#define UDA_FILL_STRETCH 3 -/** Prevent the display from sleeping. */ +/** + * Prevent the display from sleeping. + */ #define UDA_WAKELOCK_DISPLAY 0 -/** Prevent the system from idling or suspending. */ + +/** + * Prevent the system from idling or suspending. + */ #define UDA_WAKELOCK_SYSTEM 1 -/** Media playback is progressing. */ +/** + * Media playback is progressing. + */ #define UDA_MEDIA_PLAYING 0 -/** A track is loaded and halted. */ + +/** + * A track is loaded and halted. + */ #define UDA_MEDIA_PAUSED 1 -/** Nothing is loaded, or playback reached the end. */ + +/** + * Nothing is loaded, or playback reached the end. + */ #define UDA_MEDIA_STOPPED 2 + /** - * The state could not be determined. This is ALSO the code for "no media player - * is running", which is not an error: uda_media_get_status() reports it with a - * UDA_OK status. Never render it as a paused track. + * The state could not be determined. This is ALSO the code for "no media + * player is running", which is not an error: `uda_media_get_status()` reports + * it with a `UDA_OK` status. Never render it as a paused track. */ #define UDA_MEDIA_UNKNOWN 3 -/** Start or resume playback. */ +/** + * Start or resume playback. + */ #define UDA_MEDIA_CMD_PLAY 0 -/** Halt playback, keeping the position. */ + +/** + * Halt playback, keeping the position. + */ #define UDA_MEDIA_CMD_PAUSE 1 -/** Switch between playing and paused. */ + +/** + * Switch between playing and paused. + */ #define UDA_MEDIA_CMD_TOGGLE 2 -/** Advance to the next track. */ + +/** + * Advance to the next track. + */ #define UDA_MEDIA_CMD_NEXT 3 -/** Return to the previous track. */ + +/** + * Return to the previous track. + */ #define UDA_MEDIA_CMD_PREVIOUS 4 -/** Stop playback and unload the track. */ + +/** + * Stop playback and unload the track. + */ #define UDA_MEDIA_CMD_STOP 5 /** - * The calling user's session can be ended. + * A session backend exists on this platform. * - * This is set when logind can resolve the caller's own session, or a desktop - * logout manager is reachable - the two paths that can actually terminate the - * session. Power actions have their own bits and do not imply this one. + * This bit says nothing by itself: it only means at least one of the six + * actions below is reachable. Test the action's own bit before offering it. */ -#define UDA_SESSION_CAP_MANAGEMENT 0x00010000u -/** The session can be locked - the only action safe to automate. */ -#define UDA_SESSION_CAP_LOCK 0x00020000u -/** The calling user's session can be ended. */ -#define UDA_SESSION_CAP_LOGOUT 0x00040000u -/** The machine can be suspended to RAM. */ -#define UDA_SESSION_CAP_SUSPEND 0x00080000u -/** The machine can be hibernated to disk. */ -#define UDA_SESSION_CAP_HIBERNATE 0x00100000u -/** The machine can be rebooted. */ -#define UDA_SESSION_CAP_REBOOT 0x00200000u -/** The machine can be powered off. */ -#define UDA_SESSION_CAP_SHUTDOWN 0x00400000u +#define UDA_SESSION_CAP_MANAGEMENT (1u << 16) /** - * A tray backend exists on this platform. - * - * This bit says nothing by itself: test the feature bits below before relying - * on a specific tray behaviour. + * The session can be locked - the only action safe to automate. */ -#define UDA_TRAY_CAP_SYSTEM_TRAY 0x00000080u -/** The tray icon can be shown, hidden, and swapped at runtime. */ -#define UDA_TRAY_CAP_ICON 0x00000100u -/** The tray exposes hover text. */ -#define UDA_TRAY_CAP_TOOLTIP 0x00000200u +#define UDA_SESSION_CAP_LOCK (1u << 17) + /** - * The tray backend can report a single primary click. - * - * Reserved: always cleared by uda_tray_capabilities() because the C ABI has no - * click-callback registration, so activation is delivered only through menu - * rows. The flag remains defined for a future click API; do not infer click - * events from the bitmask today. + * The calling user's session can be ended. */ -#define UDA_TRAY_CAP_CLICK 0x00000400u +#define UDA_SESSION_CAP_LOGOUT (1u << 18) + /** - * The tray backend can report a native double click. - * - * Reserved for the same reason as UDA_TRAY_CAP_CLICK: never set on Linux (SNI - * has no double-click signal), and always cleared by uda_tray_capabilities() - * because the C ABI cannot register a click callback. + * The machine can be suspended to RAM. */ -#define UDA_TRAY_CAP_DOUBLE_CLICK 0x00000800u -/** The tray exposes a context menu. */ -#define UDA_TRAY_CAP_CONTEXT_MENU 0x00001000u -/** Menu rows can render a checkbox state. */ -#define UDA_TRAY_CAP_CHECKBOX 0x00002000u +#define UDA_SESSION_CAP_SUSPEND (1u << 19) + /** - * Menu rows can be added at runtime; the C ABI does not expose removal or - * relabelling (the Rust core supports both). + * The machine can be hibernated to disk. */ -#define UDA_TRAY_CAP_DYNAMIC_MENU 0x00004000u +#define UDA_SESSION_CAP_HIBERNATE (1u << 20) -/* Support levels (uda_tray_support_level). These describe what actually */ -/* happened to one icon's registration, where the UDA_TRAY_CAP_* bits above */ -/* only describe which code paths the backend has. */ +/** + * The machine can be rebooted. + */ +#define UDA_SESSION_CAP_REBOOT (1u << 21) /** - * The backend never claimed a tray at all (not reachable through handles this - * library issued). + * The machine can be powered off. */ -#define UDA_TRAY_SUPPORT_LEVEL_NONE 0 +#define UDA_SESSION_CAP_SHUTDOWN (1u << 22) + /** - * The icon is live, but its registration recorded a degradation: on Linux, no - * StatusNotifierWatcher is reachable or the watcher refuses the registration, - * so the item is exported on the bus yet the shell may never display it. - * uda_tray_support_reason() explains it. + * Capability bit: a tray backend exists at all (`SYSTEM_TRAY` in `uda-core`). */ -#define UDA_TRAY_SUPPORT_LEVEL_PARTIAL 1 -/** The icon is live and nothing about its registration degraded. */ -#define UDA_TRAY_SUPPORT_LEVEL_FULL 2 +#define UDA_TRAY_CAP_SYSTEM_TRAY (1 << 7) -/* ------------------------------------------------------------------------- */ -/* Functions */ -/* ------------------------------------------------------------------------- */ +/** + * Capability bit: the icon can be shown, hidden and swapped at runtime. + */ +#define UDA_TRAY_CAP_ICON (1 << 8) /** - * Detect the current system colour scheme. - * - * @param out_theme Receives UDA_THEME_UNKNOWN, UDA_THEME_DARK or - * UDA_THEME_LIGHT. Must not be null. - * @return UDA_OK on success, otherwise a negative status code. + * Capability bit: the tray exposes hover text. */ -int32_t uda_detect_theme(int32_t *out_theme); +#define UDA_TRAY_CAP_TOOLTIP (1 << 9) /** - * Set the desktop wallpaper. + * Capability bit: the tray reports a single primary click. * - * `path` is a plain filesystem path on every backend. A `file://` URI is - * additionally accepted on GNOME and KDE, which convert it before handing the - * value to their shell; Windows, Hyprland, Sway and X11 require a path and - * receive the string unchanged. An empty (or whitespace-only) path is rejected - * with UDA_ERR_INVALID_ARGUMENT before any backend is consulted, on every - * platform. - * - * @param path Null-terminated UTF-8 filesystem path. Must not be null. - * @param fill_mode One of the UDA_FILL_* codes. - * @return UDA_OK on success, otherwise a negative status code. + * Reserved: the C ABI has no click-callback registration, so + * `uda_tray_capabilities` always clears this bit. It stays defined for a + * future click API; do not infer click events from the bitmask today. */ -int32_t uda_set_wallpaper(const char *path, int32_t fill_mode); +#define UDA_TRAY_CAP_CLICK (1 << 10) /** - * Read the current wallpaper path. - * - * On success *out_path receives a heap C string the caller must release with - * `uda_free_string()`. When no wallpaper is configured (or the platform cannot - * report one), *out_path is set to NULL while the call still returns UDA_OK, so - * check the pointer rather than the status to detect "no wallpaper". An empty - * value is never returned as a zero-length string; it is reported as NULL too. + * Capability bit: the tray reports a native double click (never true on Linux + * SNI, where it would have to be synthesised). * - * @param out_path Receives the newly allocated string, or NULL. Must not be - * null itself. - * @return UDA_OK on success, otherwise a negative status code. + * Reserved for the same reason as [`UDA_TRAY_CAP_CLICK`]: the C ABI cannot + * register a click callback, so `uda_tray_capabilities` always clears it. */ -int32_t uda_get_wallpaper(char **out_path); +#define UDA_TRAY_CAP_DOUBLE_CLICK (1 << 11) /** - * Release a string previously returned by this library. - * - * Passing NULL is a no-op, so callers may free unconditionally. - * - * @param s A pointer obtained from `uda_get_wallpaper()`, - * `uda_media_get_metadata()`, `uda_tray_support_reason()` or - * `uda_last_error_message()`, or NULL. Freeing any other pointer is - * undefined behaviour. + * Capability bit: the tray exposes a context menu. */ -void uda_free_string(char *s); +#define UDA_TRAY_CAP_CONTEXT_MENU (1 << 12) /** - * Acquire a wake lock. - * - * A lock acquired through the CLI fallback (no native IPC available) is bounded - * to roughly one hour: past that deadline the lock is retired and its handle - * stops being live, so a host that needs a longer lock must re-acquire it. - * - * @param lock_type UDA_WAKELOCK_DISPLAY or UDA_WAKELOCK_SYSTEM. - * @param reason Null-terminated UTF-8 description used for diagnostics. - * Must not be null. - * @param out_handle Receives a non-zero handle to pass to - * `uda_wakelock_release()`. Must not be null. - * @return UDA_OK on success, otherwise a negative status code. + * Capability bit: menu rows can render a checkbox state. */ -int32_t uda_wakelock_acquire(int32_t lock_type, const char *reason, uint64_t *out_handle); +#define UDA_TRAY_CAP_CHECKBOX (1 << 13) /** - * Release a wake lock obtained from `uda_wakelock_acquire()`. - * - * Returns UDA_ERR_INVALID_ARGUMENT when the handle is not a live lock in this - * process (already released, never issued here, or a fallback lock retired - * after its bounded lifetime elapsed). + * Capability bit: menu rows can be added at runtime; the C ABI does not + * expose removal or relabelling (the Rust core supports both). + */ +#define UDA_TRAY_CAP_DYNAMIC_MENU (1 << 14) + +/** + * Support-level code: the backend never claimed a tray at all. * - * @param handle A non-zero handle from `uda_wakelock_acquire()`. - * @return UDA_OK on success, otherwise a negative status code. + * Unreachable through handles `uda_tray_create` handed out - every created + * icon publishes the backend's capability set - but the mapping stays total, + * so a fabricated or half-registered icon cannot be read as healthy. */ -int32_t uda_wakelock_release(uint64_t handle); +#define UDA_TRAY_SUPPORT_LEVEL_NONE 0 -/* ------------------------------------------------------------------------- */ -/* Notifications */ -/* ------------------------------------------------------------------------- */ +/** + * Support-level code: the icon is live, but registration recorded a + * degradation (on Linux: no `StatusNotifierWatcher`, so the shell may never + * display the item). `uda_tray_support_reason` explains it. + */ +#define UDA_TRAY_SUPPORT_LEVEL_PARTIAL 1 /** - * Send a system notification. + * Support-level code: the icon is live and nothing degraded. + */ +#define UDA_TRAY_SUPPORT_LEVEL_FULL 2 + +/** + * Callback type for a plain text menu row, or NULL for a silent row. * - * The five strings cover what a notification needs: the sending app's - * `app_name`, a one-line `title`, a multi-line `body`, an optional `icon` - * (path or URI; empty means none), and `actions` as a flat newline-separated - * list of `key\nlabel` records. Any string may be null, which is treated as the - * empty string. + * `item_id` is the row's id, as returned by `uda_tray_menu_add_text()`; + * `user_data` is the pointer registered alongside this callback. + */ +typedef void (*UdaTrayTextCallback)(uint64_t, void*); + +/** + * Callback type for a checkbox menu row, or NULL for a silent row. * - * `app_name` is not cosmetic: on Windows it is the AppUserModelID the toast is - * addressed to, and an unpackaged process has none. UDA registers it as the - * process's explicit AUMID before the first toast is shown, which is what lets - * a plain `node script.js` display a native toast. Passing null or "" selects - * the generic "UniDesktop.Notification" identity. + * `item_id` is the row's id, as returned by `uda_tray_menu_add_checkbox()`; + * `checked` is the NEW state after the toggle (`0` or `1`): the row's own + * stored value has already been updated, so this is what the shell renders + * next; `user_data` is the pointer registered alongside this callback. + */ +typedef void (*UdaTrayCheckboxCallback)(uint64_t, int32_t, void*); + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * Detect the current system colour scheme. * - * The remaining FreeDesktop fields keep their defaults: `replaces_id` is 0 (a - * new notification), the expiry is the server default, and the urgency is - * normal. Callers needing those must use the Rust API. + * Writes `UDA_THEME_UNKNOWN`, `UDA_THEME_DARK` or `UDA_THEME_LIGHT` to + * `*out_theme`. On failure a negative status code is returned and + * `*out_theme` is left untouched. * - * A trailing `key` without its `label` is dropped rather than rendered as a - * blank button. + * # Safety * - * On Windows, toast *buttons* still require a packaged (MSIX) identity, so - * `actions` is accepted for parity but not surfaced; the toast itself displays - * normally. Use `WindowsNotificationManager::availability()` to probe further. - * - * @param app_name Sending application name; the Windows toast identity. - * Null or "" selects "UniDesktop.Notification". - * @param title One-line summary. Null is treated as "". - * @param body Multi-line detail. Null is treated as "". - * @param icon Path or URI for the notification image, or null. - * @param actions Flat "key\nlabel" records separated by '\n', or null. - * @param out_id Receives the id the notification server assigned. Must not - * be null. Left untouched on failure. - * @return UDA_OK on success, otherwise a negative status code. + * `out_theme` must point to a writable, non-null `int32_t` location. */ -int32_t uda_notify(const char *app_name, - const char *title, - const char *body, - const char *icon, - const char *actions, - uint32_t *out_id); +int32_t uda_detect_theme(int32_t *out_theme); /** - * Read the system accent colour as four channels. + * Set the desktop wallpaper. * - * Writes R, G, B, A (each 0..=255) to the four bytes at `out_rgba`. A platform - * that exposes no accent colour - most Linux desktops - leaves the bytes - * untouched and still returns UDA_OK, so a zeroed slot means "no accent", - * not failure. + * `path` accepts a plain filesystem path on every backend. A `file://` URI is + * additionally accepted on GNOME and KDE, which convert it before handing the + * value to their shell; other backends (Windows, Hyprland, Sway, X11) require + * a path and receive the string unchanged. An empty path is rejected as an + * invalid argument rather than being sent to the backend. + * + * On failure a negative status code is returned and no wallpaper is changed. + * + * # Safety * - * @param out_rgba Pointer to four writable `uint8_t` values. Must not be null. - * @return UDA_OK on success, otherwise a negative status code. + * `path` must be a valid, readable, null-terminated UTF-8 string. */ -int32_t uda_get_accent_color(uint8_t *out_rgba); +int32_t uda_set_wallpaper(const char *path, int32_t fill_mode); /** - * Read the now-playing metadata of the active media player. - * - * On Linux the backend scans the session bus for an `org.mpris.MediaPlayer2.*` - * service; on Windows it asks the Global System Media Transport Controls session - * manager. Both answer `Ok(None)` when no player is running, which this function - * turns into: `*out_title`, `*out_artist` and `*out_album` set to NULL, and - * `*out_duration_ms` / `*out_position_ms` set to 0 - with a UDA_OK status. A - * now-playing card therefore renders as empty rather than as a failure. - * - * The three strings are allocated by the library and must each be released with - * uda_free_string(). Freeing NULL is a no-op, so callers may free - * unconditionally. A field the player does not publish (a radio stream with no - * album, say) is NULL rather than an empty string - as is a field the player - * publishes as the empty string, so a binding's `if (ptr)` check always sees - * "no value" the same way. - * - * @param out_title Receives the track title, or NULL. Must not be null. - * @param out_artist Receives the artist(s), already joined with ", " when - * the player publishes several, or NULL. Must not be - * null. - * @param out_album Receives the album name, or NULL. Must not be null. - * @param out_duration_ms Receives the track length in milliseconds, or 0 when - * unknown (a live stream). Must not be null. - * @param out_position_ms Optional; pass NULL to skip. Receives the playback - * position in milliseconds, or 0 when the backend - * cannot report it. - * @return UDA_OK on success, otherwise a negative status code. + * Read the metadata of the active media player. + * + * The three strings are allocated by Rust and must be released with + * [`uda_free_string`]. An unpublished field is written as a null pointer, or + * zero for a duration, so each pointer must be checked before it is read. A + * field published as an empty string stays an empty C string where the backend + * can tell the two apart (Linux); on Windows an empty read also surfaces as + * null, because SMTC has no "unset" marker on the wire, so a host must treat + * null as "skip this field" everywhere. With no player running every + * out-parameter is set to null/zero and [`UDA_OK`] is still returned. + * + * `out_position_ms` is optional: pass null to skip it. + * + * # Safety + * + * `out_title`, `out_artist` and `out_album` must each point at a writable + * `char *` location; `out_duration_ms` must point at a writable `uint64_t`; + * `out_position_ms` must be null or point at a writable `uint64_t`. */ int32_t uda_media_get_metadata(char **out_title, char **out_artist, @@ -408,95 +382,101 @@ int32_t uda_media_get_metadata(char **out_title, /** * Read the playback status of the active media player. * - * Writes UDA_MEDIA_PLAYING, UDA_MEDIA_PAUSED, UDA_MEDIA_STOPPED or - * UDA_MEDIA_UNKNOWN to `*out_status`. UDA_MEDIA_UNKNOWN covers both "no player is - * running" and "the state could not be determined", and is reported with UDA_OK: - * it is an answer, not a failure. A negative status code means the platform has - * no media backend at all. + * Writes `UDA_MEDIA_PLAYING`, `UDA_MEDIA_PAUSED`, `UDA_MEDIA_STOPPED` or + * `UDA_MEDIA_UNKNOWN` to `*out_status`. `UDA_MEDIA_UNKNOWN` covers both "no + * player is running" and "the state could not be determined", and is + * reported with [`UDA_OK`]: it is an answer, not a failure. A negative status + * code means the backend itself could not be reached: on Linux, connecting to + * the session bus or building the player proxy fails with + * `UDA_ERR_DETECTION_FAILED`; on Windows, acquiring the SMTC session manager + * fails with `UDA_ERR_NOT_SUPPORTED` or `UDA_ERR_DETECTION_FAILED`. A player + * session that *is* selected but whose state cannot be read is not a + * failure: that reports [`UDA_OK`] with `UDA_MEDIA_UNKNOWN`. On any negative + * status `*out_status` is left untouched. + * + * # Safety * - * @param out_status Receives one of the UDA_MEDIA_* status codes. Must not be - * null. - * @return UDA_OK on success, otherwise a negative status code. + * `out_status` must point to a writable, non-null `int32_t` location. */ int32_t uda_media_get_status(int32_t *out_status); /** * Send a transport command to the active media player. * - * `command` is one of UDA_MEDIA_CMD_PLAY, UDA_MEDIA_CMD_PAUSE, - * UDA_MEDIA_CMD_TOGGLE, UDA_MEDIA_CMD_NEXT, UDA_MEDIA_CMD_PREVIOUS or - * UDA_MEDIA_CMD_STOP. An unrecognised code returns UDA_ERR_INVALID_ARGUMENT and - * nothing is sent. + * `command` is one of [`UDA_MEDIA_CMD_PLAY`], [`UDA_MEDIA_CMD_PAUSE`], + * [`UDA_MEDIA_CMD_TOGGLE`], [`UDA_MEDIA_CMD_NEXT`], + * [`UDA_MEDIA_CMD_PREVIOUS`] or [`UDA_MEDIA_CMD_STOP`]. An unknown code returns + * `UDA_ERR_INVALID_ARGUMENT` and nothing is sent. * - * A player that refuses the command (an app that disables "next track") and a - * machine with no player running both report UDA_ERR_NOT_SUPPORTED, so a caller - * can tell "not delivered" from "delivered" without inspecting the player. + * `UDA_ERR_NOT_SUPPORTED` is returned + * when the player refuses the command and when no player is running. * - * @param command One of the UDA_MEDIA_CMD_* codes. - * @return UDA_OK on success, otherwise a negative status code. + * # Safety + * + * This function takes no pointers; there is nothing to validate. */ int32_t uda_media_send_command(int32_t command); /** * Report which session and power actions this platform can perform. * - * Writes a bitmask made of the UDA_SESSION_CAP_* flags to `*out_capabilities`; - * 0 means "no receiver for any session action is reachable on this target". - * - * The query is side-effect-free - it never touches the machine's power state. - * On Linux the first call runs a one-shot service probe: every D-Bus await is - * bounded, and the session lookup starts after the presence check, so the - * worst case is about 35 seconds before the answer is cached; later calls are - * immediate. A host therefore calls it once, ideally off the UI thread, before - * drawing a menu - and *must* call it before drawing one that could shut the - * machine down. + * Writes a bitmask made of the `UDA_SESSION_CAP_*` constants to + * `*out_capabilities`; `0` means "no receiver for any session action is + * reachable on this target". The query is side-effect-free - it never touches + * the machine's power state. On Linux the first call runs a one-shot service + * probe: every D-Bus await is bounded, and the session lookup starts after the + * presence check, so the worst case is about 35 seconds before the answer is + * cached; later calls are immediate. A UI therefore calls it once, ideally off + * the main thread, before drawing a menu - and must call it before drawing one + * that could shut the machine down. * * A set bit means a receiver for the action was reachable when the - * capabilities were queried; the attempt can still fail (hibernation switched - * off, polkit refusal) and then fails with UDA_ERR_NOT_SUPPORTED. On Linux - * LOCK needs the ScreenSaver service or a resolvable logind `auto` session - * (the caller's session, with the user's display session as the fallback - * logind itself applies), while LOGOUT and SESSION_MANAGEMENT need the - * caller's *own* logind session - resolved with GetSession(""), which never - * falls back to a display session - or a GNOME/KDE/XFCE desktop logout - * manager whose bus name is owned or activatable. A daemon that runs - * sessionless (or can only see other users' sessions, as on a systemd-enabled - * WSL2 host) therefore answers with the power bits, plus LOCK when `auto` - * resolves. Discovery never activates a desktop manager; activation or policy - * can still refuse an attempted action. Windows reboot and shutdown can - * likewise fail at attempt time when the caller lacks the SeShutdownPrivilege. - * - * @param out_capabilities Receives the bitmask. Must not be null. - * @return UDA_OK on success, otherwise a negative status code. + * capabilities were queried; the attempt can still fail (hibernation + * switched off, polkit refusal) and then fails with `UDA_ERR_NOT_SUPPORTED`. + * On Linux `LOCK` needs the ScreenSaver service or a resolvable logind + * `auto` session (the caller's session, with the user's display session as + * the fallback logind itself applies), while `LOGOUT` and + * `SESSION_MANAGEMENT` need the caller's *own* logind session - resolved + * with `GetSession("")`, which never falls back to a display session - or a + * GNOME/KDE/XFCE desktop logout manager whose bus name is owned or + * activatable. A daemon that runs sessionless (or can only see other users' + * sessions, as on a systemd-enabled WSL2 host) therefore answers with the + * power bits, plus `LOCK` when `auto` resolves. Discovery never activates a + * desktop manager; activation or policy can still refuse an attempted + * action. Windows reboot and shutdown can likewise fail at attempt time + * when the caller lacks the SeShutdownPrivilege. + * + * # Safety + * + * `out_capabilities` must point at a writable `uint32_t` location. */ int32_t uda_session_capabilities(uint32_t *out_capabilities); /** - * Lock the session. - * - * Linux: `org.freedesktop.ScreenSaver.Lock()` on the session bus, falling back to - * `loginctl lock-session`. Windows: `LockWorkStation()`. + * Lock the session, leaving every running program alone. * - * This is the only session action that is safe to automate: it is reversible - * (the user unlocks with their password) and it destroys nothing. The other five - * `uda_session_*` actions below must be gated behind an explicit user + * This is the **only** action safe to automate: it is reversible and destroys + * nothing. The other five exports must be gated behind an explicit user * confirmation. * - * @return UDA_OK on success, otherwise a negative status code. + * Returns `UDA_ERR_NOT_SUPPORTED` when + * the platform advertises no lock capability at all. + * + * # Safety + * + * This function takes no pointers; there is nothing to validate. */ int32_t uda_session_lock(void); /** * End the calling user's session. * - * Linux: `org.freedesktop.login1.Manager.TerminateSession("")` on the system - * bus, falling back to the desktop's own session manager (GNOME, KDE, XFCE). - * Windows: `ExitWindowsEx(EWX_LOGOFF, 0)`. + * **This action logs the user out.** Unsaved work is lost unless the desktop + * refuses to comply. Never call it without an explicit confirmation. * - * WARNING: this logs the user out. Unsaved work in applications that do not - * refuse is lost. Never call it without an explicit user confirmation. + * # Safety * - * @return UDA_OK on success, otherwise a negative status code. + * This function takes no pointers; there is nothing to validate. */ int32_t uda_session_logout(void); @@ -506,186 +486,309 @@ int32_t uda_session_logout(void); * Linux: `org.freedesktop.login1.Manager.Suspend(false)`. Windows: * `SetSuspendState(false, ...)`. * - * WARNING: this changes the machine's power state. Never call it without an + * **This action changes the machine's power state.** Never call it without an * explicit user confirmation. * - * @return UDA_OK on success, otherwise a negative status code. + * # Safety + * + * This function takes no pointers; there is nothing to validate. */ int32_t uda_session_suspend(void); /** * Hibernate the machine to disk. * - * Linux: `org.freedesktop.login1.Manager.Hibernate(false)`. Windows: - * `SetSuspendState(true, ...)`, which the platform rejects with - * ERROR_FILE_NOT_FOUND when hibernation is disabled - reported as - * UDA_ERR_NOT_SUPPORTED. + * **This action changes the machine's power state.** Unsaved work is lost. + * Never call it without an explicit user confirmation. * - * WARNING: this changes the machine's power state. Never call it without an - * explicit user confirmation. + * # Safety * - * @return UDA_OK on success, otherwise a negative status code. + * This function takes no pointers; there is nothing to validate. */ int32_t uda_session_hibernate(void); /** * Restart the machine. * - * Linux: `org.freedesktop.login1.Manager.Reboot(false)`. Windows: - * `ExitWindowsEx(EWX_REBOOT | EWX_FORCEIFHUNG, 0)` after enabling - * SeShutdownPrivilege, which needs an elevated process or an administrator - * account; without it the call fails with UDA_ERR_NOT_SUPPORTED rather than - * half-rebooting. + * On Windows this needs an elevated process or a local administrator account + * for `SeShutdownPrivilege`; without it the call fails with + * `UDA_ERR_NOT_SUPPORTED`. * - * WARNING: this restarts the machine and unsaved work is lost. Never call it + * **This action restarts the machine.** Unsaved work is lost. Never call it * without an explicit user confirmation. * - * @return UDA_OK on success, otherwise a negative status code. + * # Safety + * + * This function takes no pointers; there is nothing to validate. */ int32_t uda_session_reboot(void); /** * Power the machine off. * - * Linux: `org.freedesktop.login1.Manager.PowerOff(false)`. Windows: - * `ExitWindowsEx(EWX_POWEROFF | EWX_FORCEIFHUNG, 0)` after enabling - * SeShutdownPrivilege, with the same elevation requirement as - * uda_session_reboot(). + * Same elevation requirement as [`uda_session_reboot`]. * - * WARNING: this shuts the machine down and unsaved work is lost. Never call it + * **This action shuts the machine down.** Unsaved work is lost. Never call it * without an explicit user confirmation. * - * @return UDA_OK on success, otherwise a negative status code. + * # Safety + * + * This function takes no pointers; there is nothing to validate. */ int32_t uda_session_shutdown(void); /** - * Return the message describing the most recent failure on the calling thread. + * Read the current wallpaper path. + * + * On success `*out_path` receives a heap C string the caller must release with + * [`uda_free_string`]. When no wallpaper is configured (or the platform cannot + * report one), `*out_path` is set to null and the call still returns + * [`UDA_OK`] - check the pointer, not the status, to detect "no wallpaper". An + * empty value is never handed back as a zero-length string; it is reported as + * null too. + * + * # Safety + * + * `out_path` must point to a writable, non-null pointer location. + */ +int32_t uda_get_wallpaper(char **out_path); + +/** + * Release a string previously returned by this library. + * + * # Safety + * + * `s` must be null or a pointer obtained from an export that transfers string + * ownership to the caller: [`uda_get_wallpaper`], [`uda_media_get_metadata`], + * [`uda_tray_support_reason`] or [`uda_last_error_message`]. Freeing any other + * pointer is undefined behaviour. Passing null is a no-op, so callers may free + * unconditionally. + */ +void uda_free_string(char *s); + +/** + * Acquire a wake lock. + * + * `lock_type` is `UDA_WAKELOCK_DISPLAY` or `UDA_WAKELOCK_SYSTEM`; `reason` + * is a null-terminated UTF-8 description used for diagnostics. On success + * `*out_handle` receives a non-zero handle to pass to + * `uda_wakelock_release()`; on failure it is left untouched. + * + * On Linux, when the native IPC tiers are unavailable, the fallback holds + * the lock by running `systemd-inhibit` for at most 3600 seconds. That + * fallback lock expires silently at the cap and must be re-acquired; the + * native tiers are not capped. A successful acquire records no error message + * of its own, but it does not clear an unread message left by an earlier + * failure on the same thread; read `uda_last_error_message()` only after a + * non-`UDA_OK` status. + * + * A lock acquired through the CLI fallback (no native IPC available) is + * bounded to roughly one hour: past that deadline the lock is retired and its + * handle stops being live, so a host that needs a longer lock must re-acquire + * it. + * + * # Safety + * + * `out_handle` must point to a writable, non-null `uint64_t` location and + * `reason` must be a readable, null-terminated UTF-8 string. + */ +int32_t uda_wakelock_acquire(int32_t lock_type, const char *reason, uint64_t *out_handle); + +/** + * Release a wake lock previously obtained from `uda_wakelock_acquire()`. + * + * Returns `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live lock in + * this process (already released, never issued here, or a fallback lock + * retired after its bounded lifetime elapsed). + */ +int32_t uda_wakelock_release(uint64_t handle); + +/** + * Send a system notification. + * + * The five strings cover what a notification needs: the sending app's + * `app_name`, a one-line `title`, a multi-line `body`, an optional `icon` + * (path or URI; empty means none), and `actions` as a flat newline-separated + * list of `key\nlabel` records. Any string may be NULL, which is treated as + * the empty string. + * + * `app_name` is not cosmetic: on Windows it is the AppUserModelID the toast + * is addressed to, and an unpackaged process has none. UDA registers it as + * the process's explicit AUMID before the first toast is shown, which is + * what lets a plain `node script.js` display a native toast. Passing NULL + * or "" selects the generic "UniDesktop.Notification" identity. + * + * On Windows, toast *buttons* still require a packaged (MSIX) identity, so + * `actions` is accepted for parity but not surfaced; the toast itself + * displays normally. Rust callers can probe further with + * `WindowsNotificationManager::availability()`; the C-ABI surface has no + * notification-availability probe. + * + * A trailing `key` without its `label` is dropped rather than rendered as a + * blank button. The remaining FreeDesktop fields keep their defaults: + * `replaces_id` is 0 (a new notification), the expiry is the server + * default, and the urgency is normal. Callers needing those must use the + * Rust API. + * + * On success `*out_id` receives the id the notification server assigned; it + * is left untouched on failure. + * + * # Safety + * + * `out_id` must point to a writable, non-null `uint32_t` location. The five + * strings must each be NULL or readable, null-terminated UTF-8. + */ +int32_t uda_notify(const char *app_name, + const char *title, + const char *body, + const char *icon, + const char *actions, + uint32_t *out_id); + +/** + * Read the system accent colour as four channels. * - * The returned string is heap-allocated by this call and its ownership moves to - * the caller: release it with `uda_free_string()` (freeing NULL is a no-op) and - * it stays valid until then, no matter how many other UDA calls run in between. - * Returns NULL when no failure has been recorded on this thread yet. + * Writes R, G, B, A (each in the 0-255 range) to the four bytes at + * `out_rgba`. A platform that exposes no accent colour - most Linux + * desktops - leaves the bytes untouched and still returns `UDA_OK`, so a + * zeroed slot means "no accent", not failure. + * + * # Safety + * + * `out_rgba` must point to four writable `uint8_t` values. + */ +int32_t uda_get_accent_color(uint8_t *out_rgba); + +/** + * Return the message describing the most recent failure on this thread. * - * Reading consumes the message: the slot is emptied before the string is built, - * so an immediate second call returns NULL. A host that needs the text twice - * must copy it or keep the returned allocation alive. + * The returned string is heap-allocated by this call and its ownership moves + * to the caller: release it with [`uda_free_string`] and it stays valid until + * then, no matter how many other UDA calls run in between. Returns null when + * no failure has been recorded on this thread yet. * - * @return A newly allocated, null-terminated C string owned by the caller, or - * NULL. + * **Reading consumes the message.** The slot is emptied before the string is + * built, so an immediate second call returns null; a binding that needs the + * text twice must copy it or keep the returned allocation alive. */ char *uda_last_error_message(void); /** * Describe a status code with a static string. * - * The returned pointer is valid for the lifetime of the library and must not be - * freed. Useful for rendering a failure without a second FFI round-trip. - * - * @param status A status code returned by any UDA function. - * @return A static, null-terminated description. + * The returned pointer is valid for the lifetime of the library and must + * not be freed. Useful for rendering a failure without a second FFI + * round-trip. */ const char *uda_status_message(int32_t status); -/* ------------------------------------------------------------------------- */ -/* System tray */ -/* ------------------------------------------------------------------------- */ +/** + * Report which tray features the active platform backend advertises. + * + * Writes a bitmask made of the `UDA_TRAY_CAP_*` constants to + * `*out_capabilities`; `0` means "no tray backend exists on this target", and + * a feature the backend cannot deliver has its bit cleared. The query is + * side-effect-free - it never registers anything with the shell - so a host + * may call it freely to decide whether to build tray UI at all, and what to + * degrade gracefully. + * + * `UDA_TRAY_CAP_CLICK` and `UDA_TRAY_CAP_DOUBLE_CLICK` are always cleared: + * the C ABI has no click-callback registration, so activation is delivered + * only through menu rows. The constants stay defined for a future click API; + * a host must not infer click events from this bitmask today. + * + * # Safety + * + * `out_capabilities` must point at a writable `uint32_t` location. + */ +int32_t uda_tray_capabilities(uint32_t *out_capabilities); -/* - * Tray icons and menus are process-local resources identified by opaque - * uint64_t handles. They are NOT references, NOT pointers, and are not valid in - * another process: each handle indexes a table owned by the shared library. - * - * HANDLE LIFETIME - * - * - A handle is single-use. Destroying it removes the table entry, so a - * successful destroy followed by another call with the same value is - * reported as UDA_ERR_INVALID_ARGUMENT rather than acting on a stale - * resource. - * - Handle 0 is never a live resource. A zeroed out-parameter therefore - * unambiguously means "the call failed". - * - A menu handle stays valid after uda_tray_set_menu(): the icon holds its - * own reference, so the menu keeps working whether or not the handle is - * destroyed later. Destroying the menu handle (uda_tray_menu_destroy()) - * detaches the menu from every icon still showing it and closes its - * callback gate, so even a row snapshot a backend already cloned stays - * silent; a destroy that lands while one of the menu's callbacks is still - * running reports UDA_ERR_INTERNAL and leaves the menu intact - free the - * host trampolines only after the destroy reports success. The icons - * themselves stay alive. - * - * CALLBACK THREADING MODEL (read before writing a handler) - * - * Every menu callback is invoked on the tray worker thread that the platform - * backend owns. It is NOT the thread that called uda_tray_menu_add_text() and - * NOT your UI thread. The callback therefore must: - * - * - return as soon as possible (a slow handler stalls every later menu - * interaction); - * - not block, sleep, or wait on a lock the main thread may hold; - * - not touch GUI toolkit state directly - post an event into the host's own - * loop instead; - * - be prepared to fire after the row was removed, if the shell was already - * mid-dispatch. - * - * `user_data` is handed back to the callback verbatim. UDA never dereferences - * it; keeping it alive is the host's responsibility. - * - * The callback may be NULL, which yields a silent row that still renders. A - * NULL-callback text row has no toggle state; a NULL-callback checkbox keeps - * its initial state and never toggles. There is no API to read a row's state. - * - * DEGRADED REGISTRATIONS - * - * A successful uda_tray_create() means the item is registered with the - * platform's tray service, not that the user will ever see it. On Linux the - * shell learns about tray items from a StatusNotifierWatcher; when the session - * has none, or the watcher refuses the registration, the icon is still exported - * but may stay invisible. Such an icon reports - * UDA_TRAY_SUPPORT_LEVEL_PARTIAL from uda_tray_support_level() with a - * human-readable explanation from uda_tray_support_reason(). Windows has no - * watcher step and always reports FULL for a live icon. +/** + * Report how completely this icon's tray registration succeeded. + * + * Writes one of the `UDA_TRAY_SUPPORT_LEVEL_*` codes to `*out_level`: + * `UDA_TRAY_SUPPORT_LEVEL_FULL` when nothing degraded, + * `UDA_TRAY_SUPPORT_LEVEL_PARTIAL` when the icon is live but its registration + * recorded a degradation - on Linux, no `StatusNotifierWatcher` is reachable + * or the watcher refuses the registration, so the item is exported yet the + * shell may never display it - and `UDA_TRAY_SUPPORT_LEVEL_NONE` only when the + * backend never claimed a tray at all (not reachable through handles this + * library issued). + * + * The answer is per icon, not per platform: `uda_tray_capabilities()` reports + * which code paths exist, this reports what actually happened to *this* icon, + * and `uda_tray_support_reason()` explains a `PARTIAL` answer. + * + * On Windows the answer is always `UDA_TRAY_SUPPORT_LEVEL_FULL` for a live + * icon: the Win32 worker has no watcher step, so there is no degradation path. + * + * # Safety + * + * `out_level` must point at a writable `int32_t` location. */ +int32_t uda_tray_support_level(uint64_t handle, int32_t *out_level); + +/** + * Explain why a tray icon's support level is partial. + * + * On success `*out_reason` receives a heap C string the caller must release + * with [`uda_free_string`], or NULL when the icon is not degraded - check the + * pointer, not the status. A degraded icon (see `uda_tray_support_level`) + * always carries a non-empty reason naming what is missing or refused, e.g. a + * session with no `StatusNotifierWatcher` or a watcher that rejects the item; + * a fully supported icon reports NULL. + * + * # Safety + * + * `out_reason` must point at a writable pointer location. + */ +int32_t uda_tray_support_reason(uint64_t handle, char **out_reason); /** * Create a tray icon. * - * @param name Application name used for registration (D-Bus bus name on - * Linux, window class on Windows). An empty string selects - * this library's default name. Must be null-terminated - * UTF-8, or NULL for the default. - * @param tooltip Hover text; may be NULL or empty. Windows applies the - * 127-character clamp at registration and then fits the - * result into the 127 UTF-16 units of szTip (a non-BMP - * character uses two); Linux SNI forwards the create-time - * text as-is. uda_tray_set_tooltip() clamps to 127 - * characters on both platforms (the call still succeeds). - * @param out_handle Receives a non-zero handle on success. Must not be null. - * Left untouched on failure. - * @return UDA_OK on success, otherwise a negative status code. - * - * @note The icon has no image until uda_tray_set_icon_path() or - * uda_tray_set_icon_rgba() supplies one, so it can be prepared and only - * made visible once built. + * `name` is the application name used for registration (the D-Bus bus name on + * Linux, the window class on Windows); a null `name` selects the library + * default. `tooltip` may be null or empty. Windows applies the 127-`char` + * clamp at registration and then fits the result into szTip's 127 UTF-16 + * units (a non-BMP character uses two); Linux SNI forwards the create-time + * text as-is. `uda_tray_set_tooltip` clamps to 127 `char`s on both platforms, + * and registration still succeeds either way. + * + * On success `*out_handle` receives a non-zero handle for every other + * `uda_tray_*` call. On failure it is left untouched. The icon has no image + * until `uda_tray_set_icon_path()` or `uda_tray_set_icon_rgba()` supplies + * one, so it can be prepared and only made visible once built. + * + * # Safety + * + * `out_handle` must point to a writable, non-null `uint64_t` slot. `name` + * and `tooltip` must be NULL or readable, null-terminated UTF-8 strings. */ int32_t uda_tray_create(const char *name, const char *tooltip, uint64_t *out_handle); /** * Replace a tray icon's tooltip. * - * @param handle A handle from uda_tray_create(). - * @param tooltip Null-terminated UTF-8 text, or NULL to clear it. - * @return UDA_OK on success, otherwise a negative status code. + * `tooltip` is null-terminated UTF-8 text, or NULL to clear it. + * + * # Safety + * + * `tooltip` must be a readable, null-terminated UTF-8 string, or NULL for + * the empty string. */ int32_t uda_tray_set_tooltip(uint64_t handle, const char *tooltip); /** * Replace a tray icon's image from a file or icon-theme name. * - * @param handle A handle from uda_tray_create(). - * @param path Null-terminated UTF-8 path. Linux also accepts a freedesktop - * icon-theme name here; Windows requires a file path. - * @return UDA_OK on success, otherwise a negative status code. + * `path` is a null-terminated UTF-8 path. Linux also accepts a freedesktop + * icon-theme name here; Windows requires a file path (`.ico`, `.cur`, + * `.bmp`). + * + * # Safety + * + * `path` must be a readable, null-terminated UTF-8 string. */ int32_t uda_tray_set_icon_path(uint64_t handle, const char *path); @@ -693,16 +796,14 @@ int32_t uda_tray_set_icon_path(uint64_t handle, const char *path); * Replace a tray icon's image from raw pixels. * * The buffer is borrowed: only `stride * height` bytes are copied and the - * caller keeps ownership of `data`. Pixels are top-down RGBA, four bytes each. - * A buffer shorter than `stride * height` is rejected before any pixel is read. + * caller keeps ownership of `data`. Pixels are top-down RGBA, four bytes + * each. A zero `width` or `height`, a `stride` smaller than `width * 4`, or + * a `len` smaller than `stride * height` is rejected with + * `UDA_ERR_INVALID_ARGUMENT` before any pixel is read. + * + * # Safety * - * @param handle A handle from uda_tray_create(). - * @param width Pixel width, non-zero. - * @param height Pixel height, non-zero. - * @param stride Bytes per row; must be at least `width * 4`. - * @param data Pointer to `len` readable pixel bytes. Must not be NULL. - * @param len Readable byte count at `data`. - * @return UDA_OK on success, otherwise a negative status code. + * `data` must not be null and must point to `len` readable bytes. */ int32_t uda_tray_set_icon_rgba(uint64_t handle, uint32_t width, @@ -714,66 +815,52 @@ int32_t uda_tray_set_icon_rgba(uint64_t handle, /** * Show or hide the icon without unregistering it. * - * @param handle A handle from uda_tray_create(). - * @param visible 0 hides, any other value shows. - * @return UDA_OK on success, otherwise a negative status code. + * `visible` is a C boolean: 0 hides, any other value shows. */ int32_t uda_tray_set_visible(uint64_t handle, int32_t visible); /** * Destroy a tray icon and unregister it from the shell. * - * Terminal: the handle cannot be reused afterwards. Menus previously attached - * keep their own handles and stay valid. - * - * @param handle A handle from uda_tray_create(). - * @return UDA_OK on success, UDA_ERR_INVALID_ARGUMENT when the handle is not a - * live tray icon in this process. + * Terminal: the handle cannot be reused afterwards. Menus previously + * attached keep their own handles and stay valid. Returns + * `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live tray icon in + * this process. */ int32_t uda_tray_destroy(uint64_t handle); /** * Create an empty context menu. * - * @param out_menu_handle Receives a non-zero handle on success. Must not be - * null. Left untouched on failure. - * @return UDA_OK on success, otherwise a negative status code. - */ -int32_t uda_tray_menu_create(uint64_t *out_menu_handle); - -/** - * Callback type for a plain text menu row. + * On success `*out_menu_handle` receives a non-zero handle for the + * `uda_tray_menu_add_*` functions and `uda_tray_set_menu()`. On failure it + * is left untouched. * - * @param item_id The row's id, as returned by uda_tray_menu_add_text(). - * @param user_data The pointer registered alongside this callback. - */ -typedef void (*UdaTrayTextCallback)(uint64_t item_id, void *user_data); - -/** - * Callback type for a checkbox menu row. + * # Safety * - * @param item_id The row's id, as returned by uda_tray_menu_add_checkbox(). - * @param checked The NEW state after the toggle: 0 or 1. The row's own stored - * value has already been updated, so this is what the shell - * renders next. - * @param user_data The pointer registered alongside this callback. + * `out_menu_handle` must point to a writable, non-null `uint64_t` slot. */ -typedef void (*UdaTrayCheckboxCallback)(uint64_t item_id, int32_t checked, void *user_data); +int32_t uda_tray_menu_create(uint64_t *out_menu_handle); /** * Append a plain text row to a menu. * - * @param menu_handle A handle from uda_tray_menu_create(). - * @param label Row text; a blank label is rejected with - * UDA_ERR_INVALID_ARGUMENT because it would render - * invisibly. - * @param callback Invoked on the tray worker thread when the row is - * activated, or NULL for a silent row. - * @param user_data Handed back to `callback` untouched. - * @param out_item_id Receives the row's stable, non-zero id on success. The - * callback receives the same value. Must not be null. - * @return UDA_OK on success; UDA_ERR_INVALID_ARGUMENT for a blank label or a - * handle that is not a live menu; otherwise a negative status code. + * `callback` is invoked on the **tray worker thread** when the row is + * activated. Passing `None` (null) is legal: the row still renders, but + * activating it does nothing. A text row has no toggle state, and there is no + * API to read a row's state. `user_data` is handed back to the callback + * untouched and is never dereferenced by UDA. + * + * On success `*out_item_id` receives the row's stable, non-zero id; the + * callback receives the same value, so a host does not need a table of its + * own. + * + * # Safety + * + * `out_item_id` must be a valid, writable, non-null `uint64_t` slot. `label` + * must be a readable, null-terminated UTF-8 string; a blank label is rejected + * with `UDA_ERR_INVALID_ARGUMENT` + * because it would render an invisible row. */ int32_t uda_tray_menu_add_text(uint64_t menu_handle, const char *label, @@ -784,33 +871,24 @@ int32_t uda_tray_menu_add_text(uint64_t menu_handle, /** * Append a visual separator to a menu. * - * A separator has no label, no callback and no id, so there is no out-parameter. - * - * @param menu_handle A handle from uda_tray_menu_create(). - * @return UDA_OK on success, otherwise a negative status code. + * A separator has no label, no callback and no id, so there is no + * out-parameter. */ int32_t uda_tray_menu_add_separator(uint64_t menu_handle); /** * Append a checkbox row to a menu. * - * When a callback is supplied, the row's stored value is inverted *before* it - * runs, so the `checked` argument is the new state and the menu cannot drift - * out of sync with the shell. A NULL callback installs no handler at all: the - * row renders with its initial state and never toggles, which is what a host - * that drives the checkbox through its own UI wants. - * - * @param menu_handle A handle from uda_tray_menu_create(). - * @param label Row text; a blank label is rejected with - * UDA_ERR_INVALID_ARGUMENT. - * @param checked 0 starts unchecked, any other value starts checked. - * @param callback Invoked on the tray worker thread when the row is toggled, - * or NULL for a row that never toggles. - * @param user_data Handed back to `callback` untouched. - * @param out_item_id Receives the row's stable, non-zero id on success. Must - * not be null. - * @return UDA_OK on success; UDA_ERR_INVALID_ARGUMENT for a blank label or a - * handle that is not a live menu; otherwise a negative status code. + * When a `callback` is supplied, the row's own stored value is inverted *before* + * it runs, so the `checked` argument is the new state the shell will render. + * A null callback installs no handler at all: the row renders with its initial + * state and never toggles, which is what a host that drives the checkbox + * through its own UI wants. + * + * # Safety + * + * `out_item_id` must point to a writable, non-null `uint64_t` slot and + * `label` must be a readable, null-terminated UTF-8 string. */ int32_t uda_tray_menu_add_checkbox(uint64_t menu_handle, const char *label, @@ -824,104 +902,29 @@ int32_t uda_tray_menu_add_checkbox(uint64_t menu_handle, * * The menu handle stays valid after this call: the icon holds its own * reference, so the menu keeps working whether or not the handle is destroyed - * later. Destroying the handle (see uda_tray_menu_destroy()) detaches the menu - * from every icon still showing it. - * - * @param tray_handle A handle from uda_tray_create(). - * @param menu_handle A handle from uda_tray_menu_create(). - * @return UDA_OK on success, otherwise a negative status code. + * later. Destroying the handle (see [`uda_tray_menu_destroy`]) detaches the + * menu from every icon still showing it. */ int32_t uda_tray_set_menu(uint64_t tray_handle, uint64_t menu_handle); /** * Destroy a menu handle. * - * The menu is detached from EVERY tray icon that still shows it, so its rows - * and callbacks stop firing (a row snapshot a backend already cloned stays + * The menu is detached from **every** tray icon that still shows it, so its + * rows and callbacks stop firing (a snapshot a backend already cloned stays * silent instead of calling the host); the icons themselves stay alive and - * simply have no menu afterwards. This makes destroying a menu handle safe even - * when the host has already attached it. Terminal: the handle cannot be reused - * afterwards. - * - * While one of the menu's callbacks is still running, the destroy fails with - * UDA_ERR_INTERNAL and the menu stays fully intact: a host waits for its own - * callback to return and retries. Callback trampolines may be freed only after - * this call reports success. - * - * @param menu_handle A handle from uda_tray_menu_create(). - * @return UDA_OK on success, UDA_ERR_INVALID_ARGUMENT when the handle is not a - * live menu in this process, UDA_ERR_INTERNAL while a callback of this - * menu is still in flight (retry after it returned). + * simply have no menu afterwards. This makes destroying a menu handle safe + * even when the host has already attached it. Terminal: the handle cannot be + * reused afterwards. Returns `UDA_ERR_INVALID_ARGUMENT` when the handle is not + * a live menu, and `UDA_ERR_INTERNAL` while one of the menu's callbacks is + * still running - the menu stays fully intact then, so a host that waits for + * its own callback to return and retries will succeed; the host may free its + * callback trampolines only after this call reports success. */ int32_t uda_tray_menu_destroy(uint64_t menu_handle); -/** - * Report which tray features the active platform backend advertises. - * - * Writes a bitmask made of the UDA_TRAY_CAP_* flags to `*out_capabilities`; - * 0 means "no tray backend exists on this target", and a feature the backend - * cannot deliver has its bit cleared. The query is static and side-effect-free - * - it never registers anything with the shell - so a host may call it freely - * to decide whether to build tray UI at all, and what to degrade gracefully. - * - * UDA_TRAY_CAP_CLICK and UDA_TRAY_CAP_DOUBLE_CLICK are always cleared: the C - * ABI has no click-callback registration, so activation is delivered only - * through menu rows. The constants remain defined for a future click API; do - * not infer click events from this bitmask today. - * - * @param out_capabilities Receives the bitmask. Must not be null. - * @return UDA_OK on success, otherwise a negative status code. - */ -int32_t uda_tray_capabilities(uint32_t *out_capabilities); - -/** - * Report how completely one icon's tray registration succeeded. - * - * Writes one of the UDA_TRAY_SUPPORT_LEVEL_* codes to `*out_level`: - * UDA_TRAY_SUPPORT_LEVEL_FULL when nothing degraded, - * UDA_TRAY_SUPPORT_LEVEL_PARTIAL when the icon is live but its registration - * recorded a degradation (on Linux: no StatusNotifierWatcher, or the watcher - * refuses the registration, so the item is exported yet the shell may never - * display it), and - * UDA_TRAY_SUPPORT_LEVEL_NONE only when the backend never claimed a tray at - * all - not reachable through handles this library issued. - * - * The answer is per icon, not per platform: uda_tray_capabilities() reports - * which code paths exist, this reports what actually happened to THIS icon, - * and uda_tray_support_reason() explains a PARTIAL answer. - * - * On Windows the answer is always UDA_TRAY_SUPPORT_LEVEL_FULL for a live icon: - * the Win32 worker has no watcher step, so there is no degradation path. - * - * @param handle A handle from uda_tray_create(). - * @param out_level Receives one of the UDA_TRAY_SUPPORT_LEVEL_* codes. Must - * not be null. Left untouched on failure. - * @return UDA_OK on success; UDA_ERR_INVALID_ARGUMENT when the handle is not a - * live tray icon in this process; otherwise a negative status code. - */ -int32_t uda_tray_support_level(uint64_t handle, int32_t *out_level); - -/** - * Explain why one icon's tray support level is partial. - * - * On success `*out_reason` receives a heap C string the caller must release - * with uda_free_string(), or NULL when the icon is not degraded - check the - * pointer rather than the status. A degraded icon (see - * uda_tray_support_level()) always carries a non-empty, human-readable reason - * naming what is missing or refused, e.g. a session with no - * StatusNotifierWatcher or a watcher that rejects the item; a fully supported - * icon reports NULL. - * - * @param handle A handle from uda_tray_create(). - * @param out_reason Receives the newly allocated reason string, or NULL. Must - * not be null itself. Left untouched on failure. - * @return UDA_OK on success; UDA_ERR_INVALID_ARGUMENT when the handle is not a - * live tray icon in this process; otherwise a negative status code. - */ -int32_t uda_tray_support_reason(uint64_t handle, char **out_reason); - #ifdef __cplusplus -} -#endif +} // extern "C" +#endif // __cplusplus -#endif /* UDA_H_ */ +#endif /* UDA_H_ */ diff --git a/scripts/gen-header.sh b/scripts/gen-header.sh new file mode 100755 index 0000000..5c8dee8 --- /dev/null +++ b/scripts/gen-header.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# Regenerate include/uda.h from the Rust C-ABI surface via cbindgen. +# +# include/uda.h is a GENERATED file: never edit it by hand. Edit the doc +# comments on the exported functions in crates/uda-ffi, or the constants and +# callback types in crates/uda-ffi/src/abi.rs, then re-run this script and +# commit the header together with the Rust change. +# +# CI re-runs this script in --check mode (see .github/workflows/ci.yml), so a +# stale header fails the build instead of drifting silently. +# +# Usage: +# scripts/gen-header.sh # rewrite include/uda.h in place +# scripts/gen-header.sh --check # diff only; exit 1 when the header is stale +set -euo pipefail + +usage() { + echo "Usage: scripts/gen-header.sh [--check]" >&2 + echo " --check compare include/uda.h with fresh cbindgen output; exit 1 if stale" >&2 + echo " (default) rewrite include/uda.h in place" >&2 +} + +if [ "$#" -gt 1 ]; then + echo "error: expected at most one argument, got $#" >&2 + usage + exit 2 +fi + +check=false +case "${1:-}" in + "") ;; + --check) check=true ;; + *) + echo "error: unknown argument: $1" >&2 + usage + exit 2 + ;; +esac + +# Keep in sync with .github/workflows/ci.yml and crates/uda-ffi/cbindgen.toml: +# output can differ between cbindgen releases, so every consumer uses the same +# pinned version. +CBINDGEN_VERSION="0.29.4" + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +HEADER="$ROOT/include/uda.h" +CONFIG="$ROOT/crates/uda-ffi/cbindgen.toml" + +if ! command -v cbindgen >/dev/null 2>&1; then + echo "cbindgen not found; installing pinned v${CBINDGEN_VERSION} ..." >&2 + cargo install cbindgen --locked --version "$CBINDGEN_VERSION" +fi + +# `cargo install` can succeed while its bin directory (CARGO_HOME/bin) is not +# on PATH; fail with an actionable message instead of a bare "command not +# found" from the version probe below. +if ! command -v cbindgen >/dev/null 2>&1; then + echo "error: cbindgen is still not on PATH after installing it." >&2 + echo " Add the cargo bin directory (usually ~/.cargo/bin) to PATH." >&2 + exit 1 +fi + +installed="$(cbindgen --version | awk '{print $2}')" +if [ "$installed" != "$CBINDGEN_VERSION" ]; then + echo "error: cbindgen v${installed} installed; header generation requires v${CBINDGEN_VERSION}." >&2 + echo " Run: cargo install cbindgen --locked --version ${CBINDGEN_VERSION}" >&2 + exit 1 +fi + +# Keep the scratch file inside the workspace (`.tmp/` is gitignored): a +# `$TMPDIR` write can trip strict sandboxing setups, and every other throwaway +# artifact in this repo lands in `.tmp/` too. +mkdir -p "$ROOT/.tmp" +output="$(mktemp "$ROOT/.tmp/uda-header.XXXXXX")" +trap 'rm -f "$output"' EXIT + +# Resolve the crate through the workspace so the call works from any directory. +(cd "$ROOT" && cbindgen --config "$CONFIG" --crate uda-ffi --output "$output") + +# cbindgen renders negative constants bare (e.g. "#define UDA_ERR_IO -4"), +# which would turn a caller's "-UDA_ERR_IO" into the token "--4". Wrap +# negative literals in parentheses the way the header always has. The wrap +# only matches bare decimal literals, so fail loudly if any unwrapped +# negative define survives (a future `-0x10` or `-(1 << 4)` spelling must +# stop the generation here, not ship as `--...` tokens to callers). +perl -pi -e 's/^(#define UDA_[A-Z0-9_]+) (-\d+)$/$1 ($2)/' "$output" +if grep -nE '^#define UDA_[A-Za-z0-9_]+ -' "$output" >&2; then + echo "error: unwrapped negative constant(s) above would tokenize as" >&2 + echo " '--...' for callers; extend the wrapping step." >&2 + exit 1 +fi + +if [ "$check" = true ]; then + if ! diff -u "$HEADER" "$output"; then + echo + echo "error: include/uda.h is stale. Re-run scripts/gen-header.sh and" >&2 + echo " commit the regenerated header with your Rust change." >&2 + exit 1 + fi + echo "include/uda.h is up to date." +else + cp "$output" "$HEADER" + echo "regenerated $HEADER" +fi diff --git a/scripts/header_symbols.py b/scripts/header_symbols.py index 092a86c..2395745 100644 --- a/scripts/header_symbols.py +++ b/scripts/header_symbols.py @@ -2,12 +2,12 @@ # -*- coding: utf-8 -*- """List the ``uda_*`` function names declared in a C header. -The public header (``include/uda.h``) is the single source of truth for the -exported ABI surface: every ``#[no_mangle]`` symbol in ``crates/uda-ffi`` must be -declared there, and every declaration must be a real export of the built shared -library. Deriving the expected symbol set from the header means a newly added -export can never silently fail a check that hard-codes a stale count, which is -what broke the release pipeline. +The public header (``include/uda.h``, generated from ``crates/uda-ffi`` by +cbindgen) is the reference for the exported ABI surface: every ``#[no_mangle]`` +symbol in the crate must be declared there, and every declaration must be a +real export of the built shared library. Deriving the expected symbol set from +the header means a newly added export can never silently fail a check that +hard-codes a stale count, which is what broke the release pipeline. Usage:: @@ -52,7 +52,10 @@ def header_symbols(header: pathlib.Path) -> list[str]: # comments outright: none of them can hold a declaration. if stripped.startswith(("*", "/", "#")): continue - match = _DECLARATION.match(line) + # Match the stripped text, not the raw line: the declaration pattern is + # anchored at column 0, so an indented declaration (for example inside + # a future `#if` block) would otherwise be skipped silently. + match = _DECLARATION.match(stripped) if match: names.add(match.group(1)) return sorted(names) diff --git a/scripts/test-header.py b/scripts/test-header.py new file mode 100644 index 0000000..fa1c1f8 --- /dev/null +++ b/scripts/test-header.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +"""Direct regression checks for generated C semantics and the version gate. + +Run with: python3 -B scripts/test-header.py +Requires C11 and C++11 compilers (CC/CXX, defaulting to cc/c++). +""" + +import os +import re +import shlex +import subprocess +import tempfile +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +HEADER = ROOT / "include" / "uda.h" + +#: The canonical session-capability bits, part of the C ABI (see +#: `crates/uda-ffi/src/abi.rs`). The header is parsed and compared against this +#: map: a renumbered, renamed or dropped bit fails here, so the test proves the +#: header against an independent expectation instead of against itself. Adding +#: a capability therefore means updating both `abi.rs` and this map - which is +#: the point, since the numbers are a promise to C callers. +EXPECTED_CAPABILITIES = { + "MANAGEMENT": 16, + "LOCK": 17, + "LOGOUT": 18, + "SUSPEND": 19, + "HIBERNATE": 20, + "REBOOT": 21, + "SHUTDOWN": 22, +} + +#: A capability define exactly as cbindgen emits it: a name, then a 32-bit +#: unsigned shift expression. Leading whitespace and whitespace after the `#` +#: are allowed so a reformatted define (an `#if` block, a future formatter +#: style) is still parsed rather than silently skipped. +CAPABILITY_DEFINE = re.compile( + r"^\s*#\s*define\s+(UDA_SESSION_CAP_[A-Z0-9_]+)\s+\(1u\s*<<\s*(\d+)\)\s*$", + re.MULTILINE, +) +#: Any capability define, whatever its value shape, so a differently spelled +#: value cannot silently evade the strict parser above. +CAPABILITY_NAME = re.compile( + r"^\s*#\s*define\s+(UDA_SESSION_CAP_[A-Z0-9_]+)\b", re.MULTILINE +) + + +def parse_capabilities(text): + """Return ``{macro: bit}`` for every ``UDA_SESSION_CAP_*`` define in ``text``. + + Raises ``AssertionError`` when a define does not have the expected + ``#define NAME (1u << BIT)`` shape or when a name is defined twice, so a + malformed capability can never silently vanish from the parsed map. + """ + parsed = CAPABILITY_DEFINE.findall(text) + declared = CAPABILITY_NAME.findall(text) + if not declared: + raise AssertionError("no UDA_SESSION_CAP_* defines found") + if len(parsed) != len(declared): + raise AssertionError( + "a UDA_SESSION_CAP_* define does not have the expected " + f"'#define NAME (1u << BIT)' shape: {declared!r}" + ) + macros = {name: int(bit) for name, bit in parsed} + if len(macros) != len(parsed): + raise AssertionError(f"duplicate UDA_SESSION_CAP_* defines: {declared!r}") + return macros + + +def capability_macros(): + """Return sorted ``(macro, bit)`` pairs, checked against the ABI map.""" + macros = parse_capabilities(HEADER.read_text(encoding="utf-8")) + expected = { + f"UDA_SESSION_CAP_{name}": bit + for name, bit in EXPECTED_CAPABILITIES.items() + } + if macros != expected: + raise AssertionError( + "the header's capability defines disagree with the canonical ABI " + f"map (a bit was renumbered, renamed or dropped): " + f"header={macros!r} expected={expected!r}" + ) + return sorted(macros.items(), key=lambda item: item[1]) + + +class HeaderRegressionTests(unittest.TestCase): + def test_capability_parser_accepts_reformatted_defines(self): + # The strict shape check must not turn a reformatted define into a + # silent skip: indentation and a space after `#` are both legal C. + text = ( + "#define UDA_SESSION_CAP_LOCK (1u << 17)\n" + " # define UDA_SESSION_CAP_REBOOT (1u << 21)\n" + ) + self.assertEqual( + parse_capabilities(text), + {"UDA_SESSION_CAP_LOCK": 17, "UDA_SESSION_CAP_REBOOT": 21}, + ) + + def test_capability_parser_rejects_a_define_with_a_different_shape(self): + # A capability re-spelled with a different value must fail loudly rather + # than disappear from the parsed map: the value-agnostic name pattern + # still sees it, so the count mismatch trips the assertion. + with self.assertRaises(AssertionError): + parse_capabilities("#define UDA_SESSION_CAP_LOCK (2u << 17)\n") + + def test_capability_macros_preserve_unsigned_c_and_cpp_semantics(self): + for language, variable, default, standard in ( + ("c", "CC", "cc", "c11"), + ("c++", "CXX", "c++", "c++11"), + ): + with self.subTest(language=language): + lines = ['#include "uda.h"'] + if language == "c": + assertion = "_Static_assert" + unsigned_type = "_Generic(({macro}), unsigned int: 1, default: 0)" + else: + lines.append("#include ") + assertion = "static_assert" + unsigned_type = "std::is_same::value" + for macro, bit in capability_macros(): + lines.extend( + ( + f'{assertion}({unsigned_type.format(macro=macro)}, "{macro} type");', + f'{assertion}({macro} == {1 << bit}u, "{macro} value");', + # Type-width-derived: if the macro stops being a + # 32-bit unsigned value this complement comparison + # fails loudly instead of silently testing a + # hard-coded 0xFFFFFFFF. + f'{assertion}((uint64_t)(~{macro}) == (uint64_t)(~0u ^ (1u << {bit})), "{macro} complement");', + ) + ) + compiler = shlex.split(os.environ.get(variable, default)) + result = subprocess.run( + compiler + + [f"-std={standard}", "-Werror", "-fsyntax-only", "-x", language, + "-I", str(HEADER.parent), "-"], + input="\n".join(lines) + "\n", + text=True, + capture_output=True, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_callback_typedefs_are_usable_from_cpp(self): + # cbindgen emits the two callback typedefs before the extern "C" block. + # That does not change the exported function symbols, but a C++ consumer + # must still be able to assign an `extern "C"` function to each typedef + # exactly as the header documents. + source = "\n".join( + ( + '#include "uda.h"', + 'extern "C" void uya_text(uint64_t, void *);', + 'extern "C" void uya_checkbox(uint64_t, int32_t, void *);', + "UdaTrayTextCallback text_callback = uya_text;", + "UdaTrayCheckboxCallback checkbox_callback = uya_checkbox;", + "int main() { return text_callback == nullptr || checkbox_callback == nullptr; }", + ) + ) + "\n" + compiler = shlex.split(os.environ.get("CXX", "c++")) + result = subprocess.run( + compiler + + ["-std=c++11", "-Werror", "-pedantic", "-fsyntax-only", "-x", "c++", + "-I", str(HEADER.parent), "-"], + input=source, + text=True, + capture_output=True, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_status_alias_stays_rust_only(self): + self.assertNotRegex(HEADER.read_text(), r"\bUdaStatus\b") + + def test_wrong_generator_version_exits_before_generation(self): + scratch = ROOT / ".tmp" + scratch.mkdir(exist_ok=True) + header_before = HEADER.read_bytes() + with tempfile.TemporaryDirectory(prefix="header-test-", dir=scratch) as directory: + stub_dir = Path(directory) + calls = stub_dir / "calls" + stub = stub_dir / "cbindgen" + stub.write_text( + '#!/bin/sh\n' + 'printf "%s\\n" "$*" >> "$CBINDGEN_TEST_CALLS"\n' + 'if [ "$#" -eq 1 ] && [ "$1" = "--version" ]; then\n' + ' printf "cbindgen 0.29.3\\n"\n' + ' exit 0\n' + 'fi\n' + 'printf "generation reached\\n" >&2\n' + 'exit 99\n' + ) + stub.chmod(0o755) + env = os.environ.copy() + env["PATH"] = str(stub_dir) + os.pathsep + env.get("PATH", "") + env["CBINDGEN_TEST_CALLS"] = str(calls) + for arguments in ([], ["--check"]): + with self.subTest(arguments=arguments): + calls.write_text("") + result = subprocess.run( + ["bash", str(ROOT / "scripts" / "gen-header.sh"), *arguments], + env=env, + text=True, + capture_output=True, + ) + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("error: cbindgen v0.29.3 installed", result.stderr) + self.assertIn("requires v0.29.4", result.stderr) + self.assertEqual(calls.read_text(), "--version\n") + self.assertEqual(HEADER.read_bytes(), header_before) + + +if __name__ == "__main__": + unittest.main()