Skip to main content

wl_client/queue/
with_data.rs

1use crate::Connection;
2use crate::Queue;
3use crate::QueueOwner;
4#[expect(unused_imports)]
5use crate::queue::QueueData;
6use crate::utils::block_on::block_on;
7use std::any::TypeId;
8use std::any::type_name;
9use std::ffi::CStr;
10use std::fmt::Debug;
11use std::fmt::Formatter;
12use std::io;
13use std::marker::PhantomData;
14use std::ops::Deref;
15use std::ptr;
16
17#[cfg(test)]
18mod tests;
19
20/// An adapter for [`Queue`]s with mutable data.
21///
22/// This type is returned by [`Connection::create_queue_with_data`] and
23/// [`Connection::create_local_queue_with_data`] and can also be created from any queue
24/// by calling [`Queue::with_data`].
25///
26/// This type must be used to dispatch queues that were created with one of the two
27/// functions above. It derefs to [`Queue`] but re-declares all of the dispatching
28/// functions to also accept a `&mut T` that will be passed to the event handlers.
29///
30/// # Example
31///
32/// ```
33/// # use wl_client::{proxy, Libwayland};
34/// # use wl_client::test_protocols_data::core::wl_callback::WlCallback;
35/// # use wl_client::test_protocols_data::core::wl_display::WlDisplay;
36/// #
37/// let lib = Libwayland::open().unwrap();
38/// let con = lib.connect_to_default_display().unwrap();
39/// let (_queue, queue) = con.create_queue_with_data::<State>(c"queue name");
40///
41/// struct State {
42///     done: bool,
43/// }
44/// let mut state = State {
45///     done: false,
46/// };
47///
48/// let sync = queue.display::<WlDisplay>().sync();
49/// proxy::set_event_handler(&sync, WlCallback::on_done(|state: &mut State, _, _| {
50///     state.done = true;
51/// }));
52/// queue.dispatch_roundtrip_blocking(&mut state).unwrap();
53/// assert!(state.done);
54/// ```
55pub struct QueueWithData<T>
56where
57    T: 'static,
58{
59    /// The underlying queue. We ensure the following invariant: Either
60    /// [QueueData::mut_data_type] is `None` or it is the type ID of `T`.
61    queue: Queue,
62    _phantom: PhantomData<fn(&mut T)>,
63}
64
65impl Connection {
66    /// Creates a new queue with mutable data.
67    ///
68    /// This function is the same as [`Connection::create_queue`] except that event
69    /// handlers attached to this queue can receive a `&mut T`. When dispatching the queue,
70    /// a `&mut T` must be passed into one of the dispatcher functions of
71    /// [`QueueWithData`]. The dispatcher functions declared on [`Queue`] cannot be used
72    /// to dispatch this queue.
73    ///
74    /// # Example
75    ///
76    /// ```
77    /// # use wl_client::Libwayland;
78    /// #
79    /// let lib = Libwayland::open().unwrap();
80    /// let con = lib.connect_to_default_display().unwrap();
81    /// let (_queue_owner, _queue) = con.create_queue_with_data::<State>(c"queue name");
82    ///
83    /// struct State {
84    ///     // ...
85    /// }
86    /// ```
87    pub fn create_queue_with_data<T>(&self, name: &CStr) -> (QueueOwner, QueueWithData<T>)
88    where
89        T: 'static,
90    {
91        let owner =
92            self.create_queue2(name, false, Some(TypeId::of::<T>()), Some(type_name::<T>()));
93        let queue = owner.with_data();
94        (owner, queue)
95    }
96
97    /// Creates a new queue with mutable data.
98    ///
99    /// This function is the same as [`Connection::create_local_queue`] except that event
100    /// handlers attached to this queue can receive a `&mut T`. When dispatching the queue,
101    /// a `&mut T` must be passed into one of the dispatcher functions of
102    /// [`QueueWithData`]. The dispatcher functions declared on [`Queue`] cannot be used
103    /// to dispatch this queue.
104    ///
105    /// # Example
106    ///
107    /// ```
108    /// # use wl_client::Libwayland;
109    /// #
110    /// let lib = Libwayland::open().unwrap();
111    /// let con = lib.connect_to_default_display().unwrap();
112    /// let (_queue_owner, _queue) = con.create_local_queue_with_data::<State>(c"queue name");
113    ///
114    /// struct State {
115    ///     // ...
116    /// }
117    /// ```
118    pub fn create_local_queue_with_data<T>(&self, name: &CStr) -> (QueueOwner, QueueWithData<T>)
119    where
120        T: 'static,
121    {
122        let owner = self.create_queue2(name, true, Some(TypeId::of::<T>()), Some(type_name::<T>()));
123        let queue = owner.with_data();
124        (owner, queue)
125    }
126}
127
128impl Queue {
129    /// Creates an adapter for queues with mutable data.
130    ///
131    /// If the queue was created with [`Connection::create_queue_with_data`] or
132    /// [`Connection::create_local_queue_with_data`], then this function can only be used
133    /// with the same `T` that was used in those function calls.
134    ///
135    /// For convenience, if this queue was created without data, this function can be
136    /// used with any `T`.
137    ///
138    /// # Panic
139    ///
140    /// This function panics if this queue
141    /// - was created with [`Connection::create_queue_with_data`] or
142    ///   [`Connection::create_local_queue_with_data`], and
143    /// - it was created with a different data type.
144    pub fn with_data<T>(&self) -> QueueWithData<T>
145    where
146        T: 'static,
147    {
148        let d = &*self.queue_data;
149        if d.mut_data_type.is_some() && d.mut_data_type != Some(TypeId::of::<T>()) {
150            let rn = type_name::<T>();
151            panic!(
152                "This queue only supports mutable data of type `{}` but the \
153                requested type is `{rn}`",
154                d.mut_data_type_name.unwrap(),
155            );
156        }
157        QueueWithData {
158            queue: self.clone(),
159            _phantom: Default::default(),
160        }
161    }
162
163    /// Returns the type of mutable data required when dispatching this queue.
164    pub(crate) fn mut_data_type(&self) -> (Option<TypeId>, Option<&'static str>) {
165        let d = &*self.queue_data;
166        (d.mut_data_type, d.mut_data_type_name)
167    }
168
169    /// Returns the non-null mutable data pointer.
170    ///
171    /// When libwayland dispatches the event handler of a proxy attached to this queue,
172    /// the returned pointer can be dereferenced to `&mut T` where `T` is the type
173    /// returned by [`proxy::low_level::EventHandler::mutable_type`] or `()` if
174    /// `mutable_type` returns `None`.
175    ///
176    /// (It is up to the caller to ensure that the pointer is only dereferenced according
177    /// to the requirements of stacked borrows.)
178    ///
179    /// # Safety
180    ///
181    /// - The queue mutex must be held.
182    pub(crate) unsafe fn data(&self) -> *mut u8 {
183        // SAFETY: - the requirement is forwarded to the caller
184        //         - event handlers are only ever dispatched from within
185        //           `dispatch_pending_internal` and that function is the only code that
186        //           modifies this field
187        //         - if EventHandler::mutable_type is Some and not TypeId::of::<()>, then
188        //           `set_event_handler3` has checked that it is the same as the
189        //           `mut_data_type` of this queue.
190        //         - therefore the safety requirements of `dispatch_pending_internal`
191        //           require that the pointer stored in `mut_data` is `&mut T` where `T`
192        //           is the type returned by EventHandler::mutable_type.
193        //         - if this is being called from an event handler and there is another
194        //           event handler invocation of this queue further up in the stack,
195        //           then there must another invocation of `dispatch_pending_internal`
196        //           between these two stack entries and `dispatch_pending_internal` has
197        //           set the pointer to a fresh pointer that satisfies stacked borrows.
198        unsafe { self.queue_data.mut_data.get().0 }
199    }
200}
201
202impl<T> QueueWithData<T>
203where
204    T: 'static,
205{
206    /// Blocks the current thread until at least one event has been dispatched.
207    ///
208    /// This function is the same as [`Queue::dispatch_blocking`] but accepts a `&mut T`
209    /// that will be passed to event handlers.
210    ///
211    /// # Panic
212    ///
213    /// - Panics if this is a [local queue](Connection::create_local_queue) and the current
214    ///   thread is not the thread that this queue was created in.
215    ///
216    /// # Example
217    ///
218    /// ```
219    /// # use wl_client::Libwayland;
220    /// # use wl_client::test_protocols_data::core::wl_display::WlDisplay;
221    /// #
222    /// let lib = Libwayland::open().unwrap();
223    /// let con = lib.connect_to_default_display().unwrap();
224    /// let (_queue, queue) = con.create_queue_with_data::<State>(c"queue name");
225    ///
226    /// struct State {
227    ///     // ...
228    /// }
229    /// let mut state = State {
230    ///     // ...
231    /// };
232    ///
233    /// // For this example, ensure that the compositor sends an event in the near future.
234    /// let _sync = queue.display::<WlDisplay>().sync();
235    ///
236    /// queue.dispatch_blocking(&mut state).unwrap();
237    /// ```
238    pub fn dispatch_blocking(&self, data: &mut T) -> io::Result<u64> {
239        block_on(self.dispatch_async(data))
240    }
241
242    /// Completes when at least one event has been dispatched.
243    ///
244    /// This function is the same as [`QueueWithData::dispatch_blocking`] except that it is
245    /// async and does not block the current thread.
246    ///
247    /// # Panic
248    ///
249    /// - Panics if this is a [local queue](Connection::create_local_queue) and the thread
250    ///   polling the future is not the thread that this queue was created in.
251    ///
252    /// # Example
253    ///
254    /// ```
255    /// # use wl_client::Libwayland;
256    /// # use wl_client::test_protocols_data::core::wl_display::WlDisplay;
257    /// #
258    /// # tokio_test::block_on(async {
259    /// let lib = Libwayland::open().unwrap();
260    /// let con = lib.connect_to_default_display().unwrap();
261    /// let (_queue, queue) = con.create_queue_with_data(c"queue name");
262    ///
263    /// struct State {
264    ///     // ...
265    /// }
266    /// let mut state = State {
267    ///     // ...
268    /// };
269    ///
270    /// // For this example, ensure that the compositor sends an event in the near future.
271    /// let _sync = queue.display::<WlDisplay>().sync();
272    ///
273    /// queue.dispatch_async(&mut state).await.unwrap();
274    /// # });
275    /// ```
276    pub async fn dispatch_async(&self, data: &mut T) -> io::Result<u64> {
277        self.connection.wait_for_events(&[self]).await?;
278        self.dispatch_pending(data)
279    }
280
281    /// Blocks the current thread until the compositor has processed all previous requests
282    /// and all of its response events have been dispatched.
283    ///
284    /// This function is the same as [`Queue::dispatch_roundtrip_blocking`] but accepts a
285    /// `&mut T` that will be passed to event handlers.
286    ///
287    /// # Panic
288    ///
289    /// - Panics if this is a [local queue](Connection::create_local_queue) and the current
290    ///   thread is not the thread that this queue was created in.
291    ///
292    /// # Example
293    ///
294    /// ```
295    /// # use std::sync::Arc;
296    /// # use std::sync::atomic::AtomicBool;
297    /// # use std::sync::atomic::Ordering::Relaxed;
298    /// # use wl_client::{proxy, Libwayland};
299    /// # use wl_client::test_protocols_data::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
300    /// # use wl_client::test_protocols_data::core::wl_display::WlDisplay;
301    /// #
302    /// let lib = Libwayland::open().unwrap();
303    /// let con = lib.connect_to_default_display().unwrap();
304    /// let (_queue, queue) = con.create_queue_with_data::<State>(c"");
305    /// let display: WlDisplay = queue.display();
306    ///
307    /// struct State {
308    ///     done: bool,
309    /// }
310    /// let mut state = State {
311    ///     done: false,
312    /// };
313    ///
314    /// // send some messages to the compositor
315    /// let sync = display.sync();
316    /// proxy::set_event_handler(&sync, WlCallback::on_done(move |state: &mut State, _, _| {
317    ///     state.done = true;
318    /// }));
319    ///
320    /// // perform a roundtrip
321    /// queue.dispatch_roundtrip_blocking(&mut state).unwrap();
322    ///
323    /// // assert that we've received the response
324    /// assert!(state.done);
325    /// ```
326    pub fn dispatch_roundtrip_blocking(&self, data: &mut T) -> io::Result<()> {
327        block_on(self.dispatch_roundtrip_async(data))
328    }
329
330    /// Completes when the compositor has processed all previous requests and all of its
331    /// response events have been dispatched.
332    ///
333    /// This function is the same as [`QueueWithData::dispatch_roundtrip_blocking`] except
334    /// that it is async and does not block the current thread.
335    ///
336    /// If the future completes with `Ok(())`, then the future completes after (in the
337    /// sense of the C++ memory model) the event handlers of all previous events have been
338    /// invoked.
339    ///
340    /// # Panic
341    ///
342    /// - Panics if this is a [local queue](Connection::create_local_queue) and the current
343    ///   thread is not the thread that this queue was created in.
344    ///
345    /// # Example
346    ///
347    /// ```
348    /// # use std::sync::Arc;
349    /// # use std::sync::atomic::AtomicBool;
350    /// # use std::sync::atomic::Ordering::Relaxed;
351    /// # use wl_client::{proxy, Libwayland};
352    /// # use wl_client::test_protocols_data::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
353    /// # use wl_client::test_protocols_data::core::wl_display::WlDisplay;
354    /// #
355    /// # tokio_test::block_on(async {
356    /// let lib = Libwayland::open().unwrap();
357    /// let con = lib.connect_to_default_display().unwrap();
358    /// let (_queue, queue) = con.create_queue_with_data::<State>(c"queue name");
359    /// let display: WlDisplay = queue.display();
360    ///
361    /// struct State {
362    ///     done: bool,
363    /// }
364    /// let mut state = State {
365    ///     done: false,
366    /// };
367    ///
368    /// // send some messages to the compositor
369    /// let sync = display.sync();
370    /// proxy::set_event_handler(&sync, WlCallback::on_done(move |state: &mut State, _, _| {
371    ///     state.done = true;
372    /// }));
373    ///
374    /// // perform a roundtrip
375    /// queue.dispatch_roundtrip_async(&mut state).await.unwrap();
376    ///
377    /// // assert that we've received the response
378    /// assert!(state.done);
379    /// # });
380    /// ```
381    pub async fn dispatch_roundtrip_async(&self, data: &mut T) -> io::Result<()> {
382        self.dispatch_roundtrip_async_internal(|| self.dispatch_pending(data))
383            .await
384    }
385
386    /// Dispatches enqueued events.
387    ///
388    /// This function is the same as [`Queue::dispatch_pending`] but accepts a `&mut T`
389    /// that will be passed to event handlers.
390    ///
391    /// # Panic
392    ///
393    /// - Panics if this is a [local queue](Connection::create_local_queue) and the current
394    ///   thread is not the thread that this queue was created in.
395    ///
396    /// # Example
397    ///
398    /// ```
399    /// # use std::sync::Arc;
400    /// # use std::sync::atomic::AtomicBool;
401    /// # use std::sync::atomic::Ordering::Relaxed;
402    /// # use wl_client::{proxy, Libwayland};
403    /// # use wl_client::test_protocol_helpers::callback;
404    /// # use wl_client::test_protocols_data::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
405    /// # use wl_client::test_protocols_data::core::wl_display::WlDisplay;
406    /// #
407    /// # tokio_test::block_on(async {
408    /// let lib = Libwayland::open().unwrap();
409    /// let con = lib.connect_to_default_display().unwrap();
410    /// let (_queue, queue) = con.create_queue_with_data(c"queue name");
411    /// let display: WlDisplay = queue.display();
412    ///
413    /// struct State {
414    ///     done: bool,
415    /// }
416    /// let mut state = State {
417    ///     done: false,
418    /// };
419    ///
420    /// let sync = display.sync();
421    /// proxy::set_event_handler(&sync, WlCallback::on_done(move |state: &mut State, _, _| {
422    ///     state.done = true;
423    /// }));
424    ///
425    /// while !state.done {
426    ///     queue.wait_for_events().await.unwrap();
427    ///     // Dispatch the events.
428    ///     queue.dispatch_pending(&mut state).unwrap();
429    /// }
430    /// # });
431    /// ```
432    pub fn dispatch_pending(&self, data: &mut T) -> io::Result<u64> {
433        // SAFETY: - If mut_data_type is Some, then the invariants guarantee that it is
434        //           the type ID of T.
435        //         - Otherwise, `&mut T = &mut U`.
436        unsafe { self.dispatch_pending_internal(ptr::from_mut(data).cast()) }
437    }
438}
439
440impl<T> Clone for QueueWithData<T>
441where
442    T: 'static,
443{
444    fn clone(&self) -> Self {
445        Self {
446            queue: self.queue.clone(),
447            _phantom: Default::default(),
448        }
449    }
450}
451
452impl<T> Deref for QueueWithData<T>
453where
454    T: 'static,
455{
456    type Target = Queue;
457
458    fn deref(&self) -> &Self::Target {
459        &self.queue
460    }
461}
462
463impl<T> PartialEq for QueueWithData<T>
464where
465    T: 'static,
466{
467    fn eq(&self, other: &Self) -> bool {
468        self.queue == other.queue
469    }
470}
471
472impl<T> Eq for QueueWithData<T> where T: 'static {}
473
474impl<T> Debug for QueueWithData<T>
475where
476    T: 'static,
477{
478    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
479        Debug::fmt(&self.queue, f)
480    }
481}