wayland_backend/sys/
mod.rs

1//! Implementations of the Wayland backends using the system `libwayland`
2
3use std::sync::Arc;
4
5use wayland_sys::client::wl_proxy;
6use wayland_sys::common::{wl_argument, wl_array};
7
8use crate::protocol::{ArgumentType, Interface};
9
10#[cfg(any(test, feature = "client_system"))]
11mod client_impl;
12#[cfg(any(test, feature = "server_system"))]
13mod server_impl;
14
15/// Magic static for wayland objects managed by wayland-client or wayland-server
16///
17/// This static serves no purpose other than existing at a stable address.
18static RUST_MANAGED: u8 = 42;
19
20unsafe fn free_arrays(signature: &[ArgumentType], arglist: &[wl_argument]) {
21    for (typ, arg) in signature.iter().zip(arglist.iter()) {
22        if let ArgumentType::Array = typ {
23            // Safety: the arglist provided arglist must be valid for associated signature
24            // and contains pointers to boxed arrays as appropriate
25            let _ = unsafe { Box::from_raw(arg.a as *mut wl_array) };
26        }
27    }
28}
29
30/// Client-side implementation of a Wayland protocol backend using `libwayland`
31///
32/// Entrypoints are:
33/// - [`Backend::connect()`][client::Backend::connect()] method if you're creating the Wayland connection
34/// - [`Backend::from_foreign_display()`][client::Backend::from_foreign_display()] if you're interacting with an
35///   already existing Wayland connection through FFI.
36#[cfg(any(test, feature = "client_system"))]
37#[path = "../client_api.rs"]
38pub mod client;
39#[cfg(any(test, feature = "client_system"))]
40use client::{ObjectData, ObjectId};
41
42// API complements for FFI
43
44#[cfg(any(test, feature = "client_system"))]
45impl client::ObjectId {
46    /// Creates an object id from a libwayland-client pointer.
47    ///
48    /// # Errors
49    ///
50    /// This function returns an [`InvalidId`][client::InvalidId] error if the interface of the proxy does
51    /// not match the provided interface.
52    ///
53    /// # Safety
54    ///
55    /// The provided pointer must be a valid pointer to a `wl_resource` and remain valid for as
56    /// long as the retrieved `ObjectId` is used.
57    pub unsafe fn from_ptr(
58        interface: &'static crate::protocol::Interface,
59        ptr: *mut wayland_sys::client::wl_proxy,
60    ) -> Result<Self, client::InvalidId> {
61        Ok(Self { id: unsafe { client_impl::InnerObjectId::from_ptr(interface, ptr) }? })
62    }
63
64    /// Get the underlying libwayland pointer for this object
65    pub fn as_ptr(&self) -> *mut wayland_sys::client::wl_proxy {
66        self.id.as_ptr()
67    }
68}
69
70#[cfg(any(test, feature = "client_system"))]
71impl client::Backend {
72    /// Creates a Backend from a foreign `*mut wl_display`.
73    ///
74    /// This is useful if you are writing a library that is expected to plug itself into an existing
75    /// Wayland connection.
76    ///
77    /// This will initialize the [`Backend`][Self] in "guest" mode, meaning it will not close the
78    /// connection on drop. After the [`Backend`][Self] is dropped, if the server sends an event
79    /// to an object that was created from it, that event will be silently discarded. This may lead to
80    /// protocol errors if the server expects an answer to that event, as such you should make sure to
81    /// cleanup your Wayland state before dropping the [`Backend`][Self].
82    ///
83    /// # Safety
84    ///
85    /// You need to ensure the `*mut wl_display` remains live as long as the  [`Backend`][Self]
86    /// (or its clones) exist.
87    pub unsafe fn from_foreign_display(display: *mut wayland_sys::client::wl_display) -> Self {
88        Self { backend: unsafe { client_impl::InnerBackend::from_foreign_display(display) } }
89    }
90
91    /// Returns the underlying `wl_display` pointer to this backend.
92    ///
93    /// This pointer is needed to interface with EGL, Vulkan and other C libraries.
94    ///
95    /// This pointer is only valid for the lifetime of the backend.
96    pub fn display_ptr(&self) -> *mut wayland_sys::client::wl_display {
97        self.backend.display_ptr()
98    }
99
100    /// Take over handling for a proxy created by a third party.
101    ///
102    /// # Safety
103    ///
104    /// There must never be more than one party managing an object. This is only
105    /// safe to call when a third party gave you ownership of an unmanaged proxy.
106    ///
107    /// The caller is also responsible for making sure the passed interface matches
108    /// the proxy.
109    #[inline]
110    pub unsafe fn manage_object(
111        &self,
112        interface: &'static Interface,
113        proxy: *mut wl_proxy,
114        data: Arc<dyn ObjectData>,
115    ) -> ObjectId {
116        unsafe { self.backend.manage_object(interface, proxy, data) }
117    }
118}
119
120#[cfg(any(test, feature = "client_system"))]
121impl client::ReadEventsGuard {
122    /// The same as [`read`], but doesn't dispatch events.
123    ///
124    /// To dispatch them, use [`dispatch_inner_queue`].
125    ///
126    /// [`read`]: client::ReadEventsGuard::read
127    /// [`dispatch_inner_queue`]: client::Backend::dispatch_inner_queue
128    pub fn read_without_dispatch(mut self) -> Result<(), client::WaylandError> {
129        self.guard.read_non_dispatch()
130    }
131}
132
133// SAFETY:
134// - The display_ptr will not change for the lifetime of the backend.
135// - The display_ptr will be valid, either because we have created the pointer or the caller which created the
136//   backend has ensured the pointer is valid when `Backend::from_foreign_display` was called.
137#[cfg(feature = "raw-window-handle")]
138unsafe impl raw_window_handle::HasRawDisplayHandle for client::Backend {
139    fn raw_display_handle(&self) -> raw_window_handle::RawDisplayHandle {
140        let mut handle = raw_window_handle::WaylandDisplayHandle::empty();
141        handle.display = self.display_ptr().cast();
142        raw_window_handle::RawDisplayHandle::Wayland(handle)
143    }
144}
145
146#[cfg(all(feature = "rwh_06", feature = "client_system"))]
147impl rwh_06::HasDisplayHandle for client::Backend {
148    fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
149        use std::ptr::NonNull;
150
151        // SAFETY:
152        // - The display_ptr will be valid, either because we have created the pointer or the caller which created the
153        //   backend has ensured the pointer is valid when `Backend::from_foreign_display` was called.
154        let ptr = unsafe { NonNull::new_unchecked(self.display_ptr().cast()) };
155        let handle = rwh_06::WaylandDisplayHandle::new(ptr);
156        let raw = rwh_06::RawDisplayHandle::Wayland(handle);
157
158        // SAFETY:
159        // - The display_ptr will be valid, either because we have created the pointer or the caller which created the
160        //   backend has ensured the pointer is valid when `Backend::from_foreign_display` was called.
161        // - The lifetime assigned to the DisplayHandle borrows the Backend, ensuring the display pointer
162        //   is valid..
163        // - The display_ptr will not change for the lifetime of the backend.
164        Ok(unsafe { rwh_06::DisplayHandle::borrow_raw(raw) })
165    }
166}
167
168/// Server-side implementation of a Wayland protocol backend using `libwayland`
169///
170/// The main entrypoint is the [`Backend::new()`][server::Backend::new()] method.
171#[cfg(any(test, feature = "server_system"))]
172#[path = "../server_api.rs"]
173pub mod server;
174
175#[cfg(any(test, feature = "server_system"))]
176impl server::ObjectId {
177    /// Creates an object from a C pointer.
178    ///
179    /// # Errors
180    ///
181    /// This function returns an [`InvalidId`][server::InvalidId] error if the interface of the
182    /// resource does not match the provided interface.
183    ///
184    /// # Safety
185    ///
186    /// The provided pointer must be a valid pointer to a `wl_resource` and remain valid for as
187    /// long as the retrieved `ObjectId` is used.
188    pub unsafe fn from_ptr(
189        interface: &'static crate::protocol::Interface,
190        ptr: *mut wayland_sys::server::wl_resource,
191    ) -> Result<Self, server::InvalidId> {
192        Ok(Self { id: unsafe { server_impl::InnerObjectId::from_ptr(Some(interface), ptr) }? })
193    }
194
195    /// Returns the pointer that represents this object.
196    ///
197    /// The pointer may be used to interoperate with libwayland.
198    pub fn as_ptr(&self) -> *mut wayland_sys::server::wl_resource {
199        self.id.as_ptr()
200    }
201}
202
203#[cfg(any(test, feature = "server_system"))]
204impl server::Handle {
205    /// Access the underlying `*mut wl_display` pointer
206    pub fn display_ptr(&self) -> *mut wayland_sys::server::wl_display {
207        self.handle.display_ptr()
208    }
209}