From 9ac4a583123bc937aaa797da4fc1acbd0bcf3045 Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Thu, 8 Oct 2026 12:02:52 +0800 Subject: [PATCH 01/17] refactor(ffi): centralize the C-ABI constants and callback types in src/abi.rs The C-ABI constants were scattered across four modules and duplicated between lib.rs and error.rs (the unit tests only asserted that the duplicates agreed). All UDA_* constants and the two tray callback types now live in src/abi.rs, the module cbindgen will turn into the generated include/uda.h (UniDesktop/SDK#6); the modules that merely implement the exports import what they need from there. The callback types are renamed to their C names (UdaTrayTextCallback, UdaTrayCheckboxCallback) so the generated typedef matches the Rust item verbatim. No C-visible change: include/uda.h is untouched and the exported functions, their signatures and every constant value are exactly as before. --- crates/uda-ffi/src/abi.rs | 177 ++++++++++++++++++++++++++++++++++ crates/uda-ffi/src/error.rs | 26 +---- crates/uda-ffi/src/lib.rs | 68 ++----------- crates/uda-ffi/src/media.rs | 27 +----- crates/uda-ffi/src/session.rs | 20 +--- crates/uda-ffi/src/tray.rs | 21 +--- crates/uda-ffi/src/util.rs | 11 ++- 7 files changed, 209 insertions(+), 141 deletions(-) create mode 100644 crates/uda-ffi/src/abi.rs diff --git a/crates/uda-ffi/src/abi.rs b/crates/uda-ffi/src/abi.rs new file mode 100644 index 0000000..632add9 --- /dev/null +++ b/crates/uda-ffi/src/abi.rs @@ -0,0 +1,177 @@ +//! 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 = 1 << 16; +/// The session can be locked - the only action safe to automate. +pub const UDA_SESSION_CAP_LOCK: u32 = 1 << 17; +/// The calling user's session can be ended. +pub const UDA_SESSION_CAP_LOGOUT: u32 = 1 << 18; +/// The machine can be suspended to RAM. +pub const UDA_SESSION_CAP_SUSPEND: u32 = 1 << 19; +/// The machine can be hibernated to disk. +pub const UDA_SESSION_CAP_HIBERNATE: u32 = 1 << 20; +/// The machine can be rebooted. +pub const UDA_SESSION_CAP_REBOOT: u32 = 1 << 21; +/// The machine can be powered off. +pub const UDA_SESSION_CAP_SHUTDOWN: u32 = 1 << 22; + +// --------------------------------------------------------------------------- +// Tray callbacks +// --------------------------------------------------------------------------- + +/// Callback type for a plain text menu 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 = extern "C" fn(u64, *mut c_void); + +/// Callback type for a checkbox menu 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 = extern "C" fn(u64, i32, *mut c_void); + +#[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 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"); + } + } + } +} diff --git a/crates/uda-ffi/src/error.rs b/crates/uda-ffi/src/error.rs index 2d2fbe6..3cf150c 100644 --- a/crates/uda-ffi/src/error.rs +++ b/crates/uda-ffi/src/error.rs @@ -17,30 +17,14 @@ 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 9739c3c..61c9674 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -33,6 +33,8 @@ //! wake-lock registry (internally synchronised) and the thread-local //! last-error slot. +pub mod abi; + mod dispatch; mod error; mod media; @@ -46,58 +48,8 @@ use std::os::raw::{c_char, c_int, c_void}; use uda_core::session::SessionAction; -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, -}; - -/// 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; +pub use abi::*; +pub use error::status_message; /// Detect the current system colour scheme. /// @@ -781,7 +733,7 @@ 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: Option, user_data: *mut c_void, out_item_id: *mut u64, ) -> c_int { @@ -825,7 +777,7 @@ pub unsafe extern "C" fn uda_tray_menu_add_checkbox( menu_handle: u64, label: *const c_char, checked: c_int, - callback: Option, + callback: Option, user_data: *mut c_void, out_item_id: *mut u64, ) -> c_int { @@ -926,14 +878,6 @@ mod tests { use super::*; 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); - } - #[test] fn fill_mode_codes_are_accepted_and_rejected() { assert!(fill_mode_from_c(UDA_FILL_CROP).is_ok()); diff --git a/crates/uda-ffi/src/media.rs b/crates/uda-ffi/src/media.rs index 06afa15..37fb9b6 100644 --- a/crates/uda-ffi/src/media.rs +++ b/crates/uda-ffi/src/media.rs @@ -31,28 +31,6 @@ use uda_core::media::{MediaCommand, MediaManager, MediaMetadata, PlaybackStatus} 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 @@ -139,6 +117,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, + }; #[test] fn command_codes_match_the_c_header() { diff --git a/crates/uda-ffi/src/session.rs b/crates/uda-ffi/src/session.rs index b9815c1..af20f6d 100644 --- a/crates/uda-ffi/src/session.rs +++ b/crates/uda-ffi/src/session.rs @@ -32,21 +32,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 @@ -113,6 +98,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 9000ea0..13f9d44 100644 --- a/crates/uda-ffi/src/tray.rs +++ b/crates/uda-ffi/src/tray.rs @@ -43,21 +43,10 @@ use uda_core::tray::{ MenuItem, TrayAction, TrayEvent, TrayIcon, TrayIconBuilder, TrayIconSource, TrayMenu, }; +use crate::abi::{UdaTrayCheckboxCallback, UdaTrayTextCallback}; 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 @@ -352,7 +341,7 @@ pub(crate) fn create_menu() -> Result { pub(crate) fn menu_add_text( menu_handle: u64, label: &str, - callback: Option, + callback: Option, user_data: *mut c_void, ) -> Result { let menu = TrayRegistry::global().menu(menu_handle)?; @@ -406,7 +395,7 @@ pub(crate) fn menu_add_checkbox( menu_handle: u64, label: &str, checked: bool, - callback: Option, + callback: Option, user_data: *mut c_void, ) -> Result { let menu = TrayRegistry::global().menu(menu_handle)?; @@ -515,7 +504,7 @@ mod tests { fn registry_text( menu: u64, label: &str, - callback: Option, + callback: Option, user_data: *mut c_void, ) -> Result { menu_add_text(menu, label, callback, user_data) @@ -526,7 +515,7 @@ mod tests { menu: u64, label: &str, checked: bool, - callback: Option, + callback: Option, user_data: *mut c_void, ) -> Result { menu_add_checkbox(menu, label, checked, callback, user_data) diff --git a/crates/uda-ffi/src/util.rs b/crates/uda-ffi/src/util.rs index ba1db5c..e624f31 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 @@ -19,7 +19,8 @@ use std::cell::RefCell; use std::os::raw::c_char; -use crate::error::{Failure, UdaStatus, UDA_ERR_PANIC}; +use crate::abi::UDA_ERR_PANIC; +use crate::error::{Failure, UdaStatus}; thread_local! { /// Message of the most recent failure on the calling thread. @@ -106,7 +107,7 @@ pub(crate) unsafe fn free_c_string(pointer: *mut c_char) { /// /// The closure returns a `Result<(), Failure>`; a `panic!` inside it is caught /// and reported as -/// [`UDA_ERR_PANIC`](crate::error::UDA_ERR_PANIC) so it can never unwind into +/// [`UDA_ERR_PANIC`](crate::abi::UDA_ERR_PANIC) so it can never unwind into /// foreign frames, where unwinding across an `extern "C"` boundary is undefined /// behaviour. pub(crate) fn catch_boundary(body: F) -> UdaStatus @@ -119,7 +120,7 @@ where let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)); match outcome { - Ok(Ok(())) => crate::error::UDA_OK, + Ok(Ok(())) => crate::abi::UDA_OK, Ok(Err(failure)) => { set_last_message(&failure.message()); failure.status() @@ -168,7 +169,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; #[test] From 8c536309e9231cb9ab8fe135dcc140dc76ab7d8f Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Thu, 8 Oct 2026 12:08:18 +0800 Subject: [PATCH 02/17] docs(ffi): fold the C header's API documentation into the Rust doc comments include/uda.h carried the richest documentation of the C-ABI surface, which meant every API fact was written twice and the two copies had started to drift. The header's per-function contracts, the tray handle lifetime and callback threading model, and the platform specifics in the session actions are now merged into the Rust doc comments of the exported functions, ready to be carried into the generated header. The exported functions are also reordered to match the header's logical grouping (appearance, wallpaper, wake locks, notifications, media, session, tray). Function bodies are untouched: a line-multiset diff of the file with doc comments stripped is empty. One documentation bug is fixed while merging: the header claimed uda_tray_set_icon_rgba() accepts a NULL data pointer when len is zero, but the implementation has always rejected NULL unconditionally. The merged doc states the implemented contract. --- crates/uda-ffi/src/lib.rs | 674 ++++++++++++++++++++++---------------- 1 file changed, 391 insertions(+), 283 deletions(-) diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index 61c9674..904bbb4 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -53,13 +53,13 @@ pub use error::status_message; /// 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 { if out_theme.is_null() { @@ -85,8 +85,10 @@ pub unsafe extern "C" fn uda_detect_theme(out_theme: *mut c_int) -> c_int { /// Set the desktop wallpaper. /// -/// `path` accepts both a plain filesystem path and a `file://` URI; an empty path -/// is rejected as an invalid argument rather than being sent to the backend. +/// `path` is a null-terminated UTF-8 filesystem path; a `file://` URI is also +/// accepted. An empty path is rejected as an invalid argument rather than +/// being sent to the backend. `fill_mode` is one of the `UDA_FILL_*` codes; +/// anything else is rejected. /// /// On failure a negative status code is returned and no wallpaper is changed. /// @@ -109,21 +111,229 @@ pub unsafe extern "C" fn uda_set_wallpaper(path: *const c_char, fill_mode: c_int }) } -/// Read the metadata of the active media player. +/// Read the current wallpaper path. /// -/// 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. With -/// no player running every out-parameter is set to null/zero and [`UDA_OK`] is -/// still returned. +/// 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` - check the pointer rather than the status to detect "no +/// wallpaper". /// -/// `out_position_ms` is optional: pass null to skip it. +/// # Safety +/// +/// `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 { + if out_path.is_null() { + util::set_last_message("`out_path` must not be null"); + return UDA_ERR_INVALID_ARGUMENT; + } + + util::catch_boundary(|| { + let path = dispatch::get_wallpaper_path()?; + + // SAFETY: null was rejected above, and the caller guarantees a writable + // pointer slot at this address. + unsafe { + *out_path = match &path { + Some(path) => util::c_string_from(path), + None => std::ptr::null_mut(), + }; + } + Ok(()) + }) +} + +/// Release a string previously returned by this library. +/// +/// Passing NULL is a no-op, so callers may free unconditionally. +/// +/// # Safety +/// +/// `s` must be null or a pointer obtained from a UDA export that hands out +/// strings. Freeing a pointer owned by the caller is undefined behaviour. +#[no_mangle] +pub unsafe extern "C" fn uda_free_string(s: *mut c_char) { + let _ = util::catch_boundary(|| { + // SAFETY: see the function's safety contract. + unsafe { util::free_c_string(s) }; + Ok(()) + }); +} + +/// 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. +/// +/// # Safety +/// +/// `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, + reason: *const c_char, + out_handle: *mut u64, +) -> c_int { + if out_handle.is_null() { + util::set_last_message("`out_handle` must not be null"); + return UDA_ERR_INVALID_ARGUMENT; + } + + util::catch_boundary(|| { + // SAFETY: `reason` was validated non-null and is converted with the same + // null-terminating, UTF-8-checking helper as `path`, so it cannot read + // past the end of the caller's buffer. + let reason = unsafe { util::owned_string_from(reason, "reason") }?; + let lock_type = wake_lock_type_from_c(lock_type)?; + let handle = dispatch::acquire_wakelock(lock_type, &reason)?; + + // SAFETY: `out_handle` was validated non-null above, and the caller + // guarantees a writable `uint64_t` at that address. + unsafe { *out_handle = handle.raw() }; + Ok(()) + }) +} + +/// 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, or never issued here). +#[no_mangle] +pub extern "C" fn uda_wakelock_release(handle: u64) -> c_int { + util::catch_boundary(|| { + let handle = dispatch::WakeLockHandle::from_raw(handle) + .ok_or_else(|| error::Failure::InvalidArgument("`handle` must not be 0".to_string()))?; + dispatch::release_wakelock(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. Use `WindowsNotificationManager::availability()` to +/// probe further. +/// +/// 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. +#[no_mangle] +pub unsafe extern "C" fn uda_notify( + app_name: *const c_char, + title: *const c_char, + body: *const c_char, + icon: *const c_char, + actions: *const c_char, + out_id: *mut u32, +) -> c_int { + if out_id.is_null() { + util::set_last_message("`out_id` must not be null"); + return UDA_ERR_INVALID_ARGUMENT; + } + + util::catch_boundary(|| { + let app_name = owned_or_empty(app_name, "app_name")?; + let title = owned_or_empty(title, "title")?; + let body = owned_or_empty(body, "body")?; + let icon = owned_or_empty(icon, "icon")?; + let actions = owned_or_empty(actions, "actions")?; + + let mut id = 0u32; + notify::notify(&app_name, &title, &body, &icon, &actions, &mut id)?; + // SAFETY: the slot was validated non-null and is writable. + unsafe { *out_id = id }; + Ok(()) + }) +} + +/// Read the system accent colour as four channels. +/// +/// 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. +/// +/// # Safety +/// +/// `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 { + if out_rgba.is_null() { + util::set_last_message("`out_rgba` must not be null"); + return UDA_ERR_INVALID_ARGUMENT; + } + + util::catch_boundary(|| { + let Some(color) = dispatch::accent_color() else { + log::debug!("no accent colour reported by the platform"); + return Ok(()); + }; + + // SAFETY: the pointer was validated non-null and the caller guarantees + // four writable bytes. + unsafe { + *out_rgba = color.r; + *out_rgba.add(1) = color.g; + *out_rgba.add(2) = color.b; + *out_rgba.add(3) = color.a; + } + Ok(()) + }) +} + +/// 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 "no player" when +/// none 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, which lets a binding +/// skip it. The artist list is already joined with ", " when the player +/// publishes several artists. +/// +/// `out_duration_ms` receives the track length in milliseconds, or 0 when +/// unknown (a live stream). `out_position_ms` is optional: pass NULL to skip +/// it; it receives the playback position in milliseconds, or 0 when the +/// backend cannot report 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`. +/// `out_position_ms` must be NULL or point at a writable `uint64_t`. #[no_mangle] pub unsafe extern "C" fn uda_media_get_metadata( out_title: *mut *mut c_char, @@ -167,16 +377,15 @@ 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 platform has no media backend at all. /// /// # 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 { if out_status.is_null() { @@ -195,13 +404,15 @@ pub unsafe extern "C" fn uda_media_get_status(out_status: *mut c_int) -> c_int { /// 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 unknown 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 unrecognised code returns +/// `UDA_ERR_INVALID_ARGUMENT` and nothing is sent. /// -/// [`UDA_ERR_NOT_SUPPORTED`](crate::error::UDA_ERR_NOT_SUPPORTED) is returned -/// when the player refuses the command and when no player is running. +/// 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. /// /// # Safety /// @@ -216,16 +427,23 @@ pub unsafe extern "C" fn uda_media_send_command(command: c_int) -> c_int { /// Report which session and power actions this platform can perform. /// -/// Writes a bitmask made of the [`UDA_SESSION_CAP_*`] constants to -/// `*out_capabilities`; `0` means "no session backend exists on this target". -/// The query is side-effect-free, so a UI may call it freely to decide which -/// menu entries to draw. +/// Writes a bitmask made of the `UDA_SESSION_CAP_*` flags to +/// `*out_capabilities`; 0 means "no session backend exists on this target". /// -/// A set bit means "the code path exists", not "the account is allowed". +/// The query is static and side-effect-free - it never touches the machine's +/// power state - so a host may call it freely to decide which menu entries to +/// draw, and *must* call it before drawing one that could shut the machine +/// down. +/// +/// A set bit means "the code path exists", not "the account is allowed": a +/// machine with hibernation switched off still reports +/// `UDA_SESSION_CAP_HIBERNATE`, and the attempt then fails with +/// `UDA_ERR_NOT_SUPPORTED`. Likewise, Windows reboot and shutdown need the +/// SeShutdownPrivilege, which is a runtime answer. /// /// # Safety /// -/// `out_capabilities` must point at a writable `uint32_t` location. +/// `out_capabilities` must point to a writable, non-null `uint32_t` location. #[no_mangle] pub unsafe extern "C" fn uda_session_capabilities(out_capabilities: *mut u32) -> c_int { if out_capabilities.is_null() { @@ -241,14 +459,15 @@ pub unsafe extern "C" fn uda_session_capabilities(out_capabilities: *mut u32) -> }) } -/// Lock the session, leaving every running program alone. +/// Lock the session. /// -/// 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. +/// Linux: `org.freedesktop.ScreenSaver.Lock()` on the session bus, falling +/// back to `loginctl lock-session`. Windows: `LockWorkStation()`. /// -/// Returns [`UDA_ERR_NOT_SUPPORTED`](crate::error::UDA_ERR_NOT_SUPPORTED) when -/// the platform advertises no lock capability at all. +/// 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 must be gated behind an explicit user +/// confirmation. /// /// # Safety /// @@ -260,8 +479,12 @@ pub unsafe extern "C" fn uda_session_lock() -> c_int { /// End the calling user's session. /// -/// **This action logs the user out.** Unsaved work is lost unless the desktop -/// refuses to comply. Never call it without an explicit confirmation. +/// 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)`. +/// +/// 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 /// @@ -276,7 +499,7 @@ pub unsafe extern "C" fn uda_session_logout() -> c_int { /// Linux: `org.freedesktop.login1.Manager.Suspend(false)`. Windows: /// `SetSuspendState(false, ...)`. /// -/// **This action changes the machine's power state.** Never call it without an +/// WARNING: this changes the machine's power state. Never call it without an /// explicit user confirmation. /// /// # Safety @@ -289,8 +512,13 @@ pub unsafe extern "C" fn uda_session_suspend() -> c_int { /// Hibernate the machine to disk. /// -/// **This action changes the machine's power state.** Unsaved work is lost. -/// Never call it without an explicit user confirmation. +/// 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`. +/// +/// WARNING: this changes the machine's power state. Never call it without an +/// explicit user confirmation. /// /// # Safety /// @@ -302,11 +530,13 @@ pub unsafe extern "C" fn uda_session_hibernate() -> c_int { /// Restart the machine. /// -/// On Windows this needs an elevated process or a local administrator account -/// for `SeShutdownPrivilege`; without it the call fails with -/// [`UDA_ERR_NOT_SUPPORTED`](crate::error::UDA_ERR_NOT_SUPPORTED). +/// 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. /// -/// **This action restarts the machine.** Unsaved work is lost. Never call it +/// WARNING: this restarts the machine and unsaved work is lost. Never call it /// without an explicit user confirmation. /// /// # Safety @@ -319,10 +549,13 @@ pub unsafe extern "C" fn uda_session_reboot() -> c_int { /// Power the machine off. /// -/// Same elevation requirement as [`uda_session_reboot`]. +/// 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()`. /// -/// **This action shuts the machine down.** Unsaved work is lost. Never call it -/// without an explicit user confirmation. +/// WARNING: this shuts the machine down and unsaved work is lost. Never call +/// it without an explicit user confirmation. /// /// # Safety /// @@ -332,187 +565,11 @@ pub unsafe extern "C" fn uda_session_shutdown() -> c_int { util::catch_boundary(|| session::perform(SessionAction::Shutdown)) } -/// 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". -/// -/// # Safety -/// -/// `out_path` must be a valid, writable, non-null pointer location. -#[no_mangle] -pub unsafe extern "C" fn uda_get_wallpaper(out_path: *mut *mut c_char) -> c_int { - if out_path.is_null() { - util::set_last_message("`out_path` must not be null"); - return UDA_ERR_INVALID_ARGUMENT; - } - - util::catch_boundary(|| { - let path = dispatch::get_wallpaper_path()?; - - // SAFETY: null was rejected above, and the caller guarantees a writable - // pointer slot at this address. - unsafe { - *out_path = match &path { - Some(path) => util::c_string_from(path), - None => std::ptr::null_mut(), - }; - } - Ok(()) - }) -} - -/// # Safety -/// -/// `s` must be null or a pointer obtained from [`uda_get_wallpaper`]. Freeing a -/// pointer owned by the caller is undefined behaviour. Passing null is a no-op, -/// so callers may free unconditionally. -#[no_mangle] -pub unsafe extern "C" fn uda_free_string(s: *mut c_char) { - let _ = util::catch_boundary(|| { - // SAFETY: see the function's safety contract. - unsafe { util::free_c_string(s) }; - Ok(()) - }); -} - -/// 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. -/// -/// # Safety -/// -/// `out_handle` must be a valid, writable, non-null `uint64_t` location and -/// `reason` a readable, null-terminated UTF-8 string. -#[no_mangle] -pub unsafe extern "C" fn uda_wakelock_acquire( - lock_type: c_int, - reason: *const c_char, - out_handle: *mut u64, -) -> c_int { - if out_handle.is_null() { - util::set_last_message("`out_handle` must not be null"); - return UDA_ERR_INVALID_ARGUMENT; - } - - util::catch_boundary(|| { - // SAFETY: `reason` was validated non-null and is converted with the same - // null-terminating, UTF-8-checking helper as `path`, so it cannot read - // past the end of the caller's buffer. - let reason = unsafe { util::owned_string_from(reason, "reason") }?; - let lock_type = wake_lock_type_from_c(lock_type)?; - let handle = dispatch::acquire_wakelock(lock_type, &reason)?; - - // SAFETY: `out_handle` was validated non-null above, and the caller - // guarantees a writable `uint64_t` at that address. - unsafe { *out_handle = handle.raw() }; - Ok(()) - }) -} - -/// 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, or never issued here). -#[no_mangle] -pub extern "C" fn uda_wakelock_release(handle: u64) -> c_int { - util::catch_boundary(|| { - let handle = dispatch::WakeLockHandle::from_raw(handle) - .ok_or_else(|| error::Failure::InvalidArgument("`handle` must not be 0".to_string()))?; - dispatch::release_wakelock(handle) - }) -} - -/// 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. -/// -/// # 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. -#[no_mangle] -pub unsafe extern "C" fn uda_notify( - app_name: *const c_char, - title: *const c_char, - body: *const c_char, - icon: *const c_char, - actions: *const c_char, - out_id: *mut u32, -) -> c_int { - if out_id.is_null() { - util::set_last_message("`out_id` must not be null"); - return UDA_ERR_INVALID_ARGUMENT; - } - - util::catch_boundary(|| { - let app_name = owned_or_empty(app_name, "app_name")?; - let title = owned_or_empty(title, "title")?; - let body = owned_or_empty(body, "body")?; - let icon = owned_or_empty(icon, "icon")?; - let actions = owned_or_empty(actions, "actions")?; - - let mut id = 0u32; - notify::notify(&app_name, &title, &body, &icon, &actions, &mut id)?; - // SAFETY: the slot was validated non-null and is writable. - unsafe { *out_id = id }; - Ok(()) - }) -} - -/// Read the system accent colour. -/// -/// 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. -/// -/// # Safety -/// -/// `out_rgba` must point at four writable `uint8_t` values. -#[no_mangle] -pub unsafe extern "C" fn uda_get_accent_color(out_rgba: *mut u8) -> c_int { - if out_rgba.is_null() { - util::set_last_message("`out_rgba` must not be null"); - return UDA_ERR_INVALID_ARGUMENT; - } - - util::catch_boundary(|| { - let Some(color) = dispatch::accent_color() else { - log::debug!("no accent colour reported by the platform"); - return Ok(()); - }; - - // SAFETY: the pointer was validated non-null and the caller guarantees - // four writable bytes. - unsafe { - *out_rgba = color.r; - *out_rgba.add(1) = color.g; - *out_rgba.add(2) = color.b; - *out_rgba.add(3) = color.a; - } - Ok(()) - }) -} - -/// Return the message describing the most recent failure on this thread. +/// Return the message describing the most recent failure on the calling +/// thread. /// /// The returned string is owned by the library and stays valid until the next -/// UDA call on the same thread; copy it if it must outlive that. Returns null +/// UDA call on the same thread; copy it if it must outlive that. Returns NULL /// when no failure has been recorded yet. #[no_mangle] pub extern "C" fn uda_last_error_message() -> *const c_char { @@ -531,14 +588,9 @@ pub extern "C" fn uda_last_error_message() -> *const 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 { STATUS_MESSAGES.with(|cache| { @@ -566,18 +618,60 @@ pub extern "C" fn uda_status_message(status: c_int) -> *const c_char { /// Create a tray icon. /// -/// `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; text longer than 127 `char`s is -/// clamped, and the call still succeeds. +/// TRAY HANDLES +/// +/// 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. +/// +/// - 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 destroying the menu afterwards leaves the tray +/// working. Destroy the menu explicitly only when the icon will never need +/// it again. +/// +/// 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 and +/// still reports its state in later calls. +/// +/// ARGUMENTS +/// +/// `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; text longer than 127 characters +/// is clamped, and the call still succeeds. /// /// 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, @@ -613,10 +707,12 @@ 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 { util::catch_boundary(|| { @@ -625,10 +721,11 @@ pub unsafe extern "C" fn uda_tray_set_tooltip(handle: u64, tooltip: *const c_cha }) } -/// 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`, `.png`, +/// `.bmp`). /// /// # Safety /// @@ -646,16 +743,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 buffer shorter than `stride * height` is rejected 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. `width` +/// and `height` must be non-zero and `stride` at least `width * 4`. #[no_mangle] pub unsafe extern "C" fn uda_tray_set_icon_rgba( handle: u64, @@ -675,7 +773,7 @@ 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 { util::catch_boundary(|| tray::set_visible(handle, visible != 0)) @@ -683,9 +781,10 @@ pub extern "C" fn uda_tray_set_visible(handle: u64, visible: c_int) -> c_int { /// 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 { util::catch_boundary(|| tray::destroy_icon(handle)) @@ -693,12 +792,13 @@ pub extern "C" fn uda_tray_destroy(handle: u64) -> c_int { /// 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 { if out_menu_handle.is_null() { @@ -715,20 +815,20 @@ pub unsafe extern "C" fn uda_tray_menu_create(out_menu_handle: *mut u64) -> c_in /// Append a plain text row to a menu. /// -/// `callback` is invoked on the **tray worker thread** when the row is -/// activated. Passing `None` (null) is legal: the row toggles silently, which is -/// what a host using a polling model wants. `user_data` is handed back to the -/// callback untouched and is never dereferenced by UDA. +/// `callback` is invoked on the tray worker thread when the row is activated, +/// or NULL for a silent row that still renders and still reports its state +/// in later calls. `user_data` is handed back to the callback untouched and +/// is never dereferenced by UDA. `label` must be non-blank: a blank label is +/// rejected with `UDA_ERR_NOT_SUPPORTED` because it would render invisibly. /// -/// 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 /// -/// `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_NOT_SUPPORTED`](crate::error::UDA_ERR_NOT_SUPPORTED) because -/// it would render an invisible row. +/// `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_text( menu_handle: u64, @@ -756,7 +856,8 @@ 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 { util::catch_boundary(|| tray::menu_add_separator(menu_handle)) @@ -764,14 +865,19 @@ pub extern "C" fn uda_tray_menu_add_separator(menu_handle: u64) -> c_int { /// Append a checkbox row to a menu. /// -/// The row's own stored value is inverted *before* `callback` runs, so the -/// `checked` argument is the new state the shell will render. `callback` may be -/// null, in which case the row still toggles silently. +/// The row's stored value is inverted *before* `callback` runs, so the +/// `checked` argument is the new state the shell will render and the menu +/// cannot drift out of sync with it. `checked` is 0 to start unchecked, any +/// other value to start checked. `callback` is invoked on the tray worker +/// thread when the row is toggled, or NULL for a silent row. `label` must be +/// non-blank: a blank label is rejected with `UDA_ERR_NOT_SUPPORTED`. +/// +/// On success `*out_item_id` receives the row's stable, non-zero id. /// /// # 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, @@ -804,8 +910,8 @@ pub unsafe extern "C" fn uda_tray_menu_add_checkbox( /// Attach a menu to a tray icon, replacing any menu set earlier. /// /// The menu handle stays valid after this call: the icon holds its own -/// reference, so `uda_tray_menu_destroy` on the same menu is optional and does -/// not clear the tray's rows. +/// reference, so destroying the menu afterwards is optional and does not +/// clear the rows. #[no_mangle] pub extern "C" fn uda_tray_set_menu(tray_handle: u64, menu_handle: u64) -> c_int { util::catch_boundary(|| tray::set_menu(tray_handle, menu_handle)) @@ -813,8 +919,10 @@ pub extern "C" fn uda_tray_set_menu(tray_handle: u64, menu_handle: u64) -> c_int /// Destroy a menu handle. /// -/// Safe to call after `uda_tray_set_menu`, as documented there. Returns -/// `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live menu. +/// Safe to call after `uda_tray_set_menu()`, as documented there. Terminal: +/// the handle cannot be reused afterwards. Returns +/// `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live menu in this +/// process. #[no_mangle] pub extern "C" fn uda_tray_menu_destroy(menu_handle: u64) -> c_int { util::catch_boundary(|| tray::destroy_menu(menu_handle)) From aaeb9e93ae2f3c36e2fd03162644b025b0a30c8e Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Thu, 8 Oct 2026 12:20:57 +0800 Subject: [PATCH 03/17] feat(ffi): generate include/uda.h with cbindgen include/uda.h becomes a generated artifact: cbindgen turns the exported functions in crates/uda-ffi/src/lib.rs and the surface types in src/abi.rs into the header, making the Rust sources the single source of truth for the C ABI (UniDesktop/SDK#6). - crates/uda-ffi/cbindgen.toml: language=c, doxygen-style documentation carried from the Rust doc comments, UDA_H_ include guard, a DO NOT EDIT warning, and a preamble with the status-code convention, memory ownership, thread-safety and ABI-stability notes. - scripts/gen-header.sh regenerates the header (cbindgen pinned to 0.29.4) and supports --check for CI; it normalises negative #define values into parentheses so a caller's -UDA_ERR_IO keeps parsing. - CI's Cross-Compile Hygiene job regenerates the header and fails on drift; header_symbols.py / pe_exports.py stay as the independent header-to-library symbol gates. - Exported signatures now use i32 (instead of c_int) and usize_is_size_t is enabled, so the generated header keeps saying int32_t/size_t exactly like the hand-written one; the tray callback aliases are Option so cbindgen emits the function-pointer typedefs. Zero semantic change for C callers: 33 constant values, 32 function signatures and both callback typedefs were compared old-vs-new and are equal; scripts/header_symbols.py lists the identical 32 symbols, and the header compiles warning-free as both C and C++. --- .github/workflows/ci.yml | 33 +- AGENTS.md | 3 + CHANGELOG.md | 13 + README.md | 2 +- README_CN.md | 2 +- crates/uda-ffi/cbindgen.toml | 80 +++ crates/uda-ffi/src/abi.rs | 8 +- crates/uda-ffi/src/lib.rs | 84 +-- crates/uda-ffi/src/tray.rs | 8 +- include/uda.h | 1151 ++++++++++++++++++---------------- scripts/gen-header.sh | 60 ++ scripts/header_symbols.py | 12 +- 12 files changed, 857 insertions(+), 599 deletions(-) create mode 100644 crates/uda-ffi/cbindgen.toml create mode 100755 scripts/gen-header.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ce6d830..ef84ffa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,6 +74,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. # ========================================================================== @@ -175,10 +186,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 @@ -254,12 +266,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 2f74616..c79519d 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. --- @@ -160,3 +162,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 4cec833..e492da7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), > 完整文档见 [unidesktop.github.io](https://unidesktop.github.io/)。 > Full documentation lives at [unidesktop.github.io](https://unidesktop.github.io/). +## [Unreleased] + +### 🛠️ Changed + +- 🛠️ **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. + - 对 C 调用者零语义变化:33 个常量值、32 个函数签名与 2 个回调 typedef 逐一比对等价;`header_symbols.py` 与 `pe_exports.py` 的「头文件 ↔ 动态库符号」校验保持不变。 + - Zero semantic change for C callers: all 33 constant values, 32 function signatures and both callback typedefs compare equal one by one; the `header_symbols.py` / `pe_exports.py` header-to-library symbol checks are unchanged. + ## [v0.2.1] - Honest Theme Reporting & Reasoned Degradation · 2026-10-06 ### ✨ Added 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-ffi/cbindgen.toml b/crates/uda-ffi/cbindgen.toml new file mode 100644 index 0000000..7b20b66 --- /dev/null +++ b/crates/uda-ffi/cbindgen.toml @@ -0,0 +1,80 @@ +# 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 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 +documentation_style = "c" + +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. Human- + * readable diagnostics for the most recent failure are available from + * `uda_last_error_message()`, and `uda_status_message()` renders any code + * without crossing the boundary again. + * + * 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. + * - 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 + * (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 index 632add9..6e5c619 100644 --- a/crates/uda-ffi/src/abi.rs +++ b/crates/uda-ffi/src/abi.rs @@ -122,19 +122,19 @@ pub const UDA_SESSION_CAP_SHUTDOWN: u32 = 1 << 22; // Tray callbacks // --------------------------------------------------------------------------- -/// Callback type for a plain text menu row. +/// 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 = extern "C" fn(u64, *mut c_void); +pub type UdaTrayTextCallback = Option; -/// Callback type for a checkbox menu row. +/// 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 = extern "C" fn(u64, i32, *mut c_void); +pub type UdaTrayCheckboxCallback = Option; #[cfg(test)] mod tests { diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index 904bbb4..074d320 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 //! @@ -44,7 +46,7 @@ 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; @@ -61,7 +63,7 @@ pub use error::status_message; /// /// `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; @@ -96,7 +98,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; @@ -123,7 +125,7 @@ pub unsafe extern "C" fn uda_set_wallpaper(path: *const c_char, fill_mode: c_int /// /// `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; @@ -174,10 +176,10 @@ pub unsafe extern "C" fn uda_free_string(s: *mut c_char) { /// `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; @@ -203,7 +205,7 @@ pub unsafe extern "C" fn uda_wakelock_acquire( /// Returns `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live lock in /// this process (already released, or never issued here). #[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()))?; @@ -251,7 +253,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; @@ -283,7 +285,7 @@ pub unsafe extern "C" fn uda_notify( /// /// `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; @@ -341,7 +343,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() @@ -387,7 +389,7 @@ pub unsafe extern "C" fn uda_media_get_metadata( /// /// `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; @@ -418,7 +420,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) @@ -445,7 +447,7 @@ pub unsafe extern "C" fn uda_media_send_command(command: c_int) -> c_int { /// /// `out_capabilities` must point to a writable, non-null `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; @@ -473,7 +475,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)) } @@ -490,7 +492,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)) } @@ -506,7 +508,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)) } @@ -524,7 +526,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)) } @@ -543,7 +545,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)) } @@ -561,7 +563,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)) } @@ -592,7 +594,7 @@ pub extern "C" fn uda_last_error_message() -> *const c_char { /// **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) { @@ -677,7 +679,7 @@ 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; @@ -714,7 +716,7 @@ pub unsafe extern "C" fn uda_tray_create( /// `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) @@ -731,7 +733,7 @@ pub unsafe extern "C" fn uda_tray_set_tooltip(handle: u64, tooltip: *const c_cha /// /// `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; @@ -762,7 +764,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; @@ -775,7 +777,7 @@ pub unsafe extern "C" fn uda_tray_set_icon_rgba( /// /// `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)) } @@ -786,7 +788,7 @@ pub extern "C" fn uda_tray_set_visible(handle: u64, visible: c_int) -> c_int { /// `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)) } @@ -800,7 +802,7 @@ pub extern "C" fn uda_tray_destroy(handle: u64) -> c_int { /// /// `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; @@ -833,10 +835,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; @@ -859,7 +861,7 @@ pub unsafe extern "C" fn uda_tray_menu_add_text( /// 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)) } @@ -882,11 +884,11 @@ pub extern "C" fn uda_tray_menu_add_separator(menu_handle: u64) -> c_int { 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; @@ -913,7 +915,7 @@ pub unsafe extern "C" fn uda_tray_menu_add_checkbox( /// reference, so destroying the menu afterwards is optional and does not /// clear the rows. #[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)) } @@ -924,7 +926,7 @@ pub extern "C" fn uda_tray_set_menu(tray_handle: u64, menu_handle: u64) -> c_int /// `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live menu in this /// process. #[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)) } @@ -945,12 +947,12 @@ fn owned_or_empty(pointer: *const c_char, parameter: &str) -> Result> = + 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`]. -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, @@ -967,7 +969,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, @@ -1011,7 +1013,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) }; assert_eq!(status, UDA_OK); diff --git a/crates/uda-ffi/src/tray.rs b/crates/uda-ffi/src/tray.rs index 13f9d44..09a4839 100644 --- a/crates/uda-ffi/src/tray.rs +++ b/crates/uda-ffi/src/tray.rs @@ -341,7 +341,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 = TrayRegistry::global().menu(menu_handle)?; @@ -395,7 +395,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 = TrayRegistry::global().menu(menu_handle)?; @@ -504,7 +504,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) @@ -515,7 +515,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) diff --git a/include/uda.h b/include/uda.h index 056fc99..60e5ec0 100644 --- a/include/uda.h +++ b/include/uda.h @@ -5,266 +5,359 @@ * - 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. Human- + * readable diagnostics for the most recent failure are available from + * `uda_last_error_message()`, and `uda_status_message()` renders any code + * without crossing the boundary again. * * 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. + * - 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. * - 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. + * (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. + * 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(). 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 -/** - * 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. - */ -#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 - -/* ------------------------------------------------------------------------- */ -/* Functions */ -/* ------------------------------------------------------------------------- */ - -/** - * 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. +/* + 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. + */ +#define UDA_SESSION_CAP_MANAGEMENT (1 << 16) + +/* + The session can be locked - the only action safe to automate. + */ +#define UDA_SESSION_CAP_LOCK (1 << 17) + +/* + The calling user's session can be ended. + */ +#define UDA_SESSION_CAP_LOGOUT (1 << 18) + +/* + The machine can be suspended to RAM. + */ +#define UDA_SESSION_CAP_SUSPEND (1 << 19) + +/* + The machine can be hibernated to disk. + */ +#define UDA_SESSION_CAP_HIBERNATE (1 << 20) + +/* + The machine can be rebooted. + */ +#define UDA_SESSION_CAP_REBOOT (1 << 21) + +/* + The machine can be powered off. + */ +#define UDA_SESSION_CAP_SHUTDOWN (1 << 22) + +/* + 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. + */ +typedef void (*UdaTrayTextCallback)(uint64_t, void*); + +/* + 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. + */ +typedef void (*UdaTrayCheckboxCallback)(uint64_t, int32_t, void*); + +/* + Detect the current system colour scheme. + + 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 point to a writable, non-null `int32_t` location. */ int32_t uda_detect_theme(int32_t *out_theme); -/** - * Set the desktop wallpaper. - * - * @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. +/* + Set the desktop wallpaper. + + `path` is a null-terminated UTF-8 filesystem path; a `file://` URI is also + accepted. An empty path is rejected as an invalid argument rather than + being sent to the backend. `fill_mode` is one of the `UDA_FILL_*` codes; + anything else is rejected. + + On failure a negative status code is returned and no wallpaper is changed. + + # Safety + + `path` must be a valid, readable, null-terminated UTF-8 string. */ int32_t uda_set_wallpaper(const char *path, int32_t fill_mode); -/** - * 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". - * - * @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. +/* + 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` - check the pointer rather than the status to detect "no + wallpaper". + + # 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. - * - * Passing NULL is a no-op, so callers may free unconditionally. - * - * @param s A pointer obtained from `uda_get_wallpaper()`, or NULL. +/* + Release a string previously returned by this library. + + Passing NULL is a no-op, so callers may free unconditionally. + + # Safety + + `s` must be null or a pointer obtained from a UDA export that hands out + strings. Freeing a pointer owned by the caller is undefined behaviour. */ void uda_free_string(char *s); -/** - * Acquire a wake lock. - * - * @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. +/* + 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. + + # 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 obtained from `uda_wakelock_acquire()`. - * - * Returns UDA_ERR_INVALID_ARGUMENT when the handle is not a live lock in this - * process (already released, or never issued here). - * - * @param handle A non-zero handle from `uda_wakelock_acquire()`. - * @return UDA_OK on success, otherwise a negative status code. +/* + 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, or never issued here). */ int32_t uda_wakelock_release(uint64_t handle); -/* ------------------------------------------------------------------------- */ -/* Notifications */ -/* ------------------------------------------------------------------------- */ +/* + Send a system notification. -/** - * 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. - * - * 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. - * - * A trailing `key` without its `label` is dropped rather than rendered as a - * blank button. - * - * 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. + 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. Use `WindowsNotificationManager::availability()` to + probe further. + + 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, @@ -273,45 +366,48 @@ int32_t uda_notify(const char *app_name, const char *actions, uint32_t *out_id); -/** - * Read the system accent colour as four channels. - * - * 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. - * - * @param out_rgba Pointer to four writable `uint8_t` values. Must not be null. - * @return UDA_OK on success, otherwise a negative status code. +/* + Read the system accent colour as four channels. + + 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. + + # Safety + + `out_rgba` must point to four writable `uint8_t` values. */ int32_t uda_get_accent_color(uint8_t *out_rgba); -/** - * 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, which lets a binding skip it. - * - * @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 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 "no player" when + none 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, which lets a binding + skip it. The artist list is already joined with ", " when the player + publishes several artists. + + `out_duration_ms` receives the track length in milliseconds, or 0 when + unknown (a live stream). `out_position_ms` is optional: pass NULL to skip + it; it receives the playback position in milliseconds, or 0 when the + backend cannot report 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, @@ -319,263 +415,279 @@ int32_t uda_media_get_metadata(char **out_title, uint64_t *out_duration_ms, uint64_t *out_position_ms); -/** - * 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. - * - * @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. +/* + 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. + + # Safety + + `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. - * - * 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. - * - * @param command One of the UDA_MEDIA_CMD_* codes. - * @return UDA_OK on success, otherwise a negative status code. +/* + 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. + + 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. + + # 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 session backend exists on this target". - * - * The query is static and side-effect-free - it never touches the machine's - * power state - so a host may call it freely to decide which menu entries to - * draw, and *must* call it before drawing one that could shut the machine down. - * - * A set bit means "the code path exists", not "the account is allowed": a - * machine with hibernation switched off still reports UDA_SESSION_CAP_HIBERNATE, - * and the attempt then fails with UDA_ERR_NOT_SUPPORTED. Likewise, Windows - * reboot and shutdown need the SeShutdownPrivilege, which is a runtime answer. - * - * @param out_capabilities Receives the bitmask. Must not be null. - * @return UDA_OK on success, otherwise a negative status code. +/* + 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 session backend exists on this target". + + The query is static and side-effect-free - it never touches the machine's + power state - so a host may call it freely to decide which menu entries to + draw, and *must* call it before drawing one that could shut the machine + down. + + A set bit means "the code path exists", not "the account is allowed": a + machine with hibernation switched off still reports + `UDA_SESSION_CAP_HIBERNATE`, and the attempt then fails with + `UDA_ERR_NOT_SUPPORTED`. Likewise, Windows reboot and shutdown need the + SeShutdownPrivilege, which is a runtime answer. + + # Safety + + `out_capabilities` must point to a writable, non-null `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()`. - * - * 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 - * confirmation. - * - * @return UDA_OK on success, otherwise a negative status code. +/* + Lock the session. + + Linux: `org.freedesktop.ScreenSaver.Lock()` on the session bus, falling + back to `loginctl lock-session`. Windows: `LockWorkStation()`. + + 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 must be gated behind an explicit user + confirmation. + + # 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)`. - * - * WARNING: this logs the user out. Unsaved work in applications that do not - * refuse is lost. Never call it without an explicit user confirmation. - * - * @return UDA_OK on success, otherwise a negative status code. +/* + 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)`. + + 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 + + This function takes no pointers; there is nothing to validate. */ int32_t uda_session_logout(void); -/** - * Suspend the machine to RAM. - * - * Linux: `org.freedesktop.login1.Manager.Suspend(false)`. Windows: - * `SetSuspendState(false, ...)`. - * - * WARNING: this changes the machine's power state. Never call it without an - * explicit user confirmation. - * - * @return UDA_OK on success, otherwise a negative status code. +/* + Suspend the machine to RAM. + + Linux: `org.freedesktop.login1.Manager.Suspend(false)`. Windows: + `SetSuspendState(false, ...)`. + + WARNING: this changes the machine's power state. Never call it without an + explicit user confirmation. + + # 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. - * - * WARNING: this changes the machine's power state. Never call it without an - * explicit user confirmation. - * - * @return UDA_OK on success, otherwise a negative status code. +/* + 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`. + + WARNING: this changes the machine's power state. Never call it without an + explicit user confirmation. + + # Safety + + 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. - * - * WARNING: this restarts the machine and unsaved work is lost. Never call it - * without an explicit user confirmation. - * - * @return UDA_OK on success, otherwise a negative status code. +/* + 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. + + WARNING: this restarts the machine and unsaved work is lost. Never call it + without an explicit user confirmation. + + # 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(). - * - * WARNING: this shuts the machine down and unsaved work is lost. Never call it - * without an explicit user confirmation. - * - * @return UDA_OK on success, otherwise a negative status code. +/* + 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()`. + + WARNING: this shuts the machine down and unsaved work is lost. Never call + it without an explicit user confirmation. + + # 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. - * - * The returned string is owned by the library and stays valid until the next - * UDA call on the same thread; copy it if it must outlive that. Returns NULL - * when no failure has been recorded yet. Release the copy with - * `uda_free_string()`. - * - * @return A newly allocated C string, or NULL. +/* + Return the message describing the most recent failure on the calling + thread. + + The returned string is owned by the library and stays valid until the next + UDA call on the same thread; copy it if it must outlive that. Returns NULL + when no failure has been recorded yet. */ const 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. +/* + 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. */ const char *uda_status_message(int32_t status); -/* ------------------------------------------------------------------------- */ -/* System tray */ -/* ------------------------------------------------------------------------- */ - /* - * 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 destroying the menu afterwards leaves the tray working. - * Destroy the menu explicitly only when the icon will never need it again. - * - * 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 and - * still reports its state in later calls. - */ - -/** - * 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. Text longer than 127 - * characters is clamped (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. + Create a tray icon. + + TRAY HANDLES + + 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. + + - 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 destroying the menu afterwards leaves the tray + working. Destroy the menu explicitly only when the icon will never need + it again. + + 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 and + still reports its state in later calls. + + ARGUMENTS + + `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; text longer than 127 characters + is clamped, and the call still succeeds. + + 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. +/* + 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. */ 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. +/* + Replace a tray icon's image from a file or icon-theme name. + + `path` is a null-terminated UTF-8 path. Linux also accepts a freedesktop + icon-theme name here; Windows requires a file path (`.ico`, `.png`, + `.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); -/** - * 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. - * - * @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 the pixels, or NULL when `len` is zero. - * @param len Readable byte count at `data`. - * @return UDA_OK on success, otherwise a negative status code. +/* + 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. + + # Safety + + `data` must not be null and must point to `len` readable bytes. `width` + and `height` must be non-zero and `stride` at least `width * 4`. */ int32_t uda_tray_set_icon_rgba(uint64_t handle, uint32_t width, @@ -584,67 +696,53 @@ int32_t uda_tray_set_icon_rgba(uint64_t handle, const uint8_t *data, size_t len); -/** - * 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. +/* + Show or hide the icon without unregistering it. + + `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. +/* + 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. 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. +/* + Create an empty context 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 point to a writable, non-null `uint64_t` slot. */ int32_t uda_tray_menu_create(uint64_t *out_menu_handle); -/** - * Callback type for a plain text menu row. - * - * @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); +/* + Append a plain text row to a menu. -/** - * Callback type for a checkbox menu row. - * - * @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. - */ -typedef void (*UdaTrayCheckboxCallback)(uint64_t item_id, int32_t checked, void *user_data); + `callback` is invoked on the tray worker thread when the row is activated, + or NULL for a silent row that still renders and still reports its state + in later calls. `user_data` is handed back to the callback untouched and + is never dereferenced by UDA. `label` must be non-blank: a blank label is + rejected with `UDA_ERR_NOT_SUPPORTED` because it would render invisibly. -/** - * 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_NOT_SUPPORTED 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, otherwise a negative status code. + 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 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_text(uint64_t menu_handle, const char *label, @@ -652,32 +750,30 @@ int32_t uda_tray_menu_add_text(uint64_t menu_handle, void *user_data, uint64_t *out_item_id); -/** - * 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. +/* + Append a visual separator to a menu. + + 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. - * - * The row's stored value is inverted *before* `callback` runs, so the `checked` - * argument is the new state and the menu cannot drift out of sync with the shell. - * - * @param menu_handle A handle from uda_tray_menu_create(). - * @param label Row text; a blank label is rejected with - * UDA_ERR_NOT_SUPPORTED. - * @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 silent row. - * @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, otherwise a negative status code. +/* + Append a checkbox row to a menu. + + The row's stored value is inverted *before* `callback` runs, so the + `checked` argument is the new state the shell will render and the menu + cannot drift out of sync with it. `checked` is 0 to start unchecked, any + other value to start checked. `callback` is invoked on the tray worker + thread when the row is toggled, or NULL for a silent row. `label` must be + non-blank: a blank label is rejected with `UDA_ERR_NOT_SUPPORTED`. + + On success `*out_item_id` receives the row's stable, non-zero id. + + # 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, @@ -686,32 +782,23 @@ int32_t uda_tray_menu_add_checkbox(uint64_t menu_handle, void *user_data, uint64_t *out_item_id); -/** - * Attach a menu to a tray icon, replacing any menu set earlier. - * - * The menu handle stays valid after this call: the icon holds its own reference, - * so destroying the menu afterwards is optional and does not clear the rows. - * - * @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. +/* + Attach a menu to a tray icon, replacing any menu set earlier. + + The menu handle stays valid after this call: the icon holds its own + reference, so destroying the menu afterwards is optional and does not + clear the rows. */ int32_t uda_tray_set_menu(uint64_t tray_handle, uint64_t menu_handle); -/** - * Destroy a menu handle. - * - * Safe to call after uda_tray_set_menu(), as documented there. Terminal: the - * handle cannot be reused afterwards. - * - * @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. +/* + Destroy a menu handle. + + Safe to call after `uda_tray_set_menu()`, as documented there. Terminal: + the handle cannot be reused afterwards. Returns + `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live menu in this + process. */ int32_t uda_tray_menu_destroy(uint64_t menu_handle); -#ifdef __cplusplus -} -#endif - -#endif /* UDA_H_ */ +#endif /* UDA_H_ */ diff --git a/scripts/gen-header.sh b/scripts/gen-header.sh new file mode 100755 index 0000000..7d71713 --- /dev/null +++ b/scripts/gen-header.sh @@ -0,0 +1,60 @@ +#!/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 + +# 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 + +installed="$(cbindgen --version | awk '{print $2}')" +if [ "$installed" != "$CBINDGEN_VERSION" ]; then + echo "warning: cbindgen v${installed} installed, but the header is generated" >&2 + echo " with v${CBINDGEN_VERSION}; output can differ between versions." >&2 + echo " Consider: cargo install cbindgen --locked --version ${CBINDGEN_VERSION}" >&2 +fi + +output="$(mktemp)" +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. +perl -pi -e 's/^(#define UDA_[A-Z0-9_]+) (-\d+)$/$1 ($2)/' "$output" + +if [ "${1:-}" = "--check" ]; 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..ef5a685 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:: From 6d36c8fcd96efb770e6d8badf3eb3f5d5377c906 Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Thu, 8 Oct 2026 12:40:47 +0800 Subject: [PATCH 04/17] fix(ffi): cross-review fixes for the generated header Findings from the double-validator cross-review of the cbindgen switch: - P0: the generated header lost the C++ guards - language=c only wraps the declarations in extern "C" when cpp_compat is set. The hand-written header always guaranteed C++ linkability; it is restored. - P0: uda_last_error_message's merged doc kept the wrong half of a self-contradictory old contract. The implementation leaks a fresh allocation per call for the caller to free (take + CString::into_raw), so the doc now says exactly that, including the consume-on-read behaviour, instead of the false "owned by the library" claim. - P1: an empty wallpaper path is now rejected with UDA_ERR_INVALID_ARGUMENT by the FFI layer, honouring what the docs always claimed but the code never implemented (Windows failed with NOT_SUPPORTED, Linux passed the empty string through). Doc updated to scope the file:// URI note to Linux. - P1: the tray icon path doc claimed Windows accepts .png; LoadImageW handles .ico/.cur/.bmp - corrected to the implemented set, and uda_tray_create's doc now mentions that an empty name also selects the library default. - P1/P2: documentation_style is "doxy" again (the explicit "c" setting had downgraded the blocks from /** */ to plain /* */), the preamble no longer presents the two string-returning helpers as status-code functions, uda_wakelock_release documents the 0-handle rejection, the Rust range syntax and a stray markdown bold were rewritten for the C audience, and four stale crate::error constant links in module docs point at crate::abi again. Re-verified after the fixes: 33 defines value-equal, 32 signatures equal, both typedefs and both extern "C" guards present; the header compiles warning-free as C and as C++, and gen-header.sh --check is idempotent. --- CHANGELOG.md | 2 + crates/uda-ffi/cbindgen.toml | 19 +- crates/uda-ffi/src/lib.rs | 47 +- crates/uda-ffi/src/media.rs | 4 +- crates/uda-ffi/src/session.rs | 2 +- crates/uda-ffi/src/wakelocks.rs | 2 +- include/uda.h | 1057 ++++++++++++++++--------------- 7 files changed, 583 insertions(+), 550 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e492da7..43763b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 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. - 对 C 调用者零语义变化:33 个常量值、32 个函数签名与 2 个回调 typedef 逐一比对等价;`header_symbols.py` 与 `pe_exports.py` 的「头文件 ↔ 动态库符号」校验保持不变。 - Zero semantic change for C callers: all 33 constant values, 32 function signatures and both callback typedefs compare equal one by one; the `header_symbols.py` / `pe_exports.py` header-to-library symbol checks are unchanged. + - 两处「文档与实现不符」借此次迁移一并修正:`uda_set_wallpaper` 现在真的以 `UDA_ERR_INVALID_ARGUMENT` 拒绝空路径(原 Rust 文档如此承诺但从未实现);`uda_tray_set_icon_rgba` 的文档不再声称 `data` 可在 `len` 为 0 时为 NULL(实现一贯拒绝 NULL)。 + - Two documentation-versus-implementation mismatches were fixed along the way: `uda_set_wallpaper` now actually rejects an empty path with `UDA_ERR_INVALID_ARGUMENT` (the Rust docs always promised this but it was never implemented), and `uda_tray_set_icon_rgba` no longer documents a NULL `data` for `len == 0` (the implementation has always rejected NULL). ## [v0.2.1] - Honest Theme Reporting & Reasoned Degradation · 2026-10-06 diff --git a/crates/uda-ffi/cbindgen.toml b/crates/uda-ffi/cbindgen.toml index 7b20b66..9f92233 100644 --- a/crates/uda-ffi/cbindgen.toml +++ b/crates/uda-ffi/cbindgen.toml @@ -11,6 +11,11 @@ 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. +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). @@ -23,7 +28,10 @@ usize_is_size_t = true include_guard = "UDA_H_" documentation = true -documentation_style = "c" + +# `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. */""" @@ -42,10 +50,11 @@ header = """/* * on the next regeneration. * * 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()`, and `uda_status_message()` renders any code - * without crossing the boundary again. + * = failure) except `uda_free_string`, which returns nothing, and the two + * string-returning helpers below. Human-readable diagnostics for the most + * recent failure are available from `uda_last_error_message()`, and + * `uda_status_message()` renders any status code without a second FFI + * round-trip. * * Memory ownership * ---------------- diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index 074d320..31619ce 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -87,10 +87,11 @@ pub unsafe extern "C" fn uda_detect_theme(out_theme: *mut i32) -> i32 { /// Set the desktop wallpaper. /// -/// `path` is a null-terminated UTF-8 filesystem path; a `file://` URI is also -/// accepted. An empty path is rejected as an invalid argument rather than -/// being sent to the backend. `fill_mode` is one of the `UDA_FILL_*` codes; -/// anything else is rejected. +/// `path` is a null-terminated UTF-8 filesystem path; on Linux a `file://` +/// URI is also accepted, while Windows requires a plain filesystem path. An +/// empty path is rejected as an invalid argument rather than being sent to +/// the backend. `fill_mode` is one of the `UDA_FILL_*` codes; anything else +/// is rejected. /// /// On failure a negative status code is returned and no wallpaper is changed. /// @@ -108,6 +109,11 @@ pub unsafe extern "C" fn uda_set_wallpaper(path: *const c_char, fill_mode: i32) // 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) }) @@ -202,8 +208,10 @@ pub unsafe extern "C" fn 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, or never issued here). +/// `handle` must be a value returned by `uda_wakelock_acquire()`; 0 is +/// rejected with `UDA_ERR_INVALID_ARGUMENT`, and so is any handle that is +/// not a live lock in this process (already released, or never issued +/// here). #[no_mangle] pub extern "C" fn uda_wakelock_release(handle: u64) -> i32 { util::catch_boundary(|| { @@ -276,10 +284,10 @@ pub unsafe extern "C" fn uda_notify( /// Read the system accent colour as four channels. /// -/// 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. +/// 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 /// @@ -570,9 +578,10 @@ pub unsafe extern "C" fn uda_session_shutdown() -> i32 { /// Return the message describing the most recent failure on the calling /// thread. /// -/// The returned string is owned by the library and stays valid until the next -/// UDA call on the same thread; copy it if it must outlive that. Returns NULL -/// when no failure has been recorded yet. +/// Returns a newly allocated, null-terminated string that the caller must +/// release with `uda_free_string()`, or NULL when no failure has been +/// recorded yet. Reading consumes the message: the next call returns NULL +/// until a new failure is recorded on the same thread. #[no_mangle] pub extern "C" fn uda_last_error_message() -> *const c_char { let Some(message) = util::take_last_message() else { @@ -591,7 +600,7 @@ pub extern "C" fn uda_last_error_message() -> *const c_char { /// 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 +/// not be freed. Useful for rendering a failure without a second FFI /// round-trip. #[no_mangle] pub extern "C" fn uda_status_message(status: i32) -> *const c_char { @@ -661,9 +670,9 @@ pub extern "C" fn uda_status_message(status: i32) -> *const c_char { /// ARGUMENTS /// /// `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; text longer than 127 characters -/// is clamped, and the call still succeeds. +/// on Linux, the window class on Windows); a NULL or empty `name` selects +/// the library default. `tooltip` may be NULL or empty; text longer than +/// 127 characters is clamped, and the call still succeeds. /// /// 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 @@ -726,7 +735,7 @@ pub unsafe extern "C" fn uda_tray_set_tooltip(handle: u64, tooltip: *const c_cha /// Replace a tray icon's image from a file or icon-theme name. /// /// `path` is a null-terminated UTF-8 path. Linux also accepts a freedesktop -/// icon-theme name here; Windows requires a file path (`.ico`, `.png`, +/// icon-theme name here; Windows requires a file path (`.ico`, `.cur`, /// `.bmp`). /// /// # Safety @@ -1051,7 +1060,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] diff --git a/crates/uda-ffi/src/media.rs b/crates/uda-ffi/src/media.rs index 37fb9b6..158dca8 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, MediaManager, MediaMetadata, PlaybackStatus}; diff --git a/crates/uda-ffi/src/session.rs b/crates/uda-ffi/src/session.rs index af20f6d..60d3b3c 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 diff --git a/crates/uda-ffi/src/wakelocks.rs b/crates/uda-ffi/src/wakelocks.rs index 5777c42..5c0e710 100644 --- a/crates/uda-ffi/src/wakelocks.rs +++ b/crates/uda-ffi/src/wakelocks.rs @@ -176,7 +176,7 @@ fn register(handle: WakeLockHandle, entry: LockEntry) -> Result Result<(), Failure> { let raw = handle.raw(); diff --git a/include/uda.h b/include/uda.h index 60e5ec0..99a2230 100644 --- a/include/uda.h +++ b/include/uda.h @@ -12,10 +12,11 @@ * on the next regeneration. * * 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()`, and `uda_status_message()` renders any code - * without crossing the boundary again. + * = failure) except `uda_free_string`, which returns nothing, and the two + * string-returning helpers below. Human-readable diagnostics for the most + * recent failure are available from `uda_last_error_message()`, and + * `uda_status_message()` renders any status code without a second FFI + * round-trip. * * Memory ownership * ---------------- @@ -58,306 +59,313 @@ #include #include -/* - The call succeeded. +/** + * 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). +/** + * 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. +/** + * 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. +/** + * 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 -/* - 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. +/** + * 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. */ #define UDA_SESSION_CAP_MANAGEMENT (1 << 16) -/* - The session can be locked - the only action safe to automate. +/** + * The session can be locked - the only action safe to automate. */ #define UDA_SESSION_CAP_LOCK (1 << 17) -/* - The calling user's session can be ended. +/** + * The calling user's session can be ended. */ #define UDA_SESSION_CAP_LOGOUT (1 << 18) -/* - The machine can be suspended to RAM. +/** + * The machine can be suspended to RAM. */ #define UDA_SESSION_CAP_SUSPEND (1 << 19) -/* - The machine can be hibernated to disk. +/** + * The machine can be hibernated to disk. */ #define UDA_SESSION_CAP_HIBERNATE (1 << 20) -/* - The machine can be rebooted. +/** + * The machine can be rebooted. */ #define UDA_SESSION_CAP_REBOOT (1 << 21) -/* - The machine can be powered off. +/** + * The machine can be powered off. */ #define UDA_SESSION_CAP_SHUTDOWN (1 << 22) -/* - 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. +/** + * 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. */ typedef void (*UdaTrayTextCallback)(uint64_t, void*); -/* - 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. +/** + * 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. */ typedef void (*UdaTrayCheckboxCallback)(uint64_t, int32_t, void*); -/* - Detect the current system colour scheme. - - 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. +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus - # Safety - - `out_theme` must point to a writable, non-null `int32_t` location. +/** + * Detect the current system colour scheme. + * + * 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 point to a writable, non-null `int32_t` location. */ int32_t uda_detect_theme(int32_t *out_theme); -/* - Set the desktop wallpaper. - - `path` is a null-terminated UTF-8 filesystem path; a `file://` URI is also - accepted. An empty path is rejected as an invalid argument rather than - being sent to the backend. `fill_mode` is one of the `UDA_FILL_*` codes; - anything else is rejected. - - On failure a negative status code is returned and no wallpaper is changed. - - # Safety - - `path` must be a valid, readable, null-terminated UTF-8 string. +/** + * Set the desktop wallpaper. + * + * `path` is a null-terminated UTF-8 filesystem path; on Linux a `file://` + * URI is also accepted, while Windows requires a plain filesystem path. An + * empty path is rejected as an invalid argument rather than being sent to + * the backend. `fill_mode` is one of the `UDA_FILL_*` codes; anything else + * is rejected. + * + * On failure a negative status code is returned and no wallpaper is changed. + * + * # Safety + * + * `path` must be a valid, readable, null-terminated UTF-8 string. */ int32_t uda_set_wallpaper(const char *path, int32_t fill_mode); -/* - 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` - check the pointer rather than the status to detect "no - wallpaper". - - # Safety - - `out_path` must point to a writable, non-null pointer location. +/** + * 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` - check the pointer rather than the status to detect "no + * wallpaper". + * + * # 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. - - Passing NULL is a no-op, so callers may free unconditionally. - - # Safety - - `s` must be null or a pointer obtained from a UDA export that hands out - strings. Freeing a pointer owned by the caller is undefined behaviour. +/** + * Release a string previously returned by this library. + * + * Passing NULL is a no-op, so callers may free unconditionally. + * + * # Safety + * + * `s` must be null or a pointer obtained from a UDA export that hands out + * strings. Freeing a pointer owned by the caller is undefined behaviour. */ 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. - - # Safety - - `out_handle` must point to a writable, non-null `uint64_t` location and - `reason` must be a readable, null-terminated UTF-8 string. +/** + * 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. + * + * # 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, or never issued here). +/** + * Release a wake lock previously obtained from `uda_wakelock_acquire()`. + * + * `handle` must be a value returned by `uda_wakelock_acquire()`; 0 is + * rejected with `UDA_ERR_INVALID_ARGUMENT`, and so is any handle that is + * not a live lock in this process (already released, or never issued + * here). */ 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. Use `WindowsNotificationManager::availability()` to - probe further. - - 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. +/** + * 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. Use `WindowsNotificationManager::availability()` to + * probe further. + * + * 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, @@ -366,48 +374,48 @@ int32_t uda_notify(const char *app_name, const char *actions, uint32_t *out_id); -/* - Read the system accent colour as four channels. - - 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. - - # Safety - - `out_rgba` must point to four writable `uint8_t` values. +/** + * Read the system accent colour as four channels. + * + * 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); -/* - 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 "no player" when - none 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, which lets a binding - skip it. The artist list is already joined with ", " when the player - publishes several artists. - - `out_duration_ms` receives the track length in milliseconds, or 0 when - unknown (a live stream). `out_position_ms` is optional: pass NULL to skip - it; it receives the playback position in milliseconds, or 0 when the - backend cannot report 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`. +/** + * 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 "no player" when + * none 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, which lets a binding + * skip it. The artist list is already joined with ", " when the player + * publishes several artists. + * + * `out_duration_ms` receives the track length in milliseconds, or 0 when + * unknown (a live stream). `out_position_ms` is optional: pass NULL to skip + * it; it receives the playback position in milliseconds, or 0 when the + * backend cannot report 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, @@ -415,279 +423,280 @@ int32_t uda_media_get_metadata(char **out_title, uint64_t *out_duration_ms, uint64_t *out_position_ms); -/* - 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. - - # Safety - - `out_status` must point to a writable, non-null `int32_t` location. +/** + * 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. + * + * # Safety + * + * `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. - - 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. - - # Safety - - This function takes no pointers; there is nothing to validate. +/** + * 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. + * + * 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. + * + * # 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 session backend exists on this target". - - The query is static and side-effect-free - it never touches the machine's - power state - so a host may call it freely to decide which menu entries to - draw, and *must* call it before drawing one that could shut the machine - down. - - A set bit means "the code path exists", not "the account is allowed": a - machine with hibernation switched off still reports - `UDA_SESSION_CAP_HIBERNATE`, and the attempt then fails with - `UDA_ERR_NOT_SUPPORTED`. Likewise, Windows reboot and shutdown need the - SeShutdownPrivilege, which is a runtime answer. - - # Safety - - `out_capabilities` must point to a writable, non-null `uint32_t` location. +/** + * 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 session backend exists on this target". + * + * The query is static and side-effect-free - it never touches the machine's + * power state - so a host may call it freely to decide which menu entries to + * draw, and *must* call it before drawing one that could shut the machine + * down. + * + * A set bit means "the code path exists", not "the account is allowed": a + * machine with hibernation switched off still reports + * `UDA_SESSION_CAP_HIBERNATE`, and the attempt then fails with + * `UDA_ERR_NOT_SUPPORTED`. Likewise, Windows reboot and shutdown need the + * SeShutdownPrivilege, which is a runtime answer. + * + * # Safety + * + * `out_capabilities` must point to a writable, non-null `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()`. - - 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 must be gated behind an explicit user - confirmation. - - # Safety - - This function takes no pointers; there is nothing to validate. +/** + * Lock the session. + * + * Linux: `org.freedesktop.ScreenSaver.Lock()` on the session bus, falling + * back to `loginctl lock-session`. Windows: `LockWorkStation()`. + * + * 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 must be gated behind an explicit user + * confirmation. + * + * # 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)`. - - 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 - - This function takes no pointers; there is nothing to validate. +/** + * 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)`. + * + * 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 + * + * This function takes no pointers; there is nothing to validate. */ int32_t uda_session_logout(void); -/* - Suspend the machine to RAM. - - Linux: `org.freedesktop.login1.Manager.Suspend(false)`. Windows: - `SetSuspendState(false, ...)`. - - WARNING: this changes the machine's power state. Never call it without an - explicit user confirmation. - - # Safety - - This function takes no pointers; there is nothing to validate. +/** + * Suspend the machine to RAM. + * + * Linux: `org.freedesktop.login1.Manager.Suspend(false)`. Windows: + * `SetSuspendState(false, ...)`. + * + * WARNING: this changes the machine's power state. Never call it without an + * explicit user confirmation. + * + * # 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`. - - WARNING: this changes the machine's power state. Never call it without an - explicit user confirmation. - - # Safety - - This function takes no pointers; there is nothing to validate. +/** + * 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`. + * + * WARNING: this changes the machine's power state. Never call it without an + * explicit user confirmation. + * + * # Safety + * + * 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. - - WARNING: this restarts the machine and unsaved work is lost. Never call it - without an explicit user confirmation. - - # Safety - - This function takes no pointers; there is nothing to validate. +/** + * 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. + * + * WARNING: this restarts the machine and unsaved work is lost. Never call it + * without an explicit user confirmation. + * + * # 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()`. - - WARNING: this shuts the machine down and unsaved work is lost. Never call - it without an explicit user confirmation. - - # Safety - - This function takes no pointers; there is nothing to validate. +/** + * 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()`. + * + * WARNING: this shuts the machine down and unsaved work is lost. Never call + * it without an explicit user confirmation. + * + * # 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. - - The returned string is owned by the library and stays valid until the next - UDA call on the same thread; copy it if it must outlive that. Returns NULL - when no failure has been recorded yet. +/** + * Return the message describing the most recent failure on the calling + * thread. + * + * Returns a newly allocated, null-terminated string that the caller must + * release with `uda_free_string()`, or NULL when no failure has been + * recorded yet. Reading consumes the message: the next call returns NULL + * until a new failure is recorded on the same thread. */ const 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. +/** + * 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. */ const char *uda_status_message(int32_t status); -/* - Create a tray icon. - - TRAY HANDLES - - 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. - - - 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 destroying the menu afterwards leaves the tray - working. Destroy the menu explicitly only when the icon will never need - it again. - - 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 and - still reports its state in later calls. - - ARGUMENTS - - `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; text longer than 127 characters - is clamped, and the call still succeeds. - - 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. +/** + * Create a tray icon. + * + * TRAY HANDLES + * + * 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. + * + * - 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 destroying the menu afterwards leaves the tray + * working. Destroy the menu explicitly only when the icon will never need + * it again. + * + * 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 and + * still reports its state in later calls. + * + * ARGUMENTS + * + * `name` is the application name used for registration (the D-Bus bus name + * on Linux, the window class on Windows); a NULL or empty `name` selects + * the library default. `tooltip` may be NULL or empty; text longer than + * 127 characters is clamped, and the call still succeeds. + * + * 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. - - `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. +/** + * 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. */ 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. - - `path` is a null-terminated UTF-8 path. Linux also accepts a freedesktop - icon-theme name here; Windows requires a file path (`.ico`, `.png`, - `.bmp`). - - # Safety - - `path` must be a readable, null-terminated UTF-8 string. +/** + * Replace a tray icon's image from a file or icon-theme name. + * + * `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); -/* - 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. - - # Safety - - `data` must not be null and must point to `len` readable bytes. `width` - and `height` must be non-zero and `stride` at least `width * 4`. +/** + * 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. + * + * # Safety + * + * `data` must not be null and must point to `len` readable bytes. `width` + * and `height` must be non-zero and `stride` at least `width * 4`. */ int32_t uda_tray_set_icon_rgba(uint64_t handle, uint32_t width, @@ -696,53 +705,53 @@ int32_t uda_tray_set_icon_rgba(uint64_t handle, const uint8_t *data, size_t len); -/* - Show or hide the icon without unregistering it. - - `visible` is a C boolean: 0 hides, any other value shows. +/** + * Show or hide the icon without unregistering it. + * + * `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. Returns - `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live tray icon in - this process. +/** + * 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. 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. - - 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 point to a writable, non-null `uint64_t` slot. +/** + * Create an empty context 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 point to a writable, non-null `uint64_t` slot. */ int32_t uda_tray_menu_create(uint64_t *out_menu_handle); -/* - Append a plain text row to a menu. - - `callback` is invoked on the tray worker thread when the row is activated, - or NULL for a silent row that still renders and still reports its state - in later calls. `user_data` is handed back to the callback untouched and - is never dereferenced by UDA. `label` must be non-blank: a blank label is - rejected with `UDA_ERR_NOT_SUPPORTED` because it would render invisibly. - - 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 point to a writable, non-null `uint64_t` slot and - `label` must be a readable, null-terminated UTF-8 string. +/** + * Append a plain text row to a menu. + * + * `callback` is invoked on the tray worker thread when the row is activated, + * or NULL for a silent row that still renders and still reports its state + * in later calls. `user_data` is handed back to the callback untouched and + * is never dereferenced by UDA. `label` must be non-blank: a blank label is + * rejected with `UDA_ERR_NOT_SUPPORTED` because it would render invisibly. + * + * 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 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_text(uint64_t menu_handle, const char *label, @@ -750,30 +759,30 @@ int32_t uda_tray_menu_add_text(uint64_t menu_handle, void *user_data, uint64_t *out_item_id); -/* - Append a visual separator to a menu. - - A separator has no label, no callback and no id, so there is no - out-parameter. +/** + * Append a visual separator to a menu. + * + * 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. - - The row's stored value is inverted *before* `callback` runs, so the - `checked` argument is the new state the shell will render and the menu - cannot drift out of sync with it. `checked` is 0 to start unchecked, any - other value to start checked. `callback` is invoked on the tray worker - thread when the row is toggled, or NULL for a silent row. `label` must be - non-blank: a blank label is rejected with `UDA_ERR_NOT_SUPPORTED`. - - On success `*out_item_id` receives the row's stable, non-zero id. - - # 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. +/** + * Append a checkbox row to a menu. + * + * The row's stored value is inverted *before* `callback` runs, so the + * `checked` argument is the new state the shell will render and the menu + * cannot drift out of sync with it. `checked` is 0 to start unchecked, any + * other value to start checked. `callback` is invoked on the tray worker + * thread when the row is toggled, or NULL for a silent row. `label` must be + * non-blank: a blank label is rejected with `UDA_ERR_NOT_SUPPORTED`. + * + * On success `*out_item_id` receives the row's stable, non-zero id. + * + * # 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, @@ -782,23 +791,27 @@ int32_t uda_tray_menu_add_checkbox(uint64_t menu_handle, void *user_data, uint64_t *out_item_id); -/* - Attach a menu to a tray icon, replacing any menu set earlier. - - The menu handle stays valid after this call: the icon holds its own - reference, so destroying the menu afterwards is optional and does not - clear the rows. +/** + * Attach a menu to a tray icon, replacing any menu set earlier. + * + * The menu handle stays valid after this call: the icon holds its own + * reference, so destroying the menu afterwards is optional and does not + * clear the rows. */ int32_t uda_tray_set_menu(uint64_t tray_handle, uint64_t menu_handle); -/* - Destroy a menu handle. - - Safe to call after `uda_tray_set_menu()`, as documented there. Terminal: - the handle cannot be reused afterwards. Returns - `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live menu in this - process. +/** + * Destroy a menu handle. + * + * Safe to call after `uda_tray_set_menu()`, as documented there. Terminal: + * the handle cannot be reused afterwards. Returns + * `UDA_ERR_INVALID_ARGUMENT` when the handle is not a live menu in this + * process. */ int32_t uda_tray_menu_destroy(uint64_t menu_handle); +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + #endif /* UDA_H_ */ From 9e450703beec2cbcd74eaf5eeb8a8fcac96b66cf Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Thu, 8 Oct 2026 12:48:33 +0800 Subject: [PATCH 05/17] docs(ffi): note the const cast for freeing the last-error message Round-2 review nit: uda_last_error_message returns const char * while uda_free_string takes char *, and the regenerated doc now (correctly) makes the free obligation explicit - tell the C caller to cast away const at the call, matching the old header's copy-then-free intent without resurrecting its false ownership claim. --- crates/uda-ffi/src/lib.rs | 7 ++++--- include/uda.h | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index 31619ce..a5867fe 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -579,9 +579,10 @@ pub unsafe extern "C" fn uda_session_shutdown() -> i32 { /// thread. /// /// Returns a newly allocated, null-terminated string that the caller must -/// release with `uda_free_string()`, or NULL when no failure has been -/// recorded yet. Reading consumes the message: the next call returns NULL -/// until a new failure is recorded on the same thread. +/// release with `uda_free_string()` (cast away `const` at the call), or NULL +/// when no failure has been recorded yet. Reading consumes the message: the +/// next call returns NULL until a new failure is recorded on the same +/// thread. #[no_mangle] pub extern "C" fn uda_last_error_message() -> *const c_char { let Some(message) = util::take_last_message() else { diff --git a/include/uda.h b/include/uda.h index 99a2230..0075a82 100644 --- a/include/uda.h +++ b/include/uda.h @@ -585,9 +585,10 @@ int32_t uda_session_shutdown(void); * thread. * * Returns a newly allocated, null-terminated string that the caller must - * release with `uda_free_string()`, or NULL when no failure has been - * recorded yet. Reading consumes the message: the next call returns NULL - * until a new failure is recorded on the same thread. + * release with `uda_free_string()` (cast away `const` at the call), or NULL + * when no failure has been recorded yet. Reading consumes the message: the + * next call returns NULL until a new failure is recorded on the same + * thread. */ const char *uda_last_error_message(void); From e31a1efe2ef4e2cb40cb526371a6206c1b82523e Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Thu, 8 Oct 2026 13:19:19 +0800 Subject: [PATCH 06/17] fix(ffi): simplifier + review round: script hardening and media contract Findings from the code-simplifier and code-review pass over the branch: - gen-header.sh now validates arguments (a typo like --chekc used to fall through to rewrite mode and silently overwrite include/uda.h), parses the mode once, and fails with an actionable message when cargo install succeeds but CARGO_HOME/bin is not on PATH. - uda_media_send_command's merged doc claimed a refusing player reports UDA_ERR_NOT_SUPPORTED, but the backends map refusal to CommandFailed (-> UDA_ERR_INTERNAL); only "no player" is -2. The old hand-written header carried the same false claim. The header now only promises what the implementation guarantees: no-player is -2 and any non-OK status means "not delivered". (The deeper three-way disagreement - spec says refusal is UDA_OK, backends return -5 - is left for a maintainer decision; the header no longer takes a side.) - uda_media_get_metadata now implements the documented NULL contract: unpublished fields and "no player" write NULL (plus zero durations) instead of non-NULL pointers to empty strings. The old unwrap_or_default defeated the backends' Ok(None) normalization and contradicted docs/internals/media_specs.md and the Python/Node binding comments, which all describe NULL. A unit test pins the helper's behaviour. - util.rs imports UDA_OK alongside UDA_ERR_PANIC instead of mixing an import with a fully qualified use of its sibling. All gates re-run: clippy -D warnings and fmt clean on x86_64-unknown-linux-gnu, gen-header.sh --check green, generated header in sync. --- CHANGELOG.md | 4 +-- crates/uda-ffi/src/lib.rs | 62 ++++++++++++++++++++++++++++++------- crates/uda-ffi/src/media.rs | 6 ++-- crates/uda-ffi/src/util.rs | 4 +-- include/uda.h | 7 ++--- scripts/gen-header.sh | 34 +++++++++++++++++++- 6 files changed, 94 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43763b9..49816f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,8 +21,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 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. - 对 C 调用者零语义变化:33 个常量值、32 个函数签名与 2 个回调 typedef 逐一比对等价;`header_symbols.py` 与 `pe_exports.py` 的「头文件 ↔ 动态库符号」校验保持不变。 - Zero semantic change for C callers: all 33 constant values, 32 function signatures and both callback typedefs compare equal one by one; the `header_symbols.py` / `pe_exports.py` header-to-library symbol checks are unchanged. - - 两处「文档与实现不符」借此次迁移一并修正:`uda_set_wallpaper` 现在真的以 `UDA_ERR_INVALID_ARGUMENT` 拒绝空路径(原 Rust 文档如此承诺但从未实现);`uda_tray_set_icon_rgba` 的文档不再声称 `data` 可在 `len` 为 0 时为 NULL(实现一贯拒绝 NULL)。 - - Two documentation-versus-implementation mismatches were fixed along the way: `uda_set_wallpaper` now actually rejects an empty path with `UDA_ERR_INVALID_ARGUMENT` (the Rust docs always promised this but it was never implemented), and `uda_tray_set_icon_rgba` no longer documents a NULL `data` for `len == 0` (the implementation has always rejected NULL). + - 三处「文档与实现不符」借此次迁移一并修正:`uda_set_wallpaper` 现在真的以 `UDA_ERR_INVALID_ARGUMENT` 拒绝空路径(原 Rust 文档如此承诺但从未实现);`uda_tray_set_icon_rgba` 的文档不再声称 `data` 可在 `len` 为 0 时为 NULL(实现一贯拒绝 NULL);`uda_media_get_metadata` 现按文档为未发布字段与「无播放器」写回 NULL(此前写回指向空字符串的非 NULL 指针,与 `docs/internals/media_specs.md` 及 Python/Node 绑定的注释相悖)。 + - Three documentation-versus-implementation mismatches were fixed along the way: `uda_set_wallpaper` now actually rejects an empty path with `UDA_ERR_INVALID_ARGUMENT` (the Rust docs always promised this but it was never implemented), `uda_tray_set_icon_rgba` no longer documents a NULL `data` for `len == 0` (the implementation has always rejected NULL), and `uda_media_get_metadata` now writes NULL for unpublished fields and for "no player" as documented (it previously wrote non-NULL pointers to empty strings, contradicting `docs/internals/media_specs.md` and the Python/Node binding comments). ## [v0.2.1] - Honest Theme Reporting & Reasoned Degradation · 2026-10-06 diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index a5867fe..b40a454 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -364,11 +364,29 @@ 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); + let metadata = media::active_metadata()?; + + // 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, artist, album, duration_ms, position_ms) = match metadata { + Some(ref metadata) => ( + c_string_or_null(Some(&metadata.title)), + c_string_or_null(Some(&metadata.artist)), + c_string_or_null(Some(&metadata.album)), + metadata.duration_ms.unwrap_or(0), + metadata.position_ms.unwrap_or(0), + ), + None => ( + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + 0, + 0, + ), + }; // SAFETY: all four pointers were validated non-null and writable above; // `out_position_ms` is checked before the optional write. @@ -376,9 +394,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(()) @@ -419,10 +437,9 @@ pub unsafe extern "C" fn uda_media_get_status(out_status: *mut i32) -> i32 { /// `UDA_MEDIA_CMD_STOP`. An unrecognised 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. +/// A machine with no player running reports `UDA_ERR_NOT_SUPPORTED`, and any +/// non-`UDA_OK` status means the command was not delivered, so a caller can +/// tell "not delivered" from "delivered" without inspecting the player. /// /// # Safety /// @@ -954,6 +971,18 @@ fn owned_or_empty(pointer: *const c_char, parameter: &str) -> Result) -> *mut c_char { + match text { + Some(text) if !text.is_empty() => util::c_string_from(text), + _ => 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. @@ -998,6 +1027,17 @@ mod tests { use super::*; use std::ffi::CString; + #[test] + fn metadata_fields_publish_null_for_unpublished_strings() { + assert!(c_string_or_null(None).is_null()); + assert!(c_string_or_null(Some("")).is_null()); + let pointer = c_string_or_null(Some("/music/track.flac")); + assert!(!pointer.is_null()); + // SAFETY: the pointer came from `c_string_from` in this test and has + // not been handed to anyone else. + unsafe { util::free_c_string(pointer) }; + } + #[test] fn fill_mode_codes_are_accepted_and_rejected() { assert!(fill_mode_from_c(UDA_FILL_CROP).is_ok()); diff --git a/crates/uda-ffi/src/media.rs b/crates/uda-ffi/src/media.rs index 158dca8..bc30c60 100644 --- a/crates/uda-ffi/src/media.rs +++ b/crates/uda-ffi/src/media.rs @@ -23,9 +23,9 @@ //! may be null when the corresponding field is empty, which is the normal case //! for a player that publishes only a title. //! -//! A refused command (an app that disables `Next`, for example) returns -//! [`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". +//! A machine with nobody to command reports +//! [`UDA_ERR_NOT_SUPPORTED`](crate::abi::UDA_ERR_NOT_SUPPORTED); any other +//! non-`UDA_OK` status means the command was not delivered. use uda_core::media::{MediaCommand, MediaManager, MediaMetadata, PlaybackStatus}; diff --git a/crates/uda-ffi/src/util.rs b/crates/uda-ffi/src/util.rs index e624f31..056373e 100644 --- a/crates/uda-ffi/src/util.rs +++ b/crates/uda-ffi/src/util.rs @@ -19,7 +19,7 @@ use std::cell::RefCell; use std::os::raw::c_char; -use crate::abi::UDA_ERR_PANIC; +use crate::abi::{UDA_ERR_PANIC, UDA_OK}; use crate::error::{Failure, UdaStatus}; thread_local! { @@ -120,7 +120,7 @@ where let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)); match outcome { - Ok(Ok(())) => crate::abi::UDA_OK, + Ok(Ok(())) => UDA_OK, Ok(Err(failure)) => { set_last_message(&failure.message()); failure.status() diff --git a/include/uda.h b/include/uda.h index 0075a82..728b73e 100644 --- a/include/uda.h +++ b/include/uda.h @@ -446,10 +446,9 @@ int32_t uda_media_get_status(int32_t *out_status); * `UDA_MEDIA_CMD_STOP`. An unrecognised 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. + * A machine with no player running reports `UDA_ERR_NOT_SUPPORTED`, and any + * non-`UDA_OK` status means the command was not delivered, so a caller can + * tell "not delivered" from "delivered" without inspecting the player. * * # Safety * diff --git a/scripts/gen-header.sh b/scripts/gen-header.sh index 7d71713..b2bcaa6 100755 --- a/scripts/gen-header.sh +++ b/scripts/gen-header.sh @@ -14,6 +14,29 @@ # 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. @@ -28,6 +51,15 @@ if ! command -v cbindgen >/dev/null 2>&1; then 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 "warning: cbindgen v${installed} installed, but the header is generated" >&2 @@ -46,7 +78,7 @@ trap 'rm -f "$output"' EXIT # negative literals in parentheses the way the header always has. perl -pi -e 's/^(#define UDA_[A-Z0-9_]+) (-\d+)$/$1 ($2)/' "$output" -if [ "${1:-}" = "--check" ]; then +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 From 3e1ad4794a4575c2cfb3cc15b67b7bed63357f9f Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Thu, 8 Oct 2026 13:32:52 +0800 Subject: [PATCH 07/17] docs(ffi): cross-review round 3 - consistency fixes in header and specs Six minor findings from the two code-review validators, all verified against the code before fixing: - The metadata export's doc now also states the negative-status case (no media backend at all), matching the asymmetry with uda_media_get_status's doc. - The preamble's memory-ownership rule now carves out uda_status_message's static return (must not be freed), and its thread-safety rule now names the tray handle registry alongside the wake-lock registry; the lib.rs crate doc carries the same two fixes. - "A handle is single-use" in the tray prose read as if a handle allowed only one call; it means destruction is one-shot. Reworded to "can be destroyed exactly once". - error.rs's module doc still said the last-error message is available "until the next UDA call"; reading it actually consumes it (see take_last_message). Reworded to the consume-on-read contract. - media.rs's module doc said metadata crosses as "three strings plus an out duration"; the export carries a position slot too. - docs/internals/media_specs.md: the metadata row showed the old 4-parameter signature and claimed the three string pointers accept NULL to skip fields - the export has always rejected NULL there (only out_position_ms is optional). The row now matches the shipped contract; the send_command row no longer claims a refused command returns UDA_OK (the implementation maps refusal to a negative status; the spec no longer takes a side, matching the header). Gates re-run: clippy -D warnings and fmt clean on x86_64-unknown-linux-gnu, regenerated include/uda.h committed, gen-header.sh --check green. --- crates/uda-ffi/cbindgen.toml | 12 +++++++----- crates/uda-ffi/src/error.rs | 3 ++- crates/uda-ffi/src/lib.rs | 19 +++++++++++-------- crates/uda-ffi/src/media.rs | 4 ++-- docs/internals/media_specs.md | 6 +++--- include/uda.h | 24 ++++++++++++++---------- 6 files changed, 39 insertions(+), 29 deletions(-) diff --git a/crates/uda-ffi/cbindgen.toml b/crates/uda-ffi/cbindgen.toml index 9f92233..a68f3d4 100644 --- a/crates/uda-ffi/cbindgen.toml +++ b/crates/uda-ffi/cbindgen.toml @@ -61,6 +61,8 @@ header = """/* * - 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. @@ -75,11 +77,11 @@ header = """/* * * 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 * ------------- diff --git a/crates/uda-ffi/src/error.rs b/crates/uda-ffi/src/error.rs index 3cf150c..9c9c331 100644 --- a/crates/uda-ffi/src/error.rs +++ b/crates/uda-ffi/src/error.rs @@ -13,7 +13,8 @@ //! | `-6` | [`UDA_ERR_PANIC`] | A panic was caught at the FFI boundary | //! //! Human-readable diagnostics for the failing call are available through -//! `uda_last_error_message()` until the next UDA call on the same thread. +//! `uda_last_error_message()`. 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; diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index b40a454..062fdfc 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -17,7 +17,8 @@ //! # Memory ownership //! //! - Strings **returned** by UDA are allocated by Rust and must be freed with -//! [`uda_free_string`]. +//! [`uda_free_string`]. The one exception is [`status_message`], whose +//! static return must **not** be freed. //! - Strings **passed in** are borrowed for the duration of the call only. //! - Wake-lock handles are `uint64_t` values owned by this process; release each //! exactly once with [`uda_wakelock_release`]. @@ -32,8 +33,8 @@ //! # 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; @@ -325,7 +326,9 @@ pub unsafe extern "C" fn uda_get_accent_color(out_rgba: *mut u8) -> i32 { /// none 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. +/// therefore renders as empty rather than as a failure. If the platform has +/// no media backend at all, a negative status code is returned instead and +/// the out-parameters are left untouched. /// /// 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 @@ -654,10 +657,10 @@ pub extern "C" fn uda_status_message(status: i32) -> *const c_char { /// valid in another process: each handle indexes a table owned by the shared /// library. /// -/// - 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. +/// - A handle can be destroyed exactly once. 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 diff --git a/crates/uda-ffi/src/media.rs b/crates/uda-ffi/src/media.rs index bc30c60..b583532 100644 --- a/crates/uda-ffi/src/media.rs +++ b/crates/uda-ffi/src/media.rs @@ -4,8 +4,8 @@ //! [`MediaManager`](uda_core::media::MediaManager) trait does: read what is //! playing, read the playback status, and send a transport command. The status is //! an `int32_t` code (see [`PlaybackStatus::code`](uda_core::media::PlaybackStatus)); -//! the metadata crosses the boundary as three separately-owned strings plus an -//! out duration, because a C caller cannot allocate a Rust struct. +//! the metadata crosses the boundary as three separately-owned strings plus out +//! duration and position slots, because a C caller cannot allocate a Rust struct. //! //! # Why an out-code instead of an out-pointer for the status //! diff --git a/docs/internals/media_specs.md b/docs/internals/media_specs.md index 5fa22fa..72aec9a 100644 --- a/docs/internals/media_specs.md +++ b/docs/internals/media_specs.md @@ -139,10 +139,10 @@ let session = manager.GetCurrentSession()?; // Option Date: Thu, 8 Oct 2026 13:37:31 +0800 Subject: [PATCH 08/17] docs: two residual consistency nits from review round 3 - The tray section's Rust-facing comment still said "A handle is single-use" after the header prose was reworded; use the same "destroyed exactly once" terminology. - media_specs.md 3.4 still asserted the refusal maps to Ok(()) and HRESULT failures to UdaError::Internal, both contradicting the shipped mapping (false and HRESULT failures alike surface as CommandFailed) and the neutral table row above it. State the observed behaviour and mark the refusal-is-success question as the deferred design decision it is, matching the header's neutrality. --- crates/uda-ffi/src/lib.rs | 6 +++--- docs/internals/media_specs.md | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index 062fdfc..593c3f4 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -644,9 +644,9 @@ pub extern "C" fn uda_status_message(status: i32) -> *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. /// Create a tray icon. /// diff --git a/docs/internals/media_specs.md b/docs/internals/media_specs.md index 72aec9a..b314caa 100644 --- a/docs/internals/media_specs.md +++ b/docs/internals/media_specs.md @@ -127,8 +127,10 @@ let session = manager.GetCurrentSession()?; // Option Date: Thu, 8 Oct 2026 23:13:45 +0800 Subject: [PATCH 09/17] fix(ffi): keep published-empty metadata fields distinguishable from unpublished Addresses the follow-up review on PR #7: c_string_or_null folded Some("") and None into the same NULL, so a player publishing an empty title became indistinguishable from one that never published it. MediaMetadata's string fields are now Option: None means the player does not publish the field (NULL on the wire), Some carries the published value - including an empty one - through as a real C string. The Windows backend maps an empty SMTC read to None because the protocol cannot tell an absent property from an empty one, which is now documented on the struct. --- CHANGELOG.md | 4 +- crates/uda-core/src/media.rs | 26 ++++++++----- crates/uda-ffi/src/lib.rs | 41 +++++++++++++------- crates/uda-ffi/src/media.rs | 4 +- crates/uda-platform-linux/src/media.rs | 49 ++++++++++++++---------- crates/uda-platform-windows/src/media.rs | 27 +++++++++---- 6 files changed, 95 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 49816f0..78ce715 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,8 +21,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 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. - 对 C 调用者零语义变化:33 个常量值、32 个函数签名与 2 个回调 typedef 逐一比对等价;`header_symbols.py` 与 `pe_exports.py` 的「头文件 ↔ 动态库符号」校验保持不变。 - Zero semantic change for C callers: all 33 constant values, 32 function signatures and both callback typedefs compare equal one by one; the `header_symbols.py` / `pe_exports.py` header-to-library symbol checks are unchanged. - - 三处「文档与实现不符」借此次迁移一并修正:`uda_set_wallpaper` 现在真的以 `UDA_ERR_INVALID_ARGUMENT` 拒绝空路径(原 Rust 文档如此承诺但从未实现);`uda_tray_set_icon_rgba` 的文档不再声称 `data` 可在 `len` 为 0 时为 NULL(实现一贯拒绝 NULL);`uda_media_get_metadata` 现按文档为未发布字段与「无播放器」写回 NULL(此前写回指向空字符串的非 NULL 指针,与 `docs/internals/media_specs.md` 及 Python/Node 绑定的注释相悖)。 - - Three documentation-versus-implementation mismatches were fixed along the way: `uda_set_wallpaper` now actually rejects an empty path with `UDA_ERR_INVALID_ARGUMENT` (the Rust docs always promised this but it was never implemented), `uda_tray_set_icon_rgba` no longer documents a NULL `data` for `len == 0` (the implementation has always rejected NULL), and `uda_media_get_metadata` now writes NULL for unpublished fields and for "no player" as documented (it previously wrote non-NULL pointers to empty strings, contradicting `docs/internals/media_specs.md` and the Python/Node binding comments). + - 三处「文档与实现不符」借此次迁移一并修正:`uda_set_wallpaper` 现在真的以 `UDA_ERR_INVALID_ARGUMENT` 拒绝空路径(原 Rust 文档如此承诺但从未实现);`uda_tray_set_icon_rgba` 的文档不再声称 `data` 可在 `len` 为 0 时为 NULL(实现一贯拒绝 NULL);`uda_media_get_metadata` 现按文档为未发布字段与「无播放器」写回 NULL(此前写回指向空字符串的非 NULL 指针,与 `docs/internals/media_specs.md` 及 Python/Node 绑定的注释相悖)。同时 `MediaMetadata` 的字符串字段改为 `Option`,使「已发布但为空」在 C-ABI 上保持为空字符串、与「未发布」(NULL)可区分。 + - Three documentation-versus-implementation mismatches were fixed along the way: `uda_set_wallpaper` now actually rejects an empty path with `UDA_ERR_INVALID_ARGUMENT` (the Rust docs always promised this but it was never implemented), `uda_tray_set_icon_rgba` no longer documents a NULL `data` for `len == 0` (the implementation has always rejected NULL), and `uda_media_get_metadata` now writes NULL for unpublished fields and for "no player" as documented (it previously wrote non-NULL pointers to empty strings, contradicting `docs/internals/media_specs.md` and the Python/Node binding comments). `MediaMetadata`'s string fields became `Option`, so a field published as an empty string stays an empty C string and remains distinguishable from "unpublished" (NULL). ## [v0.2.1] - Honest Theme Reporting & Reasoned Degradation · 2026-10-06 diff --git a/crates/uda-core/src/media.rs b/crates/uda-core/src/media.rs index f90a4cd..4544d98 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, @@ -79,9 +85,9 @@ impl MediaMetadata { /// player answered but said nothing" 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() } @@ -225,7 +231,7 @@ 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()); diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index 593c3f4..1e08d62 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -334,8 +334,9 @@ pub unsafe extern "C" fn uda_get_accent_color(out_rgba: *mut u8) -> i32 { /// 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, which lets a binding -/// skip it. The artist list is already joined with ", " when the player -/// publishes several artists. +/// skip it, while a field published as an empty string stays an empty string - +/// the two cases remain distinguishable. The artist list is already joined +/// with ", " when the player publishes several artists. /// /// `out_duration_ms` receives the track length in milliseconds, or 0 when /// unknown (a live stream). `out_position_ms` is optional: pass NULL to skip @@ -376,9 +377,9 @@ pub unsafe extern "C" fn uda_media_get_metadata( // renders as empty instead of as a failure. let (title, artist, album, duration_ms, position_ms) = match metadata { Some(ref metadata) => ( - c_string_or_null(Some(&metadata.title)), - c_string_or_null(Some(&metadata.artist)), - c_string_or_null(Some(&metadata.album)), + c_string_or_null(metadata.title.as_deref()), + c_string_or_null(metadata.artist.as_deref()), + c_string_or_null(metadata.album.as_deref()), metadata.duration_ms.unwrap_or(0), metadata.position_ms.unwrap_or(0), ), @@ -976,13 +977,13 @@ fn owned_or_empty(pointer: *const c_char, parameter: &str) -> Result) -> *mut c_char { match text { - Some(text) if !text.is_empty() => util::c_string_from(text), - _ => std::ptr::null_mut(), + Some(text) => util::c_string_from(text), + None => std::ptr::null_mut(), } } @@ -1031,13 +1032,25 @@ mod tests { use std::ffi::CString; #[test] - fn metadata_fields_publish_null_for_unpublished_strings() { + fn metadata_fields_distinguish_published_empty_from_unpublished() { + // Unpublished -> NULL, the documented "skip this field" answer. assert!(c_string_or_null(None).is_null()); - assert!(c_string_or_null(Some("")).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_from` 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. let pointer = c_string_or_null(Some("/music/track.flac")); assert!(!pointer.is_null()); - // SAFETY: the pointer came from `c_string_from` in this test and has - // not been handed to anyone else. + // SAFETY: same ownership pattern as above. unsafe { util::free_c_string(pointer) }; } diff --git a/crates/uda-ffi/src/media.rs b/crates/uda-ffi/src/media.rs index b583532..3864acb 100644 --- a/crates/uda-ffi/src/media.rs +++ b/crates/uda-ffi/src/media.rs @@ -20,8 +20,8 @@ //! //! The three strings written by [`uda_media_get_metadata`] are allocated by Rust //! and must be released with [`uda_free_string`](crate::uda_free_string); they -//! may be null when the corresponding field is empty, which is the normal case -//! for a player that publishes only a title. +//! are null when the player does not publish the corresponding field, which is +//! the normal case for a player that publishes only a title. //! //! A machine with nobody to command reports //! [`UDA_ERR_NOT_SUPPORTED`](crate::abi::UDA_ERR_NOT_SUPPORTED); any other diff --git a/crates/uda-platform-linux/src/media.rs b/crates/uda-platform-linux/src/media.rs index ae0c0a0..6ea2a0f 100644 --- a/crates/uda-platform-linux/src/media.rs +++ b/crates/uda-platform-linux/src/media.rs @@ -379,10 +379,11 @@ 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 @@ -390,15 +391,11 @@ fn dict_get<'d>( 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(); + 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. @@ -753,21 +750,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 182c6aa..9fcd7db 100644 --- a/crates/uda-platform-windows/src/media.rs +++ b/crates/uda-platform-windows/src/media.rs @@ -186,15 +186,13 @@ async fn active_metadata_async() -> Result, UdaError> { .map_err(|e| UdaError::DetectionFailed(format!("SMTC media properties: {e}")))?; // `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, }; @@ -220,6 +218,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 From d6240c12c4d6faede63c414d506c9989f57cb976 Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Thu, 8 Oct 2026 23:34:08 +0800 Subject: [PATCH 10/17] fix(ffi): regenerate the header for the published-empty metadata docs 0d273aa reworded the uda_media_get_metadata doc comment on the Rust side but shipped without the regenerated header, so the Cross-Compile Hygiene gate fails on the merge commit. Commit the regenerated header; the diff is the doc paragraph only - no signature or constant changes. --- include/uda.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/include/uda.h b/include/uda.h index b7da180..fef007c 100644 --- a/include/uda.h +++ b/include/uda.h @@ -407,8 +407,9 @@ int32_t uda_get_accent_color(uint8_t *out_rgba); * 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, which lets a binding - * skip it. The artist list is already joined with ", " when the player - * publishes several artists. + * skip it, while a field published as an empty string stays an empty string - + * the two cases remain distinguishable. The artist list is already joined + * with ", " when the player publishes several artists. * * `out_duration_ms` receives the track length in milliseconds, or 0 when * unknown (a live stream). `out_position_ms` is optional: pass NULL to skip From c0a0f7d9956386cca747666e35b349052bd49e55 Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Fri, 9 Oct 2026 00:05:47 +0800 Subject: [PATCH 11/17] docs: align media specs and binding notes with the NULL/empty contract Validation round on d6240c1 flagged three spots still describing the pre-0d273aa behavior: - media_specs.md 2.3 said a missing MPRIS key equals an empty string; it maps to None (NULL on the C-ABI) while a published empty value stays an empty string - the contract section 4 already states. - media_specs.md section 6 named metadata_from_dbus / duration_from_ticks, functions that do not exist; the pure parsers are metadata_from_dict / duration_from_micros and milliseconds_from_ticks. - The python/nodejs bindings' all-empty fold comments claimed the library normalizes every published-empty field to NULL; since 0d273aa only unpublished fields are NULL, so the comments now describe both cases honestly. Binding behavior is unchanged. --- docs/internals/media_specs.md | 10 ++++++---- examples/nodejs/uda.js | 7 ++++--- examples/python/uda.py | 7 ++++--- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/internals/media_specs.md b/docs/internals/media_specs.md index b314caa..4713b48 100644 --- a/docs/internals/media_specs.md +++ b/docs/internals/media_specs.md @@ -70,7 +70,8 @@ org.freedesktop.DBus -> ListNames() 毫秒会让一首 3 分钟的歌唱成 50 小时。 - `xesam:title` 可能是 **数组**(Chromium 系历史上这么发过)。取首个元素即可, 否则标题整段丢失。 -- 任何键都可能缺席(直播流、无元数据的本地文件)。缺席 == 空字符串,不是错误。 +- 任何键都可能缺席(直播流、无元数据的本地文件)。缺席映射为 `None`(C-ABI + 上是 NULL),不是错误;已发布但为空的值保持空字符串,两者可区分。 - `mpris:length` <= 0 表示直播或未知时长,映射为 `None` 而不是 0。 ### 2.4 错误分层 @@ -156,7 +157,8 @@ let session = manager.GetCurrentSession()?; // Option MediaTrack | None: artist_text = _decode_or_empty(artist) album_text = _decode_or_empty(album) - # 库端已把"元数据全空"归一成与"无播放器"完全相同的返回值(三个 - # NULL + 时长 0),SDK 必须同样归一成 None:否则调用方拿到一个空壳 - # 对象,无法与"没有播放器"区分,示例里就会打印出一堆"(未发布)"。 + # "无播放器"与"所有字段都未发布"在库端都是三个 NULL + 时长 0; + # 播放器把每个字段都发布成空串时,库端会保留空 C 串(与 NULL 可 + # 区分),绑定层同样把它归一成 None:示例只关心"有没有可展示的 + # 元数据",否则调用方拿到一个空壳对象,打印出一堆"(未发布)"。 if ( not title_text and not artist_text From 82256e9249e1557e881d4f1cfa2cb0aa54653610 Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Sat, 10 Oct 2026 15:04:12 +0800 Subject: [PATCH 12/17] fix(ffi): round-4 review - honest changelog, ABI parity test, script hygiene Fourth review round on PR #7: - The CHANGELOG's 'zero semantic change' claim is scoped to what was actually compared - signatures, constants, typedefs - and now says explicitly that pointer semantics changed in two intentional ways; the MediaMetadata Option flip gets its own Breaking entry with the migration pattern for Rust consumers. - metadata_from_dict's title/artist-vs-album asymmetry (tolerant readers for the array-legal keys, strict downcast for the single-string album) is deliberate per the MPRIS spec; a comment now locks that intent so a refactor cannot homogenise it. - The header preamble names the two string-returning helpers instead of pointing at 'below' - positional prose ages badly in a generated file. - gen-header.sh writes its scratch file under the workspace .tmp/ (gitignored) instead of /var/folders/3c/bxhhfjtx4mvcfvw1br4843qr0000gn/T/, matching the repo convention. - CLI_LOCK_SECONDS carries a cbindgen:ignore annotation, silencing the per-run 'Skip (not pub)' warning without changing any export. - A cargo-test-level gate now pins the header's symbol set against the crate's sources: every #[no_mangle] export, pub UDA_* constant and callback typedef in abi.rs must appear in include/uda.h and vice versa, so the drift that d6240c1 shipped (and CI caught) fails in plain 'cargo test -p uda-ffi' too. --- CHANGELOG.md | 13 +- crates/uda-ffi/cbindgen.toml | 8 +- crates/uda-ffi/src/abi.rs | 172 +++++++++++++++++++++++++ crates/uda-ffi/src/wakelocks.rs | 5 +- crates/uda-platform-linux/src/media.rs | 9 ++ include/uda.h | 8 +- scripts/gen-header.sh | 6 +- 7 files changed, 207 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78ce715..f04e51e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,10 +19,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 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. - - 对 C 调用者零语义变化:33 个常量值、32 个函数签名与 2 个回调 typedef 逐一比对等价;`header_symbols.py` 与 `pe_exports.py` 的「头文件 ↔ 动态库符号」校验保持不变。 - - Zero semantic change for C callers: all 33 constant values, 32 function signatures and both callback typedefs compare equal one by one; the `header_symbols.py` / `pe_exports.py` header-to-library symbol checks are unchanged. - - 三处「文档与实现不符」借此次迁移一并修正:`uda_set_wallpaper` 现在真的以 `UDA_ERR_INVALID_ARGUMENT` 拒绝空路径(原 Rust 文档如此承诺但从未实现);`uda_tray_set_icon_rgba` 的文档不再声称 `data` 可在 `len` 为 0 时为 NULL(实现一贯拒绝 NULL);`uda_media_get_metadata` 现按文档为未发布字段与「无播放器」写回 NULL(此前写回指向空字符串的非 NULL 指针,与 `docs/internals/media_specs.md` 及 Python/Node 绑定的注释相悖)。同时 `MediaMetadata` 的字符串字段改为 `Option`,使「已发布但为空」在 C-ABI 上保持为空字符串、与「未发布」(NULL)可区分。 - - Three documentation-versus-implementation mismatches were fixed along the way: `uda_set_wallpaper` now actually rejects an empty path with `UDA_ERR_INVALID_ARGUMENT` (the Rust docs always promised this but it was never implemented), `uda_tray_set_icon_rgba` no longer documents a NULL `data` for `len == 0` (the implementation has always rejected NULL), and `uda_media_get_metadata` now writes NULL for unpublished fields and for "no player" as documented (it previously wrote non-NULL pointers to empty strings, contradicting `docs/internals/media_specs.md` and the Python/Node binding comments). `MediaMetadata`'s string fields became `Option`, so a field published as an empty string stays an empty C string and remains distinguishable from "unpublished" (NULL). + - **ABI 表面零变化**(仅限签名、常量与 typedef 三个维度):33 个常量值、32 个函数签名与 2 个回调 typedef 逐一比对等价;`header_symbols.py` 与 `pe_exports.py` 的「头文件 ↔ 动态库符号」校验保持不变。指针语义维度**有**两处有意的行为修正(见下一条:`uda_media_get_metadata` 的 NULL 回填、`uda_set_wallpaper` 的空路径拒绝)——依赖旧行为的 C 宿主必须按新契约适配,这不属于「零变化」的承诺范围。 + - **Zero ABI-surface change** (scoped to signatures, constants and typedefs): all 33 constant values, 32 function signatures and both callback typedefs compare equal one by one; the `header_symbols.py` / `pe_exports.py` header-to-library symbol checks are unchanged. Pointer semantics **did** change in two intentional ways (next bullet: `uda_media_get_metadata`'s NULL backfill and `uda_set_wallpaper`'s empty-path refusal) - a C host relying on the old behavior must adapt to the new contract and is not covered by the "zero change" claim. + - 三处「文档与实现不符」借此次迁移一并修正:`uda_set_wallpaper` 现在真的以 `UDA_ERR_INVALID_ARGUMENT` 拒绝空路径(原 Rust 文档如此承诺但从未实现);`uda_tray_set_icon_rgba` 的文档不再声称 `data` 可在 `len` 为 0 时为 NULL(实现一贯拒绝 NULL);`uda_media_get_metadata` 现按文档为未发布字段与「无播放器」写回 NULL(此前写回指向空字符串的非 NULL 指针,与 `docs/internals/media_specs.md` 及 Python/Node 绑定的注释相悖)。同时 `MediaMetadata` 的字符串字段改为 `Option`,使「已发布但为空」在 C-ABI 上保持为空字符串、与「未发布」(NULL)可区分。三个字段从 `String` 改为 `Option` 本身是 **uda-core 的破坏性 Rust API 变更**(见下方 Breaking 条目)。 + - Three documentation-versus-implementation mismatches were fixed along the way: `uda_set_wallpaper` now actually rejects an empty path with `UDA_ERR_INVALID_ARGUMENT` (the Rust docs always promised this but it was never implemented), `uda_tray_set_icon_rgba` no longer documents a NULL `data` for `len == 0` (the implementation has always rejected NULL), and `uda_media_get_metadata` now writes NULL for unpublished fields and for "no player" as documented (it previously wrote non-NULL pointers to empty strings, contradicting `docs/internals/media_specs.md` and the Python/Node binding comments). `MediaMetadata`'s string fields became `Option`, so a field published as an empty string stays an empty C string and remains distinguishable from "unpublished" (NULL). The `String` → `Option` flip is itself a **breaking Rust API change in uda-core** (see the Breaking entry below). + +### ⚠️ 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 ↔ `None` 的映射见上一条)。动机: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 and the Python/Node bindings are unaffected (the NULL ↔ `None` mapping is covered by the previous bullet). Motivation: a C host must tell "not published" (NULL) from "published empty" (empty string), which a bare `String` cannot express. ## [v0.2.1] - Honest Theme Reporting & Reasoned Degradation · 2026-10-06 diff --git a/crates/uda-ffi/cbindgen.toml b/crates/uda-ffi/cbindgen.toml index a68f3d4..e1da9b9 100644 --- a/crates/uda-ffi/cbindgen.toml +++ b/crates/uda-ffi/cbindgen.toml @@ -51,10 +51,10 @@ header = """/* * * 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 below. Human-readable diagnostics for the most - * recent failure are available from `uda_last_error_message()`, and - * `uda_status_message()` renders any status code without a second FFI - * round-trip. + * 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 * ---------------- diff --git a/crates/uda-ffi/src/abi.rs b/crates/uda-ffi/src/abi.rs index 6e5c619..51bdd9a 100644 --- a/crates/uda-ffi/src/abi.rs +++ b/crates/uda-ffi/src/abi.rs @@ -151,6 +151,178 @@ mod tests { assert_eq!(UDA_ERR_PANIC, -6); } + /// 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` the way the safety-classification gate does. + 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"); + for line in source.lines() { + if line.trim() == "#[no_mangle]" { + pending_no_mangle = true; + continue; + } + if pending_no_mangle { + pending_no_mangle = false; + if let Some(name) = identifier_after(line, " fn ") { + functions.push(name); + } + } + if let Some(name) = identifier_after(line, "pub const UDA_") { + constants.push(format!("UDA_{name}")); + } + // 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"); + 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. + 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 = [ diff --git a/crates/uda-ffi/src/wakelocks.rs b/crates/uda-ffi/src/wakelocks.rs index 5c0e710..b716ba0 100644 --- a/crates/uda-ffi/src/wakelocks.rs +++ b/crates/uda-ffi/src/wakelocks.rs @@ -34,12 +34,15 @@ 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 /// child is a `sleep` bounded by this value. The lock is therefore *not* /// indefinite, which the C caller is told about through -/// `uda_last_error_message()` when the tier is used. +/// `uda_last_error_message()` when the tier is used. Implementation detail, +/// not C-ABI surface: the ignore annotation keeps cbindgen from scanning (and +/// warning about) a private constant it would otherwise visit. const CLI_LOCK_SECONDS: u64 = 3600; /// How a live entry must be released. diff --git a/crates/uda-platform-linux/src/media.rs b/crates/uda-platform-linux/src/media.rs index 6ea2a0f..4e41dec 100644 --- a/crates/uda-platform-linux/src/media.rs +++ b/crates/uda-platform-linux/src/media.rs @@ -391,6 +391,15 @@ fn dict_get<'d>( 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. + // + // `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))); diff --git a/include/uda.h b/include/uda.h index fef007c..0311a31 100644 --- a/include/uda.h +++ b/include/uda.h @@ -13,10 +13,10 @@ * * 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 below. Human-readable diagnostics for the most - * recent failure are available from `uda_last_error_message()`, and - * `uda_status_message()` renders any status code without a second FFI - * round-trip. + * 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 * ---------------- diff --git a/scripts/gen-header.sh b/scripts/gen-header.sh index b2bcaa6..53ef3a5 100755 --- a/scripts/gen-header.sh +++ b/scripts/gen-header.sh @@ -67,7 +67,11 @@ if [ "$installed" != "$CBINDGEN_VERSION" ]; then echo " Consider: cargo install cbindgen --locked --version ${CBINDGEN_VERSION}" >&2 fi -output="$(mktemp)" +# 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. From 4162d7feb6545b4322bf97c3958bbd8344d1ccaa Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Tue, 13 Oct 2026 11:24:30 +0800 Subject: [PATCH 13/17] fix(ffi): cross-validation round - honest Windows qualifier, loud gates Four-way cross-validation (two reviewers, four validators) over the full delta confirmed six minors, addressed: - The header's 'published empty stays an empty string' promise is now scoped: it holds on Linux; on Windows an empty read also surfaces as NULL because SMTC has no unset marker on the wire. media_specs.md gains the same qualifier in both the MPRIS and SMTC sections. - The parity test's scanner fails with the actual cause when #[no_mangle] is not immediately followed by its fn line, instead of a misleading 're-run gen-header.sh'; its hand-rolled parser limitations are documented as such (all currently unreachable, all failing loudly, never as silent drift). - gen-header.sh fails the generation when an unwrapped negative define survives the wrapping step, so a future non-decimal negative constant cannot ship '--...' tokens to callers silently. - The notify doc's availability probe is labelled Rust-only; the C-ABI surface has no notification-availability probe. - Simplifier pass: dict_get returns a reference, not an owned Value (comment was factually wrong); a dangling 'safety-classification gate' reference is gone; UDA_MEDIA_UNKNOWN's UDA_OK gets its backtick; and a pre-existing private intra-doc link in uda-core's notification.rs broke the rustdoc gate - now a plain code span. Verified in containers: uda-ffi 92 passed (parity test included), header regenerated and --check green, clippy -D warnings, fmt, and the uda-core rustdoc --locked gate all clean. --- crates/uda-core/src/notification.rs | 2 +- crates/uda-ffi/src/abi.rs | 42 +++++++++++++++++++++----- crates/uda-ffi/src/lib.rs | 10 ++++-- crates/uda-platform-linux/src/media.rs | 4 +-- docs/internals/media_specs.md | 10 ++++-- include/uda.h | 12 +++++--- scripts/gen-header.sh | 10 +++++- 7 files changed, 69 insertions(+), 21 deletions(-) diff --git a/crates/uda-core/src/notification.rs b/crates/uda-core/src/notification.rs index 6197ba8..73c3b2a 100644 --- a/crates/uda-core/src/notification.rs +++ b/crates/uda-core/src/notification.rs @@ -116,7 +116,7 @@ pub fn has_uri_scheme(value: &str) -> bool { /// relative ones keep what the caller supplied, because UDA has no working /// directory to resolve them against. /// -/// Absolute-ness comes from [`is_absolute_path`], which is host-independent. +/// Absolute-ness comes from `is_absolute_path`, which is host-independent. pub fn file_uri(path: &str) -> String { let forward = path.replace('\\', "/"); diff --git a/crates/uda-ffi/src/abi.rs b/crates/uda-ffi/src/abi.rs index 51bdd9a..c5d4481 100644 --- a/crates/uda-ffi/src/abi.rs +++ b/crates/uda-ffi/src/abi.rs @@ -76,7 +76,7 @@ pub const UDA_MEDIA_PAUSED: i32 = 1; 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. +/// it with a `UDA_OK` status. Never render it as a paused track. pub const UDA_MEDIA_UNKNOWN: i32 = 3; // --------------------------------------------------------------------------- @@ -167,7 +167,10 @@ mod tests { } /// The exported C-ABI names this crate's sources declare, gathered by - /// scanning `src/*.rs` the way the safety-classification gate does. + /// 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(); @@ -181,6 +184,10 @@ mod tests { 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; @@ -188,17 +195,27 @@ mod tests { } if pending_no_mangle { pending_no_mangle = false; - if let Some(name) = identifier_after(line, " fn ") { - functions.push(name); + 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}")); } - // 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"); if is_abi { if let Some(name) = identifier_after(line, "pub type ") { callbacks.push(name); @@ -217,6 +234,15 @@ mod tests { // 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( diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index 1e08d62..317ef73 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -238,8 +238,9 @@ pub extern "C" fn uda_wakelock_release(handle: u64) -> i32 { /// /// 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. +/// 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: @@ -335,7 +336,10 @@ pub unsafe extern "C" fn uda_get_accent_color(out_rgba: *mut u8) -> i32 { /// unconditionally. A field the player does not publish (a radio stream with /// no album, say) is NULL rather than an empty string, which lets a binding /// skip it, while a field published as an empty string stays an empty string - -/// the two cases remain distinguishable. The artist list is already joined +/// the two cases remain distinguishable on 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 rather than as a +/// Linux-only synonym for "unpublished". The artist list is already joined /// with ", " when the player publishes several artists. /// /// `out_duration_ms` receives the track length in milliseconds, or 0 when diff --git a/crates/uda-platform-linux/src/media.rs b/crates/uda-platform-linux/src/media.rs index 4e41dec..cda2aa4 100644 --- a/crates/uda-platform-linux/src/media.rs +++ b/crates/uda-platform-linux/src/media.rs @@ -389,8 +389,8 @@ fn dict_get<'d>( /// 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. + // `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 diff --git a/docs/internals/media_specs.md b/docs/internals/media_specs.md index 4713b48..1a69630 100644 --- a/docs/internals/media_specs.md +++ b/docs/internals/media_specs.md @@ -71,7 +71,9 @@ org.freedesktop.DBus -> ListNames() - `xesam:title` 可能是 **数组**(Chromium 系历史上这么发过)。取首个元素即可, 否则标题整段丢失。 - 任何键都可能缺席(直播流、无元数据的本地文件)。缺席映射为 `None`(C-ABI - 上是 NULL),不是错误;已发布但为空的值保持空字符串,两者可区分。 + 上是 NULL),不是错误;已发布但为空的值保持空字符串,两者可区分。这一 + 可区分性**仅 Linux 成立**:Windows 章节的 SMTC 没有线上"未发布"标记, + 空读取同样折叠为 `None`(见 §3.4)。 - `mpris:length` <= 0 表示直播或未知时长,映射为 `None` 而不是 0。 ### 2.4 错误分层 @@ -127,6 +129,10 @@ let session = manager.GetCurrentSession()?; // Option&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 From f00aa8e4f8dc7f1e11d7b97a0dfdc4fd25b36452 Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Tue, 13 Oct 2026 13:42:50 +0800 Subject: [PATCH 14/17] fix(ffi): keep the generated header's C semantics - unsigned caps, UdaStatus, pinned cbindgen - the seven UDA_SESSION_CAP_* constants now spell 1u32 << n, so cbindgen emits (1u << n) and a C caller's ~MASK keeps the unsigned 32-bit semantics the hand-written header had (regenerated include/uda.h); - restore the uda_ffi::UdaStatus rlib re-export that the abi.rs move dropped - existing `use uda_ffi::UdaStatus` hosts keep compiling; - gen-header.sh exits with an error instead of warning when the installed cbindgen is not the pinned version, before touching any output; - regressions: scripts/test-header.py (C11/C++11 static asserts for the capability macros, the Rust-only UdaStatus alias, and the version-gate behaviour), a public-API integration test, and a CI step running the header contract on the Linux job. --- .github/workflows/ci.yml | 8 +++ crates/uda-ffi/src/abi.rs | 14 ++-- crates/uda-ffi/src/lib.rs | 2 +- crates/uda-ffi/tests/public_api.rs | 9 +++ include/uda.h | 14 ++-- scripts/gen-header.sh | 6 +- scripts/test-header.py | 107 +++++++++++++++++++++++++++++ 7 files changed, 142 insertions(+), 18 deletions(-) create mode 100644 crates/uda-ffi/tests/public_api.rs create mode 100644 scripts/test-header.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ef84ffa..058480a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -118,6 +118,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 diff --git a/crates/uda-ffi/src/abi.rs b/crates/uda-ffi/src/abi.rs index c5d4481..e8f25cd 100644 --- a/crates/uda-ffi/src/abi.rs +++ b/crates/uda-ffi/src/abi.rs @@ -104,19 +104,19 @@ pub const UDA_MEDIA_CMD_STOP: i32 = 5; /// /// 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 = 1 << 16; +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 = 1 << 17; +pub const UDA_SESSION_CAP_LOCK: u32 = 1u32 << 17; /// The calling user's session can be ended. -pub const UDA_SESSION_CAP_LOGOUT: u32 = 1 << 18; +pub const UDA_SESSION_CAP_LOGOUT: u32 = 1u32 << 18; /// The machine can be suspended to RAM. -pub const UDA_SESSION_CAP_SUSPEND: u32 = 1 << 19; +pub const UDA_SESSION_CAP_SUSPEND: u32 = 1u32 << 19; /// The machine can be hibernated to disk. -pub const UDA_SESSION_CAP_HIBERNATE: u32 = 1 << 20; +pub const UDA_SESSION_CAP_HIBERNATE: u32 = 1u32 << 20; /// The machine can be rebooted. -pub const UDA_SESSION_CAP_REBOOT: u32 = 1 << 21; +pub const UDA_SESSION_CAP_REBOOT: u32 = 1u32 << 21; /// The machine can be powered off. -pub const UDA_SESSION_CAP_SHUTDOWN: u32 = 1 << 22; +pub const UDA_SESSION_CAP_SHUTDOWN: u32 = 1u32 << 22; // --------------------------------------------------------------------------- // Tray callbacks diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index 317ef73..eec2245 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -52,7 +52,7 @@ use std::os::raw::{c_char, c_void}; use uda_core::session::SessionAction; pub use abi::*; -pub use error::status_message; +pub use error::{status_message, UdaStatus}; /// Detect the current system colour scheme. /// 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/include/uda.h b/include/uda.h index 972ca12..190457a 100644 --- a/include/uda.h +++ b/include/uda.h @@ -199,37 +199,37 @@ * 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 (1 << 16) +#define UDA_SESSION_CAP_MANAGEMENT (1u << 16) /** * The session can be locked - the only action safe to automate. */ -#define UDA_SESSION_CAP_LOCK (1 << 17) +#define UDA_SESSION_CAP_LOCK (1u << 17) /** * The calling user's session can be ended. */ -#define UDA_SESSION_CAP_LOGOUT (1 << 18) +#define UDA_SESSION_CAP_LOGOUT (1u << 18) /** * The machine can be suspended to RAM. */ -#define UDA_SESSION_CAP_SUSPEND (1 << 19) +#define UDA_SESSION_CAP_SUSPEND (1u << 19) /** * The machine can be hibernated to disk. */ -#define UDA_SESSION_CAP_HIBERNATE (1 << 20) +#define UDA_SESSION_CAP_HIBERNATE (1u << 20) /** * The machine can be rebooted. */ -#define UDA_SESSION_CAP_REBOOT (1 << 21) +#define UDA_SESSION_CAP_REBOOT (1u << 21) /** * The machine can be powered off. */ -#define UDA_SESSION_CAP_SHUTDOWN (1 << 22) +#define UDA_SESSION_CAP_SHUTDOWN (1u << 22) /** * Callback type for a plain text menu row, or NULL for a silent row. diff --git a/scripts/gen-header.sh b/scripts/gen-header.sh index 226b907..5c8dee8 100755 --- a/scripts/gen-header.sh +++ b/scripts/gen-header.sh @@ -62,9 +62,9 @@ fi installed="$(cbindgen --version | awk '{print $2}')" if [ "$installed" != "$CBINDGEN_VERSION" ]; then - echo "warning: cbindgen v${installed} installed, but the header is generated" >&2 - echo " with v${CBINDGEN_VERSION}; output can differ between versions." >&2 - echo " Consider: cargo install cbindgen --locked --version ${CBINDGEN_VERSION}" >&2 + 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 diff --git a/scripts/test-header.py b/scripts/test-header.py new file mode 100644 index 0000000..65853c0 --- /dev/null +++ b/scripts/test-header.py @@ -0,0 +1,107 @@ +#!/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 +from pathlib import Path +import shlex +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +HEADER = ROOT / "include" / "uda.h" +CAPABILITIES = ( + ("MANAGEMENT", 16), + ("LOCK", 17), + ("LOGOUT", 18), + ("SUSPEND", 19), + ("HIBERNATE", 20), + ("REBOOT", 21), + ("SHUTDOWN", 22), +) + + +class HeaderRegressionTests(unittest.TestCase): + 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 name, bit in CAPABILITIES: + macro = f"UDA_SESSION_CAP_{name}" + complement = 0xFFFFFFFF ^ (1 << bit) + lines.extend( + ( + f'{assertion}({unsigned_type.format(macro=macro)}, "{macro} type");', + f'{assertion}({macro} == {1 << bit}u, "{macro} value");', + f'{assertion}((uint64_t)(~{macro}) == UINT64_C({complement}), "{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_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() From d22e565f5815dda6b6a295a80aedc9d0e25d3a00 Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Tue, 13 Oct 2026 16:39:26 +0800 Subject: [PATCH 15/17] fix: clarify media command outcomes in generated ABI contract --- crates/uda-ffi/src/lib.rs | 30 ++++++++++-------------------- crates/uda-ffi/src/media.rs | 6 ++++-- docs/internals/media_specs.md | 4 ++++ include/uda.h | 7 ++++--- 4 files changed, 22 insertions(+), 25 deletions(-) diff --git a/crates/uda-ffi/src/lib.rs b/crates/uda-ffi/src/lib.rs index eec2245..a4b4eed 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -372,29 +372,18 @@ pub unsafe extern "C" fn uda_media_get_metadata( } util::catch_boundary(|| { - let metadata = media::active_metadata()?; + let metadata = media::active_metadata()?.unwrap_or_default(); // 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, artist, album, duration_ms, position_ms) = match metadata { - Some(ref metadata) => ( - c_string_or_null(metadata.title.as_deref()), - c_string_or_null(metadata.artist.as_deref()), - c_string_or_null(metadata.album.as_deref()), - metadata.duration_ms.unwrap_or(0), - metadata.position_ms.unwrap_or(0), - ), - None => ( - std::ptr::null_mut(), - std::ptr::null_mut(), - std::ptr::null_mut(), - 0, - 0, - ), - }; + 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. @@ -445,9 +434,10 @@ pub unsafe extern "C" fn uda_media_get_status(out_status: *mut i32) -> i32 { /// `UDA_MEDIA_CMD_STOP`. An unrecognised code returns /// `UDA_ERR_INVALID_ARGUMENT` and nothing is sent. /// -/// A machine with no player running reports `UDA_ERR_NOT_SUPPORTED`, and any -/// non-`UDA_OK` status means the command was not delivered, so a caller can -/// tell "not delivered" from "delivered" without inspecting the player. +/// A machine with no player running reports `UDA_ERR_NOT_SUPPORTED`. Any +/// non-`UDA_OK` status means success was not confirmed. After a timeout or +/// communication failure, the player may already have executed the command; +/// do not blindly retry commands such as Next or Toggle, which can act twice. /// /// # Safety /// diff --git a/crates/uda-ffi/src/media.rs b/crates/uda-ffi/src/media.rs index 3864acb..58b2a9c 100644 --- a/crates/uda-ffi/src/media.rs +++ b/crates/uda-ffi/src/media.rs @@ -24,8 +24,10 @@ //! the normal case for a player that publishes only a title. //! //! A machine with nobody to command reports -//! [`UDA_ERR_NOT_SUPPORTED`](crate::abi::UDA_ERR_NOT_SUPPORTED); any other -//! non-`UDA_OK` status means the command was not delivered. +//! [`UDA_ERR_NOT_SUPPORTED`](crate::abi::UDA_ERR_NOT_SUPPORTED). Any +//! non-`UDA_OK` status means success was not confirmed. After a timeout or +//! communication failure, the player may already have executed the command; +//! do not blindly retry commands such as Next or Toggle, which can act twice. use uda_core::media::{MediaCommand, MediaManager, MediaMetadata, PlaybackStatus}; diff --git a/docs/internals/media_specs.md b/docs/internals/media_specs.md index 1a69630..ed08748 100644 --- a/docs/internals/media_specs.md +++ b/docs/internals/media_specs.md @@ -151,6 +151,10 @@ let session = manager.GetCurrentSession()?; // Option Date: Fri, 30 Oct 2026 12:59:22 +0800 Subject: [PATCH 16/17] fix: final cross-review round - ABI docs, media taxonomy, header gates Addresses the cross-validated review findings: tray menu rows use push-returned ids; media status/wakelock/command docs match the implementations; Windows media read failures degrade to Unknown/None; capability header gates pin the canonical bit map and parser shapes; malformed icon geometry reports InvalidArgument with a non-vacuous test. --- CHANGELOG.md | 6 +- crates/uda-core/src/media.rs | 41 +++++-- crates/uda-ffi/cbindgen.toml | 10 ++ crates/uda-ffi/src/abi.rs | 10 ++ crates/uda-ffi/src/dispatch.rs | 18 +-- crates/uda-ffi/src/lib.rs | 85 +++++++++++++-- crates/uda-ffi/src/tray.rs | 80 ++++++++++---- crates/uda-ffi/src/wakelocks.rs | 10 +- crates/uda-platform-linux/src/media.rs | 11 +- crates/uda-platform-windows/src/media.rs | 129 +++++++++++++++------- examples/nodejs/uda.js | 12 +- examples/python/uda.py | 20 +++- include/uda.h | 24 +++- scripts/header_symbols.py | 5 +- scripts/test-header.py | 133 ++++++++++++++++++++--- 15 files changed, 472 insertions(+), 122 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f04e51e..71e9184 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,8 +21,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 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 表面零变化**(仅限签名、常量与 typedef 三个维度):33 个常量值、32 个函数签名与 2 个回调 typedef 逐一比对等价;`header_symbols.py` 与 `pe_exports.py` 的「头文件 ↔ 动态库符号」校验保持不变。指针语义维度**有**两处有意的行为修正(见下一条:`uda_media_get_metadata` 的 NULL 回填、`uda_set_wallpaper` 的空路径拒绝)——依赖旧行为的 C 宿主必须按新契约适配,这不属于「零变化」的承诺范围。 - **Zero ABI-surface change** (scoped to signatures, constants and typedefs): all 33 constant values, 32 function signatures and both callback typedefs compare equal one by one; the `header_symbols.py` / `pe_exports.py` header-to-library symbol checks are unchanged. Pointer semantics **did** change in two intentional ways (next bullet: `uda_media_get_metadata`'s NULL backfill and `uda_set_wallpaper`'s empty-path refusal) - a C host relying on the old behavior must adapt to the new contract and is not covered by the "zero change" claim. - - 三处「文档与实现不符」借此次迁移一并修正:`uda_set_wallpaper` 现在真的以 `UDA_ERR_INVALID_ARGUMENT` 拒绝空路径(原 Rust 文档如此承诺但从未实现);`uda_tray_set_icon_rgba` 的文档不再声称 `data` 可在 `len` 为 0 时为 NULL(实现一贯拒绝 NULL);`uda_media_get_metadata` 现按文档为未发布字段与「无播放器」写回 NULL(此前写回指向空字符串的非 NULL 指针,与 `docs/internals/media_specs.md` 及 Python/Node 绑定的注释相悖)。同时 `MediaMetadata` 的字符串字段改为 `Option`,使「已发布但为空」在 C-ABI 上保持为空字符串、与「未发布」(NULL)可区分。三个字段从 `String` 改为 `Option` 本身是 **uda-core 的破坏性 Rust API 变更**(见下方 Breaking 条目)。 - - Three documentation-versus-implementation mismatches were fixed along the way: `uda_set_wallpaper` now actually rejects an empty path with `UDA_ERR_INVALID_ARGUMENT` (the Rust docs always promised this but it was never implemented), `uda_tray_set_icon_rgba` no longer documents a NULL `data` for `len == 0` (the implementation has always rejected NULL), and `uda_media_get_metadata` now writes NULL for unpublished fields and for "no player" as documented (it previously wrote non-NULL pointers to empty strings, contradicting `docs/internals/media_specs.md` and the Python/Node binding comments). `MediaMetadata`'s string fields became `Option`, so a field published as an empty string stays an empty C string and remains distinguishable from "unpublished" (NULL). The `String` → `Option` flip is itself a **breaking Rust API change in uda-core** (see the Breaking entry below). + - 三处「文档与实现不符」借此次迁移一并修正:`uda_set_wallpaper` 现在真的以 `UDA_ERR_INVALID_ARGUMENT` 拒绝空路径(原 Rust 文档如此承诺但从未实现);`uda_tray_set_icon_rgba` 的文档不再声称 `data` 可在 `len` 为 0 时为 NULL(实现一贯拒绝 NULL);`uda_media_get_metadata` 现按文档为未发布字段与「无播放器」写回 NULL(此前写回指向空字符串的非 NULL 指针,与 `docs/internals/media_specs.md` 及 Python/Node 绑定的注释相悖)。同时 `MediaMetadata` 的字符串字段改为 `Option`,使「已发布但为空」在 C-ABI 上保持为空字符串、与「未发布」(NULL)可区分(仅在 Linux;Windows SMTC 无未发布标记,空读取折叠为 NULL)。三个字段从 `String` 改为 `Option` 本身是 **uda-core 的破坏性 Rust API 变更**(见下方 Breaking 条目)。 + - Three documentation-versus-implementation mismatches were fixed along the way: `uda_set_wallpaper` now actually rejects an empty path with `UDA_ERR_INVALID_ARGUMENT` (the Rust docs always promised this but it was never implemented), `uda_tray_set_icon_rgba` no longer documents a NULL `data` for `len == 0` (the implementation has always rejected NULL), and `uda_media_get_metadata` now writes NULL for unpublished fields and for "no player" as documented (it previously wrote non-NULL pointers to empty strings, contradicting `docs/internals/media_specs.md` and the Python/Node binding comments). `MediaMetadata`'s string fields became `Option`, so a field published as an empty string stays an empty C string and remains distinguishable from "unpublished" (NULL) (Linux only; Windows SMTC has no unpublished marker, so an empty read folds to NULL). The `String` → `Option` flip is itself a **breaking Rust API change in uda-core** (see the Breaking entry below). +- 🛠️ **`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 侧这层只负责给出正确的状态码与诊断信息。 +- 🛠️ **`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`; the FFI layer only owns the status code and the diagnosis. ### ⚠️ Breaking diff --git a/crates/uda-core/src/media.rs b/crates/uda-core/src/media.rs index 4544d98..95abca7 100644 --- a/crates/uda-core/src/media.rs +++ b/crates/uda-core/src/media.rs @@ -81,9 +81,12 @@ 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_none() && self.artist.is_none() @@ -151,10 +154,21 @@ 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. + /// + /// Once a player has been selected, a refusal or a transport failure is + /// [`UdaError::CommandFailed`]. Reaching a player at all can fail first, + /// and those acquisition failures keep their own types: 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`] - so a non-`Ok` result does not always mean "the + /// player declined". Whether a refusal *should* instead count as a + /// successful call (the platform cannot always distinguish "declined" from + /// "done") is an open cross-platform design question; until it is settled, + /// 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. @@ -237,6 +251,19 @@ mod tests { 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()); + } + #[test] fn a_duration_alone_counts_as_information() { // A live-stream player often publishes nothing but a length. diff --git a/crates/uda-ffi/cbindgen.toml b/crates/uda-ffi/cbindgen.toml index e1da9b9..33cb6aa 100644 --- a/crates/uda-ffi/cbindgen.toml +++ b/crates/uda-ffi/cbindgen.toml @@ -14,6 +14,16 @@ 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 diff --git a/crates/uda-ffi/src/abi.rs b/crates/uda-ffi/src/abi.rs index e8f25cd..b3f67b5 100644 --- a/crates/uda-ffi/src/abi.rs +++ b/crates/uda-ffi/src/abi.rs @@ -151,6 +151,16 @@ mod tests { 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(); diff --git a/crates/uda-ffi/src/dispatch.rs b/crates/uda-ffi/src/dispatch.rs index f0cc8c7..9c71d6d 100644 --- a/crates/uda-ffi/src/dispatch.rs +++ b/crates/uda-ffi/src/dispatch.rs @@ -29,6 +29,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. @@ -81,11 +82,11 @@ 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, } } @@ -245,11 +246,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/lib.rs b/crates/uda-ffi/src/lib.rs index a4b4eed..c0d4f27 100644 --- a/crates/uda-ffi/src/lib.rs +++ b/crates/uda-ffi/src/lib.rs @@ -177,6 +177,14 @@ pub unsafe extern "C" fn uda_free_string(s: *mut c_char) { /// `*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. +/// /// # Safety /// /// `out_handle` must point to a writable, non-null `uint64_t` location and @@ -406,7 +414,13 @@ pub unsafe extern "C" fn uda_media_get_metadata( /// `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. +/// 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 /// @@ -774,13 +788,13 @@ pub unsafe extern "C" fn uda_tray_set_icon_path(handle: u64, path: *const c_char /// /// 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. +/// 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 not be null and must point to `len` readable bytes. `width` -/// and `height` must be non-zero and `stride` at least `width * 4`. +/// `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, @@ -1041,13 +1055,70 @@ mod tests { assert_eq!(text, ""); // SAFETY: same pointer, freed exactly once. unsafe { util::free_c_string(pointer) }; - // Published text -> the text. + // Published text -> the text, read back verbatim. let pointer = c_string_or_null(Some("/music/track.flac")); assert!(!pointer.is_null()); - // SAFETY: same ownership pattern as above. + // SAFETY: the pointer came from `c_string_from` 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] fn fill_mode_codes_are_accepted_and_rejected() { assert!(fill_mode_from_c(UDA_FILL_CROP).is_ok()); diff --git a/crates/uda-ffi/src/tray.rs b/crates/uda-ffi/src/tray.rs index 09a4839..2b827ae 100644 --- a/crates/uda-ffi/src/tray.rs +++ b/crates/uda-ffi/src/tray.rs @@ -281,6 +281,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()))? @@ -345,19 +366,11 @@ pub(crate) fn menu_add_text( user_data: *mut c_void, ) -> Result { let menu = TrayRegistry::global().menu(menu_handle)?; - // Push first so the core model allocates the id: it is the authority on what - // the shell will see, and duplicating that numbering here would let the two - // disagree. The callback then needs a second lookup by label-free id, which - // `entries()` gives back, so the trampoline is attached in a second step. - menu.push(MenuItem::text(label))?; - - // The id of the row just appended: the menu assigns ids monotonically, so - // the last entry is the one this call added. - let item_id = menu - .entries() - .last() - .map(|(id, _)| *id) - .ok_or_else(|| Failure::InvalidArgument("the menu dropped the new row".to_string()))?; + // `push` returns the id the core model assigned to *this* row. Using that + // value directly (rather than looking at `entries().last()`) keeps the + // callback attached to the row this call appended even when another thread + // appends to the same menu concurrently - the documented threading model. + let item_id = menu.push(MenuItem::text(label))?; if let Some(callback) = callback { let payload = SendVoidPtr(user_data); @@ -404,14 +417,9 @@ pub(crate) fn menu_add_checkbox( } else { MenuItem::checkbox(label) }; - menu.push(item)?; - - // The id of the row just appended, for the same reason as in `menu_add_text`. - let item_id = menu - .entries() - .last() - .map(|(id, _)| *id) - .ok_or_else(|| Failure::InvalidArgument("the menu dropped the new row".to_string()))?; + // The id of the row this call appended, for the same reason as in + // `menu_add_text`: the returned id is authoritative under concurrent adds. + let item_id = menu.push(item)?; let payload = SendVoidPtr(user_data); // The menu is cloned into the closure so the trampoline can invert the @@ -744,6 +752,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/wakelocks.rs b/crates/uda-ffi/src/wakelocks.rs index b716ba0..30cd614 100644 --- a/crates/uda-ffi/src/wakelocks.rs +++ b/crates/uda-ffi/src/wakelocks.rs @@ -39,10 +39,12 @@ use crate::error::Failure; /// /// `systemd-inhibit --mode=block` returns as soon as its child exits, so the /// child is a `sleep` bounded by this value. The lock is therefore *not* -/// indefinite, which the C caller is told about through -/// `uda_last_error_message()` when the tier is used. Implementation detail, -/// not C-ABI surface: the ignore annotation keeps cbindgen from scanning (and -/// warning about) a private constant it would otherwise visit. +/// indefinite; the C caller is told about the cap in the public +/// `uda_wakelock_acquire` documentation, not through +/// `uda_last_error_message()` (a successful acquire records no message). +/// Implementation detail, not C-ABI surface: the ignore annotation keeps +/// cbindgen from scanning (and warning about) a private constant it would +/// otherwise visit. const CLI_LOCK_SECONDS: u64 = 3600; /// How a live entry must be released. diff --git a/crates/uda-platform-linux/src/media.rs b/crates/uda-platform-linux/src/media.rs index cda2aa4..08a6aae 100644 --- a/crates/uda-platform-linux/src/media.rs +++ b/crates/uda-platform-linux/src/media.rs @@ -469,11 +469,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. diff --git a/crates/uda-platform-windows/src/media.rs b/crates/uda-platform-windows/src/media.rs index 9fcd7db..1678d18 100644 --- a/crates/uda-platform-windows/src/media.rs +++ b/crates/uda-platform-windows/src/media.rs @@ -142,6 +142,24 @@ pub(crate) async fn send_smtc_command(command: MediaCommand) -> Result<(), UdaEr run_command(&session, command).await } +/// Interpret the `bool` a `Try*Async()` transport call returns. +/// +/// Both `true` and `false` are successful WinRT calls; `false` means the +/// session *refused* the command (or is not listening), which UDA reports as +/// [`UdaError::CommandFailed`] so a caller can tell "sent" from "refused". +/// Kept as a pure helper so the mapping is testable without a live SMTC +/// session. +fn command_outcome(accepted: bool, command: MediaCommand) -> Result<(), UdaError> { + if accepted { + Ok(()) + } else { + Err(UdaError::CommandFailed(format!( + "the media session refused the command {:?}", + command.code() + ))) + } +} + /// Invoke one transport method and report a refusal as an error. async fn run_command( session: &windows::Media::Control::GlobalSystemMediaTransportControlsSession, @@ -160,11 +178,7 @@ async fn run_command( }; match accepted { - Ok(true) => Ok(()), - Ok(false) => Err(UdaError::CommandFailed(format!( - "the media session refused the command {:?}", - command.code() - ))), + Ok(accepted) => command_outcome(accepted, command), Err(e) => Err(UdaError::CommandFailed(format!("SMTC {e}"))), } } @@ -173,17 +187,36 @@ async fn run_command( /// /// `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. An absent @@ -242,19 +275,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)) } @@ -347,21 +397,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] @@ -377,13 +429,13 @@ mod tests { // The `Ok(false)` branch is the SMTC-specific quirk: the WinRT call // succeeded but the session declined. A caller must be able to tell that // apart from "sent", which is why it maps to `CommandFailed`. - let outcome: Result<(), UdaError> = Err(UdaError::CommandFailed( - "the media session refused the command 2".to_string(), - )); - - match outcome { + match command_outcome(false, MediaCommand::TogglePlayPause) { Err(UdaError::CommandFailed(message)) => { assert!(message.contains("refused"), "message: {message}"); + assert!( + message.contains('2'), + "the command code is quoted: {message}" + ); } other => panic!("expected a CommandFailed, got {other:?}"), } @@ -393,8 +445,7 @@ mod tests { fn an_accepted_command_is_reported_as_success() { // A `true` reply only means the session accepted the command; it can // still fail inside the app, and that is indistinguishable from here. - let accepted: Result = Ok(true); - assert_eq!(accepted.ok(), Some(true)); + assert!(command_outcome(true, MediaCommand::Play).is_ok()); } #[test] diff --git a/examples/nodejs/uda.js b/examples/nodejs/uda.js index f1555f7..0ac45da 100644 --- a/examples/nodejs/uda.js +++ b/examples/nodejs/uda.js @@ -863,11 +863,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;播放器把 - // 每个字段都发布成空串时,库端会保留空 C 串(与 NULL 可区分),绑定层 - // 同样把它归一成 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; } diff --git a/examples/python/uda.py b/examples/python/uda.py index 25d8da6..81a76e4 100644 --- a/examples/python/uda.py +++ b/examples/python/uda.py @@ -1036,15 +1036,19 @@ def now_playing(self) -> MediaTrack | None: artist_text = _decode_or_empty(artist) album_text = _decode_or_empty(album) - # "无播放器"与"所有字段都未发布"在库端都是三个 NULL + 时长 0; - # 播放器把每个字段都发布成空串时,库端会保留空 C 串(与 NULL 可 - # 区分),绑定层同样把它归一成 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 @@ -1081,8 +1085,12 @@ def send(self, command: str) -> None: command: :class:`MediaCommand` 常量之一。 Raises: - UdaError: 指令名无法识别(状态码 -1),或没有播放器可接收、播放器 - 拒绝执行(状态码 -2)。 + UdaError: 指令名无法识别(状态码 -1,``ERR_INVALID_ARGUMENT``); + 没有播放器可接收,或 Windows 取不到 SMTC 会话管理器 + (状态码 -2,``ERR_NOT_SUPPORTED``);Linux 连不上 session bus, + 或 Windows 的 SMTC 管理器 ``RequestAsync`` 失败(状态码 -3, + ``ERR_DETECTION_FAILED``);已选中的播放器拒绝执行,或其传输 + 调用/代理构建失败(状态码 -5,``ERR_INTERNAL``)。 """ try: code = _MEDIA_COMMAND_CODES[command] diff --git a/include/uda.h b/include/uda.h index 92d9583..7887474 100644 --- a/include/uda.h +++ b/include/uda.h @@ -318,6 +318,14 @@ void uda_free_string(char *s); * `*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. + * * # Safety * * `out_handle` must point to a writable, non-null `uint64_t` location and @@ -439,7 +447,13 @@ int32_t uda_media_get_metadata(char **out_title, * `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. + * 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 * @@ -700,13 +714,13 @@ int32_t uda_tray_set_icon_path(uint64_t handle, const char *path); * * 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. + * 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 not be null and must point to `len` readable bytes. `width` - * and `height` must be non-zero and `stride` at least `width * 4`. + * `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, diff --git a/scripts/header_symbols.py b/scripts/header_symbols.py index ef5a685..2395745 100644 --- a/scripts/header_symbols.py +++ b/scripts/header_symbols.py @@ -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 index 65853c0..fa1c1f8 100644 --- a/scripts/test-header.py +++ b/scripts/test-header.py @@ -6,27 +6,106 @@ """ import os -from pathlib import Path +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" -CAPABILITIES = ( - ("MANAGEMENT", 16), - ("LOCK", 17), - ("LOGOUT", 18), - ("SUSPEND", 19), - ("HIBERNATE", 20), - ("REBOOT", 21), - ("SHUTDOWN", 22), + +#: 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"), @@ -41,14 +120,16 @@ def test_capability_macros_preserve_unsigned_c_and_cpp_semantics(self): lines.append("#include ") assertion = "static_assert" unsigned_type = "std::is_same::value" - for name, bit in CAPABILITIES: - macro = f"UDA_SESSION_CAP_{name}" - complement = 0xFFFFFFFF ^ (1 << bit) + 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");', - f'{assertion}((uint64_t)(~{macro}) == UINT64_C({complement}), "{macro} complement");', + # 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)) @@ -62,6 +143,32 @@ def test_capability_macros_preserve_unsigned_c_and_cpp_semantics(self): ) 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") From 01f4cb528ab0d78ba4af79a71d2c806335fc0cbe Mon Sep 17 00:00:00 2001 From: umbrella22 <1035765115@qq.com> Date: Sun, 1 Nov 2026 22:58:17 +0800 Subject: [PATCH 17/17] fix(ffi): drop a redundant rustdoc link target after the merge The merged util.rs carried an explicit target that now resolves through the abi re-export, which the workspace rustdoc gate rejects under -D warnings. --- crates/uda-ffi/src/util.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/uda-ffi/src/util.rs b/crates/uda-ffi/src/util.rs index 36b22e7..56a2dc6 100644 --- a/crates/uda-ffi/src/util.rs +++ b/crates/uda-ffi/src/util.rs @@ -144,7 +144,7 @@ pub(crate) unsafe fn free_c_string(pointer: *mut c_char) { /// /// The closure returns a `Result<(), Failure>`; a `panic!` inside it is caught /// and reported as -/// [`UDA_ERR_PANIC`](crate::abi::UDA_ERR_PANIC) so it can never unwind into +/// [`UDA_ERR_PANIC`] so it can never unwind into /// foreign frames, where unwinding across an `extern "C"` boundary is undefined /// behaviour. pub(crate) fn catch_boundary(body: F) -> UdaStatus