wl_client/proxy.rs
1//! Wayland proxy objects and helpers.
2//!
3//! Proxies represent objects in the wayland protocol. Libwayland uses `wl_proxy` pointers
4//! to represent proxies and `wl-client` provides safe types to handle them.
5//!
6//! # Proxy types
7//!
8//! There are four different types of proxies across two dimensions:
9//!
10//! - In libwayland:
11//! - A *wrapper* `wl_proxy` is a proxy that was created by calling the
12//! `wl_proxy_create_wrapper` function.
13//! - A *plain* `wl_proxy` is any other proxy.
14//! - In `wl-client`:
15//! - An *owned* proxy is a proxy that will destroy the underlying `wl_proxy` when it is
16//! dropped.
17//! - A *borrowed* proxy is a proxy that only references a `wl_proxy` and will never be
18//! used to destroy it.
19//!
20//! Therefore, each proxy is
21//!
22//! - an owned wrapper proxy,
23//! - an owned plain proxy,
24//! - a borrowed wrapper proxy, or
25//! - a borrowed plain proxy.
26//!
27//! # Owned proxies
28//!
29//! Owned proxies are proxies created by `wl-client`. They have a [`Queue`], also created by
30//! `wl-client`, which can be accessed by calling [`queue`].
31//!
32//! When an owned proxy is used to create a new wayland object, the function returns a new
33//! owned proxy that is assigned to the same queue as its parent.
34//!
35//! An owned proxy can be used to destroy the proxy by sending a destructor request or by
36//! using the [`destroy`] function. Owned proxies are implicitly destroyed with the
37//! [`destroy`] function in the following situations:
38//!
39//! - When the last reference to the owned proxy is dropped.
40//! - When the [`QueueOwner`] owning the proxy's queue is dropped. This is explained in
41//! detail in the documentation of [`Queue`].
42//!
43//! # Borrowed proxies
44//!
45//! Borrowed proxies might or might not have been created by `wl-client`. Each owned proxy
46//! derefs to a borrowed proxy but a borrowed proxy can also be created from raw
47//! `wl_proxy` pointers.
48//!
49//! Since the ownership of these proxies is unknown, they cannot be used to to destroy the
50//! proxy.
51//!
52//! If a request is sent on a borrowed proxy that creates a new wayland object, the caller
53//! must also pass in a [`Queue`]. The returned owned proxy will be assigned to this
54//! queue.
55//!
56//! # Creating wrapper proxies
57//!
58//! When working with wayland objects created by foreign code, the foreign code usually
59//! shares raw `wl_proxy` pointers. Given a [`Queue`], it is possible to create a new
60//! owned wrapper proxy by calling [`Queue::wrap_wl_proxy`].
61//!
62//! # Setting proxy event handlers
63//!
64//! Event handlers can be attached to owned plain proxies by using one of the following
65//! functions:
66//!
67//! - [`set_event_handler`] - for `Send + 'static` event handlers
68//! - [`set_event_handler_local`] - for `'static` event handlers
69//! - [`set_event_handler_no_op`]
70//! - [`Scope::set_event_handler`] - for `Send + 'scope` event handlers
71//! - [`Scope::set_event_handler_local`] - for `'scope` event handlers
72//!
73//! The `_local` variant allows setting event handlers that do not implement `Send`. The
74//! `_no_op` variant can be used to destroy compositor-created resources if
75//! the application is not otherwise interested in events.
76//!
77//! Event handlers cannot be set on owned wrapper proxies.
78//!
79//! For each proxy, the event handler can only be set once and once set it cannot be
80//! unset.
81
82use crate::Queue;
83#[expect(unused_imports)]
84use crate::Scope;
85#[expect(unused_imports)]
86use crate::connection::Connection;
87use crate::ffi;
88use crate::ffi::wl_interface;
89use crate::proxy::low_level::CreateEventHandler;
90use crate::proxy::low_level::EventHandler;
91use crate::proxy::low_level::UntypedBorrowedProxy;
92use crate::proxy::low_level::UntypedBorrowedProxyWrapper;
93use crate::proxy::low_level::UntypedOwnedProxy;
94use crate::proxy::low_level::UntypedOwnedProxyWrapper;
95pub use crate::proxy::low_level::borrowed::BorrowedProxyLock;
96#[expect(unused_imports)]
97use crate::queue::QueueOwner;
98use std::mem;
99use std::ptr::NonNull;
100
101pub mod low_level;
102#[cfg(test)]
103mod tests;
104
105/// An owned proxy.
106///
107/// This type is usually implemented by bindings that are automatically generated with the
108/// `wl-client-builder` crate.
109///
110/// # Safety
111///
112/// - `WL_INTERFACE` must refer to a valid interface specification.
113/// - It must be safe to transmute this type from an [`UntypedOwnedProxy`] that has an
114/// interface that is compatible with `WL_INTERFACE`.
115/// - The interface of the contained proxy must be compatible with `WL_INTERFACE`.
116/// - The [`EventHandler::mutable_type`] of the [`OwnedProxy::NoOpEventHandler`] must be
117/// `None` or the type ID of `()`.
118pub unsafe trait OwnedProxy: UntypedOwnedProxyWrapper {
119 /// The name of the interface.
120 const INTERFACE: &'static str;
121 /// The libwayland interface specification.
122 const WL_INTERFACE: &'static wl_interface;
123 /// An event handler that ignores all events without leaking memory.
124 const NO_OP_EVENT_HANDLER: Self::NoOpEventHandler;
125 /// The maximum protocol version supported by this type.
126 const MAX_VERSION: u32;
127
128 /// The borrowed version of this proxy.
129 type Borrowed: BorrowedProxy<Owned = Self>;
130 /// A type used to implement some technical operations on the proxy.
131 ///
132 /// This type exists to avoid polluting the function namespace of the proxy.
133 type Api;
134 /// An event handler that ignores all events without leaking memory.
135 type NoOpEventHandler: EventHandler + Send + 'static;
136}
137
138/// A borrowed proxy.
139///
140/// This type is usually implemented by bindings that are automatically generated with the
141/// `wl-client-builder` crate.
142///
143/// # Safety
144///
145/// - It must be safe to transmute this type from a [`UntypedBorrowedProxy`] that has an
146/// interface that is compatible with `Owned::WL_INTERFACE`.
147/// - The interface of the contained proxy must be compatible with `Owned::WL_INTERFACE`.
148pub unsafe trait BorrowedProxy: UntypedBorrowedProxyWrapper {
149 /// The owned version of this proxy.
150 type Owned: OwnedProxy<Borrowed = Self>;
151}
152
153#[inline]
154pub(crate) fn get_owned<T>(proxy: &T) -> &UntypedOwnedProxy
155where
156 T: UntypedOwnedProxyWrapper,
157{
158 // SAFETY: The trait requires that T is a transparent wrapper around UntypedOwnedProxy
159 unsafe { mem::transmute::<&T, &UntypedOwnedProxy>(proxy) }
160}
161
162#[inline]
163pub(crate) fn get_ref<T>(proxy: &T) -> &UntypedBorrowedProxy
164where
165 T: UntypedBorrowedProxyWrapper,
166{
167 // SAFETY: The trait requires that T is a transparent wrapper around UntypedBorrowedProxy
168 unsafe { mem::transmute::<&T, &UntypedBorrowedProxy>(proxy) }
169}
170
171/// Destroys a proxy without sending a wayland message.
172///
173/// This function only destroys the proxy in libwayland without sending a message to the
174/// compositor. You might use this function in the following situations:
175///
176/// - The type does not provide a destructor request.
177/// - In an event handler that destroys the object, e.g. `wl_callback.done`.
178/// - You want to deliberately leak the wayland object without leaking memory.
179///
180/// This function does nothing if the proxy is already destroyed.
181///
182/// # Panic
183///
184/// This function might panic if the proxy is attached to a local queue and the current
185/// thread is not the thread in which the queue was created.
186///
187/// # Example
188///
189/// ```
190/// # use std::ptr;
191/// # use wl_client::{proxy, Libwayland};
192/// # use wl_client::test_protocols::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
193/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
194/// #
195/// let lib = Libwayland::open().unwrap();
196/// let con = lib.connect_to_default_display().unwrap();
197/// let queue = con.create_queue(c"");
198/// let display: WlDisplay = queue.display();
199///
200/// let sync = display.sync();
201/// let sync2 = sync.clone();
202/// proxy::set_event_handler(&sync, WlCallback::on_done(move |_, _| {
203/// proxy::destroy(&sync2);
204/// }));
205///
206/// queue.dispatch_roundtrip_blocking().unwrap();
207/// assert!(proxy::wl_proxy(&*sync).is_none());
208/// ```
209#[inline]
210pub fn destroy(proxy: &impl UntypedOwnedProxyWrapper) {
211 get_owned(proxy).destroy();
212}
213
214/// Sets the event handler of the proxy.
215///
216/// This function can only be called once for each proxy. This function cannot be called
217/// on wrappers.
218///
219/// The event handler must implement [`Send`]. Use [`set_event_handler_local`] if your
220/// event handler does not implement `Send`.
221///
222/// # Panic
223///
224/// This function panics if
225///
226/// - the proxy has already been destroyed,
227/// - the proxy is a wrapper,
228/// - the proxy is attached to a local queue and the current thread is not the thread in
229/// which the queue was created,
230/// - the proxy already has an event handler, or
231/// - the event handler accepts a `&mut T`, `T != ()`, and the queue that the proxy
232/// is attached to was not created with this data type.
233///
234/// This function also panics if the interface of the created handler is not the same as
235/// the interface of the proxy. However, this cannot happen if you're using the bindings
236/// generated by `wl-client-builder`.
237///
238/// # Example
239///
240/// ```
241/// # use std::sync::Arc;
242/// # use std::sync::atomic::AtomicBool;
243/// # use std::sync::atomic::Ordering::Relaxed;
244/// # use wl_client::{proxy, Libwayland};
245/// # use wl_client::test_protocols::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
246/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
247/// #
248/// let lib = Libwayland::open().unwrap();
249/// let con = lib.connect_to_default_display().unwrap();
250/// let queue = con.create_queue(c"");
251/// let display: WlDisplay = queue.display();
252/// let sync = display.sync();
253/// let done = Arc::new(AtomicBool::new(false));
254///
255/// // Attach the event handler.
256/// let done2 = done.clone();
257/// proxy::set_event_handler(&sync, WlCallback::on_done(move |_, _| {
258/// done2.store(true, Relaxed);
259/// }));
260///
261/// // Wait for the compositor to send the `done` message.
262/// queue.dispatch_roundtrip_blocking().unwrap();
263///
264/// // The event handler sets the value to `true`.
265/// assert!(done.load(Relaxed));
266/// ```
267#[inline]
268pub fn set_event_handler<P, H>(proxy: &P, handler: H)
269where
270 P: OwnedProxy,
271 P::Api: CreateEventHandler<H>,
272 <P::Api as CreateEventHandler<H>>::EventHandler: Send + 'static,
273{
274 get_owned(proxy).set_event_handler(P::Api::create_event_handler(handler));
275}
276
277/// Sets the `!Send` event handler of the proxy.
278///
279/// This function is the same as [`set_event_handler`] except that the event handler does
280/// not have to implement [`Send`] and the queue of the proxy must be a
281/// [local queue](Connection::create_local_queue).
282///
283/// # Panic
284///
285/// This function panics whenever [`set_event_handler`] panics and also if the queue of
286/// the proxy is not a local queue.
287///
288/// # Example
289///
290/// ```
291/// # use std::cell::Cell;
292/// # use std::rc::Rc;
293/// # use std::sync::atomic::Ordering::Relaxed;
294/// # use wl_client::{proxy, Libwayland};
295/// # use wl_client::test_protocols::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
296/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
297/// #
298/// let lib = Libwayland::open().unwrap();
299/// let con = lib.connect_to_default_display().unwrap();
300/// let queue = con.create_local_queue(c"");
301/// let display: WlDisplay = queue.display();
302/// let sync = display.sync();
303/// let done = Rc::new(Cell::new(false));
304///
305/// // Attach the event handler.
306/// let done2 = done.clone();
307/// proxy::set_event_handler_local(&sync, WlCallback::on_done(move |_, _| {
308/// done2.set(true);
309/// }));
310///
311/// // Wait for the compositor to send the `done` message.
312/// queue.dispatch_roundtrip_blocking().unwrap();
313///
314/// // The event handler sets the value to `true`.
315/// assert!(done.get());
316/// ```
317#[inline]
318pub fn set_event_handler_local<P, H>(proxy: &P, handler: H)
319where
320 P: OwnedProxy,
321 P::Api: CreateEventHandler<H>,
322 <P::Api as CreateEventHandler<H>>::EventHandler: 'static,
323{
324 get_owned(proxy).set_event_handler_local(P::Api::create_event_handler(handler));
325}
326
327/// Sets the event handler of the proxy to ignore all events.
328///
329/// This can be used in the following situation:
330///
331/// - The application is not interested in events from this proxy.
332/// - But the interface has events that contain file descriptors or create new proxies.
333///
334/// Not setting any event handler would cause the file descriptors and new proxies to be
335/// leaked. Using this function will ensure that all resources are released.
336///
337/// # Example
338///
339/// ```
340/// # use wl_client::{proxy, Libwayland};
341/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
342/// #
343/// let lib = Libwayland::open().unwrap();
344/// let con = lib.connect_to_default_display().unwrap();
345/// let queue = con.create_queue(c"queue name");
346/// let display: WlDisplay = queue.display();
347///
348/// let sync = display.sync();
349/// proxy::set_event_handler_no_op(&sync);
350/// ```
351#[inline]
352pub fn set_event_handler_no_op<P>(proxy: &P)
353where
354 P: OwnedProxy,
355{
356 get_owned(proxy).set_event_handler(P::NO_OP_EVENT_HANDLER);
357}
358
359/// Locks the proxy for concurrent destruction.
360///
361/// If the proxy is not already destroyed, holding this lock will prevent other threads
362/// from destroying it.
363///
364/// Trying to destroy the proxy from this thread while holding this lock will deadlock.
365///
366/// This lock only locks out concurrent destruction. Multiple threads can acquire this
367/// lock at the same time.
368///
369/// # Example
370///
371/// ```
372/// # use std::{ptr, thread};
373/// # use std::sync::{Arc, Barrier};
374/// # use std::time::Duration;
375/// # use wl_client::{proxy, Libwayland};
376/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
377/// #
378/// let lib = Libwayland::open().unwrap();
379/// let con = lib.connect_to_default_display().unwrap();
380/// let queue = con.create_queue(c"");
381/// let display: WlDisplay = queue.display();
382///
383/// // Create a wl_callback that we will destroy in another thread.
384/// let sync1 = display.sync();
385/// let sync2 = sync1.clone();
386///
387/// // Lock the proxy to prevent the other thread from destroying it.
388/// let lock = proxy::lock(&*sync1);
389///
390/// // Create a barrier to synchronize with the other thread.
391/// let barrier1 = Arc::new(Barrier::new(2));
392/// let barrier2 = barrier1.clone();
393///
394/// thread::spawn(move || {
395/// // This will block until the main thread has released the lock.
396/// proxy::destroy(&sync2);
397/// barrier2.wait();
398/// });
399///
400/// // Sleep for a second to demonstrate that the proxy::destroy does in fact not proceed.
401/// thread::sleep(Duration::from_secs(1));
402///
403/// // The other spawned thread has not yet destroyed the proxy.
404/// assert!(lock.wl_proxy().is_some());
405/// // Drop the lock to let the other thread proceed.
406/// drop(lock);
407///
408/// // Wait for the other thread to run to completion.
409/// barrier1.wait();
410///
411/// // The proxy is now destroyed.
412/// assert!(proxy::wl_proxy(&*sync1).is_none());
413/// ```
414pub fn lock(proxy: &impl UntypedBorrowedProxyWrapper) -> BorrowedProxyLock<'_> {
415 get_ref(proxy).lock()
416}
417
418/// Returns the `wl_proxy` pointer of a proxy.
419///
420/// This function returns a null pointer if the proxy has already been destroyed.
421///
422/// If this function returns a non-null pointer, the proxy might still get invalidated at
423/// any time when another thread destroys the proxy. Consider using [`lock`] instead.
424///
425/// # Example
426///
427/// ```
428/// # use std::ptr;
429/// # use wl_client::{proxy, Libwayland};
430/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
431/// let lib = Libwayland::open().unwrap();
432/// let con = lib.connect_to_default_display().unwrap();
433/// let queue = con.create_queue(c"");
434/// let display: WlDisplay = queue.display();
435/// assert!(proxy::wl_proxy(&*display).is_some());
436/// ```
437#[inline]
438pub fn wl_proxy(proxy: &impl UntypedBorrowedProxyWrapper) -> Option<NonNull<ffi::wl_proxy>> {
439 get_ref(proxy).wl_proxy()
440}
441
442/// Returns the wayland object ID of a proxy.
443///
444/// If the proxy has already been destroyed, this function returns either the original
445/// ID or 0.
446///
447/// # Example
448///
449/// ```
450/// # use wl_client::{proxy, Libwayland};
451/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
452/// let lib = Libwayland::open().unwrap();
453/// let con = lib.connect_to_default_display().unwrap();
454/// let queue = con.create_queue(c"");
455///
456/// let display: WlDisplay = queue.display();
457/// assert_eq!(proxy::id(&*display), 1);
458/// ```
459#[inline]
460pub fn id(proxy: &impl UntypedBorrowedProxyWrapper) -> u32 {
461 get_ref(proxy).id()
462}
463
464/// Returns the version of this proxy object.
465///
466/// The version of the display object is always 0.
467///
468/// # Panic
469///
470/// Panics if the proxy is already destroyed.
471///
472/// # Example
473///
474/// ```
475/// # use wl_client::{proxy, Libwayland};
476/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
477/// let lib = Libwayland::open().unwrap();
478/// let con = lib.connect_to_default_display().unwrap();
479/// let queue = con.create_queue(c"");
480///
481/// let display: WlDisplay = queue.display();
482/// assert_eq!(proxy::version(&*display), 0);
483/// ```
484#[inline]
485pub fn version(proxy: &impl UntypedBorrowedProxyWrapper) -> u32 {
486 get_ref(proxy).version()
487}
488
489/// Returns the queue of a proxy.
490///
491/// # Example
492///
493/// ```
494/// # use wl_client::{proxy, Libwayland};
495/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
496/// let lib = Libwayland::open().unwrap();
497/// let con = lib.connect_to_default_display().unwrap();
498///
499/// let queue = con.create_queue(c"");
500/// let display: WlDisplay = queue.display();
501/// assert_eq!(proxy::queue(&display), &*queue);
502/// ```
503#[inline]
504pub fn queue(proxy: &impl UntypedOwnedProxyWrapper) -> &Queue {
505 get_owned(proxy).queue()
506}
507
508/// Returns whether this proxy is destroyed.
509///
510/// The proxy being destroyed and the wayland object being destroyed are two separate
511/// properties. A proxy can be destroyed even if the wayland object is not yet destroyed
512/// and vice versa.
513///
514/// In a multi-threaded application, a proxy might get destroyed immediately after this
515/// function returns `false`. You can use [`lock`] to keep a proxy alive for a while.
516///
517/// # Example
518///
519/// ```
520/// # use wl_client::{proxy, Libwayland};
521/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
522/// #
523/// let lib = Libwayland::open().unwrap();
524/// let con = lib.connect_to_default_display().unwrap();
525/// let queue = con.create_queue(c"");
526/// let display: WlDisplay = queue.display();
527///
528/// let sync = display.sync();
529/// assert!(proxy::is_not_destroyed(&*sync));
530///
531/// proxy::destroy(&sync);
532/// assert!(proxy::is_destroyed(&*sync));
533/// ```
534#[inline]
535pub fn is_destroyed(proxy: &impl UntypedBorrowedProxyWrapper) -> bool {
536 wl_proxy(proxy).is_none()
537}
538
539/// Returns whether this proxy is not destroyed.
540///
541/// This is the same as `!is_destroyed(proxy)`.
542#[inline]
543pub fn is_not_destroyed(proxy: &impl UntypedBorrowedProxyWrapper) -> bool {
544 !is_destroyed(proxy)
545}