wl_client/queue.rs
1use crate::Libwayland;
2use crate::QueueWatcher;
3use crate::connection::Connection;
4use crate::ffi::interface_compatible;
5use crate::ffi::wl_event_queue;
6use crate::ffi::wl_proxy;
7use crate::protocols::wayland::wl_callback::WlCallbackEventHandler;
8use crate::protocols::wayland::wl_callback::WlCallbackRef;
9use crate::protocols::wayland::wl_display::WlDisplay;
10use crate::proxy;
11use crate::proxy::BorrowedProxy;
12use crate::proxy::OwnedProxy;
13use crate::proxy::low_level::OwnedProxyRegistry;
14use crate::proxy::low_level::ProxyDataDestruction;
15use crate::proxy::low_level::UntypedOwnedProxy;
16use crate::proxy::low_level::check_dispatching_proxy;
17use crate::proxy::low_level::check_new_proxy;
18use crate::proxy::low_level::owned::DISPATCH_PANIC;
19use crate::utils::block_on::block_on;
20use crate::utils::reentrant_mutex::ReentrantMutex;
21use crate::utils::reentrant_mutex::ReentrantMutexGuard;
22use crate::utils::sync_cell::SyncCell;
23use crate::utils::sync_ptr::SyncNonNull;
24use crate::utils::sync_ptr::SyncPtr;
25use parking_lot::Mutex;
26use run_on_drop::on_drop;
27use std::any::TypeId;
28use std::cell::Cell;
29use std::cell::RefCell;
30use std::ffi::CStr;
31use std::ffi::CString;
32use std::fmt::Debug;
33use std::fmt::Formatter;
34use std::future::poll_fn;
35use std::io;
36use std::mem;
37use std::ops::Deref;
38use std::panic::resume_unwind;
39use std::pin::pin;
40use std::ptr;
41use std::ptr::NonNull;
42use std::sync::Arc;
43use std::task::Poll;
44use std::task::Waker;
45use std::thread::panicking;
46pub use with_data::QueueWithData;
47
48#[cfg(test)]
49mod tests;
50mod with_data;
51
52/// The owner of an event queue.
53///
54/// This is a thin wrapper around [`Queue`] and implements `Deref<Target = Queue>`.
55///
56/// The purpose of this type is to manage the lifetimes of proxies attached to queues.
57/// This is described in more detail in the documentation of [`Queue`].
58pub struct QueueOwner {
59 queue: Queue,
60}
61
62#[expect(clippy::doc_overindented_list_items)]
63/// An event queue.
64///
65/// An event queue stores events that have been sent by the compositor but whose callbacks
66/// have not yet been invoked. Invoking these callbacks is called _dispatching_ the queue.
67///
68/// A connection can have many queues that can be dispatched in parallel, but the events
69/// in a single queue are always dispatched in series. That is, the callback for the next
70/// event will not start executing until after the callback for the previous event.
71///
72/// New queues are created by calling [`Connection::create_local_queue`] or
73/// [`Connection::create_queue`].
74///
75/// # Proxies attached to a queue
76///
77/// Each proxy is attached to a queue. This queue is determined as follows:
78///
79/// - When [`Queue::display`] is called, the returned proxy is attached to that queue.
80/// - When [`Queue::wrap_proxy`] is called, the returned proxy is attached to that queue.
81/// - When a constructor request is called on an owned proxy `P`, e.g. `WlDisplay::sync`,
82/// the returned proxy is attached to the same queue as `P`.
83/// - When a constructor request is called on a borrowed proxy, e.g. `WlDisplayRef::sync`,
84/// the request takes a queue argument and the returned proxy is attached to that queue.
85///
86/// See the documentation of the [`proxy`] module for more information about proxies.
87///
88/// # Queue ownership
89///
90/// Each queue is owned by a [`QueueOwner`] which is returned when you call
91/// [`Connection::create_local_queue`] or [`Connection::create_queue`].
92///
93/// When a [`QueueOwner`] is dropped, it will automatically destroy _some_ of the proxies
94/// attached to the queue. This ensures that, when the [`QueueOwner`] is dropped, all
95/// reference cycles between proxies and their event handlers are broken and no memory is
96/// leaked. (Normally these cycles are broken when a destructor request is sent or the
97/// proxy is destroyed with [`proxy::destroy`], but for long-lived proxies, such as
98/// `wl_registry`, it is more convenient for this to happen automatically.)
99///
100/// A queue and the attached proxies should no longer be used after its [`QueueOwner`] has
101/// been dropped. Doing so might lead to panics or memory leaks.
102///
103/// To ensure that the [`QueueOwner`] is eventually dropped, the queue owner should never
104/// be reachable from an event handler.
105///
106/// ```
107/// # use wl_client::Libwayland;
108/// # use wl_client::Queue;
109/// # use wl_client::Connection;
110/// # use wl_client::QueueOwner;
111/// #
112/// fn main() {
113/// let lib = Libwayland::open().unwrap();
114/// let con = lib.connect_to_default_display().unwrap();
115/// let queue: QueueOwner = con.create_queue(c"queue name");
116///
117/// // the queue owner is stored on the stack and will be dropped when this function
118/// // returns
119/// application_logic(&queue);
120/// }
121/// #
122/// # fn application_logic(_queue: &Queue) {
123/// # }
124/// ```
125///
126/// # Local and non-local queues
127///
128/// Each queue is either local or non-local. Local queues are created with
129/// [`Connection::create_local_queue`]. Non-local queues are created with
130/// [`Connection::create_queue`].
131///
132/// Local queues have the following advantage:
133///
134/// - Event handlers attached to local queues do not have to implement [`Send`].
135///
136/// This allows such events handlers to contain `Rc<T>` where the same event handler on
137/// a non-local queue would have to use `Arc<T>`.
138///
139/// To ensure that these event handlers are not accessed or dropped on different threads,
140/// this advantage comes with the following restrictions:
141///
142/// - If a local queue was created on a thread `X`:
143/// - Event handlers must be attached on `X`.
144/// - The queue must only be dispatched on `X`.
145/// - The [`QueueOwner`] owning the queue must be dropped on `X`.
146/// - Proxies attached to the queue must only be destroyed on `X`.
147/// - Note: Proxies are destroyed when [`proxy::destroy`] is called *or* when a
148/// destructor request is sent *or* implicitly when the last reference to the proxy is
149/// dropped.
150///
151/// These restrictions are checked at runtime and will lead to panics if violated.
152///
153/// ```
154/// # use std::cell::Cell;
155/// # use std::rc::Rc;
156/// # use wl_client::{proxy, Libwayland};
157/// # use wl_client::test_protocols::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
158/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
159/// #
160/// let lib = Libwayland::open().unwrap();
161/// let con = lib.connect_to_default_display().unwrap();
162///
163/// // Create a local queue.
164/// let queue = con.create_local_queue(c"queue name");
165/// let display: WlDisplay = queue.display();
166///
167/// // Create an `Rc` and use it as an event handler.
168/// let done = Rc::new(Cell::new(false));
169/// let done2 = done.clone();
170/// let sync = display.sync();
171/// proxy::set_event_handler_local(&sync, WlCallback::on_done(move |_, _| done2.set(true)));
172///
173/// // Calling this function from another thread would panic.
174/// queue.dispatch_roundtrip_blocking().unwrap();
175///
176/// assert!(done.get());
177/// ```
178///
179/// # Locking
180///
181/// Each queue contains a re-entrant mutex. Re-entrant means that a thread that already
182/// holds the lock can acquire it again.
183///
184/// This lock can be acquired explicitly by calling [`Queue::lock_dispatch`]. You might
185/// want to use this function if you're dispatching the queue from multiple threads to
186/// avoid lock inversion. For example, consider the following situation:
187///
188/// - Thread 1: Acquires the lock of some shared state.
189/// - Thread 2: Starts dispatching and acquires the queue's re-entrant lock.
190/// - Thread 2: Calls an event handler which tries to lock the shared state and blocks.
191/// - Thread 1: Destroys a proxy which will implicitly acquire the queue's re-entrant lock.
192/// This deadlocks.
193///
194/// Instead, thread 1 could call [`Queue::lock_dispatch`] before locking the shared state
195/// to prevent the lock inversion.
196///
197/// This deadlock concern does not apply if the queue is only ever used from a single
198/// thread or if the queue is a local queue. If you need to poll the wayland socket on a
199/// separate thread, you can use [`BorrowedQueue::wait_for_events`] and send a message to
200/// the main thread when the future completes.
201///
202/// The lock is acquired implicitly in the following situations:
203///
204/// - The lock is held for the entirety of the following function calls:
205/// - [`Queue::dispatch_pending`]
206/// - [`QueueWithData::dispatch_pending`]
207/// - The lock is sometimes held during the following function calls but not while they
208/// are waiting for new events:
209/// - [`Queue::dispatch_blocking`]
210/// - [`Queue::dispatch_roundtrip_blocking`]
211/// - [`QueueWithData::dispatch_blocking`]
212/// - [`QueueWithData::dispatch_roundtrip_blocking`]
213/// - The lock is sometimes held while the futures produced by the following functions
214/// are being polled but not while they are waiting for new events:
215/// - [`Queue::dispatch_async`]
216/// - [`Queue::dispatch_roundtrip_async`]
217/// - [`QueueWithData::dispatch_async`]
218/// - [`QueueWithData::dispatch_roundtrip_async`]
219/// - The lock is held at the start and the end of the following function calls but not
220/// while invoking the callback:
221/// - [`Queue::dispatch_scope_blocking`]
222/// - The lock is sometimes held while the futures produced by the following functions
223/// are being polled but not while polling the future passed as an argument:
224/// - [`Queue::dispatch_scope_async`]
225/// - The lock is held while attaching an event handler to a proxy.
226/// - The lock is held when a proxy with an event handler is being destroyed:
227/// - When sending a destructor request.
228/// - When calling [`proxy::destroy`].
229/// - Implicitly when dropping the last reference to a proxy.
230/// - The lock is held while dropping the [`QueueOwner`] of the queue.
231#[derive(Clone)]
232pub struct Queue {
233 queue_data: Arc<QueueData>,
234}
235
236/// A borrowed event queue.
237///
238/// This type is a thin wrapper around a `wl_event_queue` pointer. If the pointer is a
239/// null pointer, this object refers to the default libwayland queue.
240///
241/// [`Queue`] implements `Deref<Target = BorrowedQueue>`.
242///
243/// This type can be used to safely interact with foreign queues. It guarantees that the
244/// contained pointer is either null or valid. This type can be passed into
245/// [`Connection::wait_for_events`] to wait for events to arrive on multiple queues
246/// in a race-free way.
247///
248/// You can construct a [`BorrowedQueue`] by calling
249///
250/// - [`Connection::borrow_default_queue`] or
251/// - [`Connection::borrow_foreign_queue`].
252///
253/// # Example
254///
255/// ```
256/// # use wl_client::Libwayland;
257/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
258/// #
259/// # tokio_test::block_on(async {
260/// let lib = Libwayland::open().unwrap();
261/// let con = lib.connect_to_default_display().unwrap();
262/// let queue1 = con.create_queue(c"queue name");
263/// let queue2 = con.create_queue(c"another queue");
264/// let default_queue = con.borrow_default_queue();
265/// # // ensure that some event arrives for this test
266/// # let sync = queue2.display::<WlDisplay>().sync();
267///
268/// con.wait_for_events(&[&queue1, &queue2, &default_queue]).await.unwrap();
269/// # });
270/// ```
271pub struct BorrowedQueue {
272 /// A reference to the connection that this queue belongs to. This also ensures
273 /// that the connection outlives the queue.
274 connection: Connection,
275 queue: Option<SyncNonNull<wl_event_queue>>,
276}
277
278/// A lock that prevents concurrent dispatching of a queue.
279///
280/// This lock can be acquired by calling [`Queue::lock_dispatch`].
281///
282/// See the description of [`Queue`] for why you might use this.
283///
284/// # Example
285///
286/// ```
287/// # use std::thread;
288/// # use wl_client::Libwayland;
289/// #
290/// let lib = Libwayland::open().unwrap();
291/// let con = lib.connect_to_default_display().unwrap();
292/// let queue = con.create_queue(c"queue name");
293///
294/// let lock = queue.lock_dispatch();
295///
296/// let thread = {
297/// let queue = queue.clone();
298/// thread::spawn(move || {
299/// // this dispatch will not start until the lock is dropped.
300/// queue.dispatch_roundtrip_blocking().unwrap();
301/// })
302/// };
303///
304/// // this dispatch starts immediately since the lock is re-entrant
305/// queue.dispatch_roundtrip_blocking().unwrap();
306///
307/// drop(lock);
308/// thread.join().unwrap();
309/// ```
310pub struct DispatchLock<'a> {
311 _lock: ReentrantMutexGuard<'a, DispatchData>,
312}
313
314struct QueueData {
315 /// A reference to the Libwayland singleton.
316 libwayland: &'static Libwayland,
317 /// The borrowed version of this queue for `Deref`.
318 borrowed: BorrowedQueue,
319 /// The name of the queue.
320 name: CString,
321 /// The native queue. This is always a valid pointer.
322 queue: SyncNonNull<wl_event_queue>,
323 /// This mutex protects
324 /// - the unsynchronized fields of any proxies attached to the queue
325 /// - the fields is_dispatching and to_destroy below
326 mutex: ReentrantMutex<DispatchData>,
327 /// The type of mutable data passed to event handlers attached to this queue. Each
328 /// event handler attached to this queue must
329 /// - not use any mutable data,
330 /// - use mutable data of type `()`, or
331 /// - use mutable data of this type.
332 mut_data_type: Option<TypeId>,
333 /// The name of mut_data_type, if any. This field is only used for panic messages.
334 mut_data_type_name: Option<&'static str>,
335 /// This field is protected by the mutex. It always contains a non-null pointer that
336 /// can be dereferenced to `&mut ()`. During dispatch, if `mut_data_type` is not
337 /// `None`, it contains a pointer to the data that was passed into `dispatch_pending`.
338 mut_data: SyncCell<SyncPtr<u8>>,
339 /// The registry for proxies that need manual destruction when the connection is
340 /// dropped.
341 owned_proxy_registry: OwnedProxyRegistry,
342}
343
344#[derive(Default)]
345struct DispatchData {
346 /// Contains whether the queue is currently dispatching. Note that, since
347 /// dispatching is protected by the mutex, this field is only ever accessed by a
348 /// single thread at a time.
349 is_dispatching: Cell<bool>,
350 /// If we are dispatching, this vector might contain work to run after the dispatch.
351 /// Protected against access from multiple threads by the mutex. These destructions
352 /// have the following invariant:
353 ///
354 /// - It must be safe to run the destruction once the queue is idle.
355 to_destroy_on_idle: RefCell<Vec<ProxyDataDestruction>>,
356}
357
358impl Deref for QueueOwner {
359 type Target = Queue;
360
361 fn deref(&self) -> &Self::Target {
362 &self.queue
363 }
364}
365
366impl Queue {
367 /// Returns a reference to the [`Libwayland`] singleton.
368 pub fn libwayland(&self) -> &'static Libwayland {
369 self.queue_data.libwayland
370 }
371
372 /// Returns the connection that this queue belongs to.
373 ///
374 /// # Example
375 ///
376 /// ```
377 /// # use wl_client::Libwayland;
378 /// #
379 /// let lib = Libwayland::open().unwrap();
380 /// let con = lib.connect_to_default_display().unwrap();
381 /// let queue = con.create_queue(c"queue name");
382 /// assert_eq!(queue.connection(), &con);
383 /// ```
384 pub fn connection(&self) -> &Connection {
385 &self.queue_data.borrowed.connection
386 }
387
388 /// Acquires the queue's re-entrant lock.
389 ///
390 /// See the description of [`Queue`] for why you might use this.
391 ///
392 /// # Example
393 ///
394 /// ```
395 /// # use std::thread;
396 /// # use wl_client::Libwayland;
397 /// #
398 /// let lib = Libwayland::open().unwrap();
399 /// let con = lib.connect_to_default_display().unwrap();
400 /// let queue = con.create_queue(c"queue name");
401 ///
402 /// let lock = queue.lock_dispatch();
403 ///
404 /// let thread = {
405 /// let queue = queue.clone();
406 /// thread::spawn(move || {
407 /// // this dispatch will not start until the lock is dropped.
408 /// queue.dispatch_roundtrip_blocking().unwrap();
409 /// })
410 /// };
411 ///
412 /// // this dispatch starts immediately since the lock is re-entrant
413 /// queue.dispatch_roundtrip_blocking().unwrap();
414 ///
415 /// drop(lock);
416 /// thread.join().unwrap();
417 /// ```
418 pub fn lock_dispatch(&self) -> DispatchLock<'_> {
419 DispatchLock {
420 _lock: self.queue_data.mutex.lock(),
421 }
422 }
423
424 /// Creates a wrapper proxy around the singleton `wl_display` object.
425 ///
426 /// The proxy is a wrapper and no event handler can be attached to it.
427 ///
428 /// The proxy is attached to this queue.
429 ///
430 /// # Panic
431 ///
432 /// Panics if the interface of `T` is not compatible with the `wl_display` interface.
433 ///
434 /// # Example
435 ///
436 /// ```
437 /// # use wl_client::{proxy, Libwayland};
438 /// # use wl_client::test_protocols::core::wl_display::WlDisplay;
439 /// #
440 /// let lib = Libwayland::open().unwrap();
441 /// let con = lib.connect_to_default_display().unwrap();
442 /// let queue = con.create_queue(c"queue name");
443 /// let display: WlDisplay = queue.display();
444 /// assert_eq!(proxy::queue(&display), &*queue);
445 /// assert_eq!(proxy::id(&*display), 1);
446 /// ```
447 pub fn display<T>(&self) -> T
448 where
449 T: OwnedProxy,
450 {
451 // SAFETY: OwnedProxy::WL_DISPLAY is always a valid interface.
452 let compatible = unsafe { interface_compatible(WlDisplay::WL_INTERFACE, T::WL_INTERFACE) };
453 if !compatible {
454 panic!("T::WL_INTERFACE is not compatible with wl_display");
455 }
456 // SAFETY: - wl_display always returns a valid object
457 // - we've just verified that T has a compatible interface
458 unsafe { self.wrap_wl_proxy(self.connection().wl_display().cast()) }
459 }
460
461 /// Returns whether this is a local queue.
462 ///
463 /// The documentation of the [`Queue`] type explains the difference between local and
464 /// non-local queues.
465 ///
466 /// # Example
467 ///
468 /// ```
469 /// # use wl_client::Libwayland;
470 /// #
471 /// let lib = Libwayland::open().unwrap();
472 /// let con = lib.connect_to_default_display().unwrap();
473 /// let queue1 = con.create_queue(c"non-local queue");
474 /// let queue2 = con.create_local_queue(c"local queue");
475 ///
476 /// assert!(queue1.is_non_local());
477 /// assert!(queue2.is_local());
478 /// ```
479 pub fn is_local(&self) -> bool {
480 self.queue_data.mutex.is_thread_local()
481 }
482
483 /// Returns whether this is *not* a local queue.
484 ///
485 /// This is the same as `!self.is_local()`.
486 ///
487 /// The documentation of the [`Queue`] type explains the difference between local and
488 /// non-local queues.
489 pub fn is_non_local(&self) -> bool {
490 !self.is_local()
491 }
492
493 /// Returns the `wl_event_queue` pointer of this queue.
494 ///
495 /// The returned pointer is valid for as long as this queue exists.
496 ///
497 /// You must not dispatch the queue except through the [`Queue`] interface.
498 /// Otherwise the behavior is undefined.
499 pub fn wl_event_queue(&self) -> NonNull<wl_event_queue> {
500 self.queue_data.queue.0
501 }
502
503 /// Returns the proxy registry of this queue.
504 ///
505 /// Proxies attached to this registry will be destroyed when the [`QueueOwner`] is
506 /// dropped.
507 pub(crate) fn owned_proxy_registry(&self) -> &OwnedProxyRegistry {
508 &self.queue_data.owned_proxy_registry
509 }
510
511 /// Runs the closure while holding the reentrant queue mutex.
512 pub(crate) fn run_locked<T>(&self, f: impl FnOnce() -> T) -> T {
513 self.run_locked_(|_| f())
514 }
515
516 /// Runs the closure while holding the reentrant queue mutex.
517 fn run_locked_<T>(&self, f: impl FnOnce(&DispatchData) -> T) -> T {
518 let lock = self.queue_data.mutex.lock();
519 f(&lock)
520 }
521
522 /// Runs the closure while holding the reentrant queue mutex. The is_dispatching
523 /// field will be set to true for the duration of the callback.
524 fn with_dispatch<T>(&self, f: impl FnOnce() -> T) -> T {
525 self.run_locked_(|dd| {
526 let is_dispatching = dd.is_dispatching.get();
527 dd.is_dispatching.set(true);
528 let ret = f();
529 dd.is_dispatching.set(is_dispatching);
530 if !is_dispatching {
531 let mut to_destroy = dd.to_destroy_on_idle.borrow_mut();
532 if to_destroy.len() > 0 {
533 let mut todo = mem::take(&mut *to_destroy);
534 drop(to_destroy);
535 for dd in todo.drain(..) {
536 // SAFETY: - For a thread to dispatch, it must
537 // 1. hold the queue lock
538 // 2. set is_dispatching
539 // - The queue lock is not dropped before the dispatch finishes
540 // and is_dispatching is not reset before then.
541 // - Since we're holding the queue lock and is_dispatching is false,
542 // we know that no dispatches are currently running.
543 // - If a future dispatch starts in this thread, it will happen
544 // after this line of code.
545 // - If a future dispatch starts on another thread, it will have
546 // to acquire the queue lock and will therefore happen after we
547 // release the lock below.
548 // - Therefore this queue is idle at this point.
549 // - to_destroy_on_idle contains only destructions that are safe
550 // to run while idle.
551 unsafe {
552 dd.run();
553 }
554 }
555 let mut to_destroy = dd.to_destroy_on_idle.borrow_mut();
556 mem::swap(&mut todo, &mut *to_destroy);
557 }
558 }
559 ret
560 })
561 }
562
563 /// Blocks the current thread until at least one event has been dispatched.
564 ///
565 /// If you are in an async context, then you might want to use
566 /// [`Queue::dispatch_async`] instead.
567 ///
568 /// This function should not be used when integrating with an existing, poll-based
569 /// event loop, as it might block indefinitely. Use [`Connection::create_watcher`] and
570 /// [`Queue::dispatch_pending`] instead.
571 ///
572 /// This function cannot be used if the queue was created with
573 /// [`Connection::create_queue_with_data`] or
574 /// [`Connection::create_local_queue_with_data`]. Use
575 /// [`QueueWithData::dispatch_blocking`] instead.
576 ///
577 /// The returned number is the number of events that have been dispatched by this
578 /// call. The number can be zero if another thread dispatched the events before us.
579 ///
580 /// # Panic
581 ///
582 /// - Panics if this is a [local queue](Connection::create_local_queue) and the current
583 /// thread is not the thread that this queue was created in.
584 /// - Panics if the queue was created with [`Connection::create_queue_with_data`] or
585 /// [`Connection::create_local_queue_with_data`].
586 ///
587 /// # Example
588 ///
589 /// ```
590 /// # use wl_client::Libwayland;
591 /// # use wl_client::test_protocols::core::wl_display::WlDisplay;
592 /// #
593 /// let lib = Libwayland::open().unwrap();
594 /// let con = lib.connect_to_default_display().unwrap();
595 /// let queue = con.create_queue(c"queue name");
596 ///
597 /// // For this example, ensure that the compositor sends an event in the near future.
598 /// let _sync = queue.display::<WlDisplay>().sync();
599 ///
600 /// queue.dispatch_blocking().unwrap();
601 /// ```
602 pub fn dispatch_blocking(&self) -> io::Result<u64> {
603 block_on(self.dispatch_async())
604 }
605
606 /// Completes when at least one event has been dispatched.
607 ///
608 /// This function is the same as [`Queue::dispatch_blocking`] except that it is async and does
609 /// not block the current thread.
610 ///
611 /// # Panic
612 ///
613 /// - Panics if this is a [local queue](Connection::create_local_queue) and the thread
614 /// polling the future is not the thread that this queue was created in.
615 /// - Panics if the queue was created with [`Connection::create_queue_with_data`] or
616 /// [`Connection::create_local_queue_with_data`].
617 ///
618 /// # Example
619 ///
620 /// ```
621 /// # use wl_client::Libwayland;
622 /// # use wl_client::test_protocols::core::wl_display::WlDisplay;
623 /// #
624 /// # tokio_test::block_on(async {
625 /// let lib = Libwayland::open().unwrap();
626 /// let con = lib.connect_to_default_display().unwrap();
627 /// let queue = con.create_queue(c"queue name");
628 ///
629 /// // For this example, ensure that the compositor sends an event in the near future.
630 /// let _sync = queue.display::<WlDisplay>().sync();
631 ///
632 /// queue.dispatch_async().await.unwrap();
633 /// # });
634 /// ```
635 pub async fn dispatch_async(&self) -> io::Result<u64> {
636 self.connection.wait_for_events(&[self]).await?;
637 self.dispatch_pending()
638 }
639
640 /// Dispatches enqueued events.
641 ///
642 /// This function does not read new events from the file descriptor.
643 ///
644 /// This function can be used together with [`BorrowedQueue::wait_for_events`] or
645 /// [`Queue::create_watcher`] to dispatch the queue in an async context or event loop
646 /// respectively.
647 ///
648 /// This function cannot be used if the queue was created with
649 /// [`Connection::create_queue_with_data`] or
650 /// [`Connection::create_local_queue_with_data`]. Use
651 /// [`QueueWithData::dispatch_pending`] instead.
652 ///
653 /// The returned number is the number of events that were dispatched.
654 ///
655 /// # Panic
656 ///
657 /// - Panics if this is a [local queue](Connection::create_local_queue) and the current
658 /// thread is not the thread that this queue was created in.
659 /// - Panics if the queue was created with [`Connection::create_queue_with_data`] or
660 /// [`Connection::create_local_queue_with_data`].
661 ///
662 /// # Example
663 ///
664 /// ```
665 /// # use std::sync::Arc;
666 /// # use std::sync::atomic::AtomicBool;
667 /// # use std::sync::atomic::Ordering::Relaxed;
668 /// # use wl_client::{proxy, Libwayland};
669 /// # use wl_client::test_protocol_helpers::callback;
670 /// # use wl_client::test_protocols::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
671 /// # use wl_client::test_protocols::core::wl_display::WlDisplay;
672 /// #
673 /// # tokio_test::block_on(async {
674 /// let lib = Libwayland::open().unwrap();
675 /// let con = lib.connect_to_default_display().unwrap();
676 /// let queue = con.create_queue(c"queue name");
677 /// let display: WlDisplay = queue.display();
678 ///
679 /// let done = Arc::new(AtomicBool::new(false));
680 /// let done2 = done.clone();
681 /// let sync = display.sync();
682 /// proxy::set_event_handler(&sync, WlCallback::on_done(move |_, _| {
683 /// done2.store(true, Relaxed);
684 /// }));
685 ///
686 /// while !done.load(Relaxed) {
687 /// queue.wait_for_events().await.unwrap();
688 /// // Dispatch the events.
689 /// queue.dispatch_pending().unwrap();
690 /// }
691 /// # });
692 /// ```
693 pub fn dispatch_pending(&self) -> io::Result<u64> {
694 let d = &*self.queue_data;
695 if d.mut_data_type.is_some() {
696 panic!(
697 "Queue requires mutable data of type `{}` to be dispatched",
698 d.mut_data_type_name.unwrap(),
699 );
700 }
701 // SAFETY: - We've just checked that `mut_data_type` is None and
702 // `&mut () = &mut U`.
703 unsafe { self.dispatch_pending_internal(ptr::from_mut(&mut ()).cast()) }
704 }
705
706 /// # Safety
707 ///
708 /// - If `self.mut_data_type` is Some, then `mut_data` must be a `&mut T` where
709 /// `T` has the type ID `self.mut_data_type`.
710 /// - Otherwise `mut_data` must be `&mut U` for any `U`.
711 unsafe fn dispatch_pending_internal(&self, mut_data: *mut u8) -> io::Result<u64> {
712 let d = &*self.queue_data;
713 let _resume_unwind = on_drop(|| {
714 if let Some(err) = DISPATCH_PANIC.take()
715 && !panicking()
716 {
717 resume_unwind(err);
718 }
719 });
720 let res = self.with_dispatch(|| {
721 let md = &self.queue_data.mut_data;
722 // SAFETY: - We're holding the queue lock.
723 // - If mut_data_type is Some, then mut_data is `&mut T` where T has
724 // the type ID mut_data_type.
725 let prev_mut_data = unsafe { md.replace(SyncPtr(mut_data)) };
726 let _reset_mut_data = on_drop(|| {
727 // SAFETY: - This closure runs before exiting the with_dispatch callback,
728 // so we're still holding the queue lock.
729 // - If this is a nested dispatch, then that dispatch had already
730 // started when we entered the with_dispatch callback, therefore
731 // prev_mut_data satisfies all of the requirements.
732 unsafe { md.set(prev_mut_data) }
733 });
734 // SAFETY: - by the invariants, the display and queue are valid
735 // - the queue was created from the display
736 // - we're inside with_dispatch which means that we're holding the
737 // reentrant queue mutex. by the invariants, this mutex protects
738 // the unsynchronized fields of the proxies.
739 unsafe {
740 d.libwayland.wl_display_dispatch_queue_pending(
741 d.borrowed.connection.wl_display().as_ptr(),
742 d.queue.as_ptr(),
743 )
744 }
745 });
746 if res == -1 {
747 return Err(io::Error::last_os_error());
748 }
749 assert!(res >= 0);
750 Ok(res as u64)
751 }
752
753 /// Blocks the current thread until the compositor has processed all previous requests
754 /// and all of its response events have been dispatched.
755 ///
756 /// If you are in an async context, then you might want to use
757 /// [`Queue::dispatch_roundtrip_async`] instead.
758 ///
759 /// Since this function usually returns quickly, you might use this function even
760 /// when integrating a wayland connection into an existing event loop and even in an
761 /// async context. For example, a library that creates buffers might use this function
762 /// during initialization to receive the full list of supported formats before
763 /// returning.
764 ///
765 /// This function cannot be used if the queue was created with
766 /// [`Connection::create_queue_with_data`] or
767 /// [`Connection::create_local_queue_with_data`]. Use
768 /// [`QueueWithData::dispatch_roundtrip_blocking`] instead.
769 ///
770 /// If this function returns `Ok(())`, then the function returns after (in the sense
771 /// of the C++ memory model) the event handlers of all previous events have been
772 /// invoked.
773 ///
774 /// # Panic
775 ///
776 /// - Panics if this is a [local queue](Connection::create_local_queue) and the current
777 /// thread is not the thread that this queue was created in.
778 /// - Panics if the queue was created with [`Connection::create_queue_with_data`] or
779 /// [`Connection::create_local_queue_with_data`].
780 ///
781 /// # Example
782 ///
783 /// ```
784 /// # use std::sync::Arc;
785 /// # use std::sync::atomic::AtomicBool;
786 /// # use std::sync::atomic::Ordering::Relaxed;
787 /// # use wl_client::{proxy, Libwayland};
788 /// # use wl_client::test_protocols::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
789 /// # use wl_client::test_protocols::core::wl_display::WlDisplay;
790 /// #
791 /// let lib = Libwayland::open().unwrap();
792 /// let con = lib.connect_to_default_display().unwrap();
793 /// let queue = con.create_queue(c"");
794 /// let display: WlDisplay = queue.display();
795 ///
796 /// // send some messages to the compositor
797 /// let done = Arc::new(AtomicBool::new(false));
798 /// let done2 = done.clone();
799 /// let sync = display.sync();
800 /// proxy::set_event_handler(&sync, WlCallback::on_done(move |_, _| {
801 /// done2.store(true, Relaxed);
802 /// }));
803 ///
804 /// // perform a roundtrip
805 /// queue.dispatch_roundtrip_blocking().unwrap();
806 ///
807 /// // assert that we've received the response
808 /// assert!(done.load(Relaxed));
809 /// ```
810 pub fn dispatch_roundtrip_blocking(&self) -> io::Result<()> {
811 block_on(self.dispatch_roundtrip_async())
812 }
813
814 /// Completes when the compositor has processed all previous requests and all of its
815 /// response events have been dispatched.
816 ///
817 /// This function is the same as [`Queue::dispatch_roundtrip_blocking`] except that it is async and does
818 /// not block the current thread.
819 ///
820 /// If the future completes with `Ok(())`, then the future completes after (in the
821 /// sense of the C++ memory model) the event handlers of all previous events have been
822 /// invoked.
823 ///
824 /// # Panic
825 ///
826 /// - Panics if this is a [local queue](Connection::create_local_queue) and the thread
827 /// polling the future is not the thread that this queue was created in.
828 /// - Panics if the queue was created with [`Connection::create_queue_with_data`] or
829 /// [`Connection::create_local_queue_with_data`].
830 ///
831 /// # Example
832 ///
833 /// ```
834 /// # use std::sync::Arc;
835 /// # use std::sync::atomic::AtomicBool;
836 /// # use std::sync::atomic::Ordering::Relaxed;
837 /// # use wl_client::{proxy, Libwayland};
838 /// # use wl_client::test_protocols::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
839 /// # use wl_client::test_protocols::core::wl_display::WlDisplay;
840 /// #
841 /// # tokio_test::block_on(async {
842 /// let lib = Libwayland::open().unwrap();
843 /// let con = lib.connect_to_default_display().unwrap();
844 /// let queue = con.create_queue(c"queue name");
845 /// let display: WlDisplay = queue.display();
846 ///
847 /// // send some messages to the compositor
848 /// let done = Arc::new(AtomicBool::new(false));
849 /// let done2 = done.clone();
850 /// let sync = display.sync();
851 /// proxy::set_event_handler(&sync, WlCallback::on_done(move |_, _| {
852 /// done2.store(true, Relaxed);
853 /// }));
854 ///
855 /// // perform a roundtrip
856 /// queue.dispatch_roundtrip_async().await.unwrap();
857 ///
858 /// // assert that we've received the response
859 /// assert!(done.load(Relaxed));
860 /// # });
861 /// ```
862 pub async fn dispatch_roundtrip_async(&self) -> io::Result<()> {
863 self.dispatch_roundtrip_async_internal(|| self.dispatch_pending())
864 .await
865 }
866
867 async fn dispatch_roundtrip_async_internal(
868 &self,
869 mut dispatch_pending: impl FnMut() -> io::Result<u64>,
870 ) -> io::Result<()> {
871 #[derive(Default)]
872 struct State {
873 ready: bool,
874 waker: Option<Waker>,
875 }
876
877 struct RoundtripEventHandler(Arc<Mutex<State>>);
878 impl WlCallbackEventHandler for RoundtripEventHandler {
879 fn done(&self, _slf: &WlCallbackRef, _callback_data: u32) {
880 let waker = {
881 let state = &mut *self.0.lock();
882 state.ready = true;
883 state.waker.take()
884 };
885 if let Some(waker) = waker {
886 waker.wake();
887 }
888 }
889 }
890
891 let state = Arc::new(Mutex::new(State::default()));
892
893 let _sync = self.run_locked(|| {
894 let sync = self.display::<WlDisplay>().sync();
895 proxy::set_event_handler(&sync, RoundtripEventHandler(state.clone()));
896 sync
897 });
898
899 // NOTE: A simple 1) check flag 2) wait for events loop would be incorrect here
900 // since another thread could dispatch the queue between these two steps,
901 // leaving us blocked even though the flag has already been set. Therefore
902 // we have to make sure that this task gets woken up whenever the flag is
903 // set.
904
905 self.connection.flush()?;
906 let queues = [&**self];
907 loop {
908 let fut = self.connection.wait_for_events_without_flush(&queues);
909 let mut fut = pin!(fut);
910 let ready = poll_fn(|ctx| {
911 let mut s = state.lock();
912 if s.ready {
913 return Poll::Ready(Ok(true));
914 }
915 if let Poll::Ready(res) = fut.as_mut().poll(ctx) {
916 return Poll::Ready(res.map(|_| false));
917 }
918 s.waker = Some(ctx.waker().clone());
919 Poll::Pending
920 })
921 .await?;
922 if ready {
923 return Ok(());
924 }
925 dispatch_pending()?;
926 }
927 }
928
929 /// Creates a wrapper for an existing proxy.
930 ///
931 /// The wrapper will be assigned to this queue. No event handler can be assigned to
932 /// the wrapper.
933 ///
934 /// # Panic
935 ///
936 /// - Panics if the proxy and this queue don't belong to the same `wl_display`.
937 /// - Panics if the proxy is already destroyed.
938 ///
939 /// # Example
940 ///
941 /// ```
942 /// # use wl_client::{proxy, Libwayland};
943 /// # use wl_client::test_protocols::core::wl_display::WlDisplay;
944 /// #
945 /// let lib = Libwayland::open().unwrap();
946 /// let con = lib.connect_to_default_display().unwrap();
947 ///
948 /// let queue1 = con.create_queue(c"queue name");
949 /// let display1: WlDisplay = queue1.display();
950 /// assert_eq!(proxy::queue(&display1), &*queue1);
951 ///
952 /// let queue2 = con.create_queue(c"second queue");
953 /// let display2 = queue2.wrap_proxy(&*display1);
954 /// assert_eq!(proxy::queue(&display2), &*queue2);
955 /// ```
956 pub fn wrap_proxy<P>(&self, proxy: &P) -> P::Owned
957 where
958 P: BorrowedProxy,
959 {
960 let lock = proxy::get_ref(proxy).lock();
961 let proxy = check_dispatching_proxy(lock.wl_proxy());
962 // SAFETY: - We've verified that the proxy is not null. UntypedBorrowedProxy
963 // requires that the pointer is valid in this case.
964 // - The interface of the proxy is compatible with P::Owned::WL_INTERFACE.
965 unsafe { self.wrap_wl_proxy(proxy) }
966 }
967
968 /// Creates a wrapper for an existing `wl_proxy`.
969 ///
970 /// The wrapper will be assigned to this queue. No event handler can be assigned to
971 /// the wrapper.
972 ///
973 /// If the `wl_proxy` already has a safe wrapper, the [`Queue::wrap_proxy`] function
974 /// can be used instead.
975 ///
976 /// # Panic
977 ///
978 /// - Panics if the proxy and this queue don't belong to the same `wl_display`.
979 ///
980 /// # Safety
981 ///
982 /// - `proxy` must be a valid pointer.
983 /// - `proxy` must have an interface compatible with `P::WL_INTERFACE`.
984 ///
985 /// # Example
986 ///
987 /// Some frameworks, e.g. winit, expose libwayland `wl_display` and `wl_surface`
988 /// pointers. These can be imported into this crate as follows:
989 ///
990 /// ```
991 /// # use std::ffi::c_void;
992 /// # use std::ptr::NonNull;
993 /// # use wl_client::{Libwayland, Queue};
994 /// # use wl_client::test_protocols::core::wl_surface::WlSurface;
995 /// #
996 /// unsafe fn wrap_foreign_surface(display: NonNull<c_void>, wl_surface: NonNull<c_void>) {
997 /// let lib = Libwayland::open().unwrap();
998 /// // SAFETY: ...
999 /// let con = unsafe { lib.wrap_borrowed_pointer(display.cast()).unwrap() };
1000 /// let queue = con.create_queue(c"queue name");
1001 /// // SAFETY: ...
1002 /// let surface: WlSurface = unsafe { queue.wrap_wl_proxy(wl_surface.cast()) };
1003 /// }
1004 /// ```
1005 pub unsafe fn wrap_wl_proxy<P>(&self, proxy: NonNull<wl_proxy>) -> P
1006 where
1007 P: OwnedProxy,
1008 {
1009 let d = &*self.queue_data;
1010 // SAFETY: - It's a requirement of this function that the proxy is a valid pointer.
1011 let display = unsafe { d.libwayland.wl_proxy_get_display(proxy.as_ptr()) };
1012 assert_eq!(display, d.borrowed.connection.wl_display().as_ptr());
1013 // SAFETY: - It's a requirement of this function that the proxy is a valid pointer.
1014 let wrapper: *mut wl_proxy = unsafe {
1015 d.libwayland
1016 .wl_proxy_create_wrapper(proxy.as_ptr().cast())
1017 .cast()
1018 };
1019 let wrapper = check_new_proxy(wrapper);
1020 // SAFETY: - we just created wrapper so it is valid
1021 // - queue is valid by the invariants
1022 // - the UntypedOwnedProxy created below will hold a reference to this queue
1023 // - the wrapper belongs to the same display as the proxy, and we've
1024 // verified above that the proxy has the same display as this queue
1025 unsafe {
1026 d.libwayland
1027 .wl_proxy_set_queue(wrapper.as_ptr(), d.queue.as_ptr());
1028 }
1029 // SAFETY: - we just created wrapper so it is valid
1030 // - wrapper is a wrapper so it doesn't have an event handler
1031 // - we have ownership of wrapper and hand it over
1032 // - we just assigned self as the queue of wrapper
1033 // - the interface is none since this is a wrapper
1034 let wrapper = unsafe { UntypedOwnedProxy::from_wrapper_wl_proxy(self, wrapper) };
1035 // SAFETY: - the requirement is forwarded to the caller
1036 unsafe { proxy::low_level::from_untyped_owned(wrapper) }
1037 }
1038
1039 /// Schedules a destruction to be run once the queue has become idle.
1040 ///
1041 /// Idle here means that
1042 ///
1043 /// 1. there are no dispatches running, and
1044 /// 2. all future dispatches happen after this function call.
1045 ///
1046 /// # Panic
1047 ///
1048 /// Panics if this is a local queue and the current thread is not the thread that this
1049 /// queue was created in.
1050 ///
1051 /// # Safety
1052 ///
1053 /// - It must be safe to run the destruction once the queue is idle.
1054 pub(crate) unsafe fn run_destruction_on_idle(&self, destruction: ProxyDataDestruction) {
1055 self.run_locked_(|dd| {
1056 if dd.is_dispatching.get() {
1057 dd.to_destroy_on_idle.borrow_mut().push(destruction);
1058 } else {
1059 // SAFETY: - For a thread to dispatch, it must
1060 // 1. hold the queue lock
1061 // 2. set is_dispatching
1062 // - The queue lock is not dropped before the dispatch finishes
1063 // and is_dispatching is not reset before then.
1064 // - Since we're holding the queue lock and is_dispatching is false,
1065 // we know that no dispatches are currently running.
1066 // - If a future dispatch starts in this thread, it will happen
1067 // after this line of code.
1068 // - If a future dispatch starts on another thread, it will have
1069 // to acquire the queue lock and will therefore happen after we
1070 // release the lock below.
1071 // - By the pre-conditions of this function, it is safe to run
1072 // the destruction at this point.
1073 unsafe {
1074 destruction.run();
1075 }
1076 }
1077 });
1078 }
1079
1080 /// Creates a [`QueueWatcher`] for event-loop integration.
1081 ///
1082 /// This is a shorthand for calling [`Connection::create_watcher`] with a queue list
1083 /// containing exactly this queue.
1084 pub fn create_watcher(&self) -> io::Result<QueueWatcher> {
1085 self.connection.create_watcher(&[self], [])
1086 }
1087}
1088
1089impl BorrowedQueue {
1090 /// Creates a [`QueueWatcher`] for event-loop integration.
1091 ///
1092 /// This is a shorthand for calling [`Connection::create_watcher`] with a queue list
1093 /// containing exactly this queue.
1094 ///
1095 /// The [`BorrowedQueue`] is dropped when the last clone of the [`QueueWatcher`] is
1096 /// dropped.
1097 pub fn create_watcher(self) -> io::Result<QueueWatcher> {
1098 let con = self.connection.clone();
1099 con.create_watcher(&[], [self])
1100 }
1101
1102 /// Completes when there are new events in this queue.
1103 ///
1104 /// When this function returns `Ok(())`, this queue has an event queued.
1105 ///
1106 /// This is a shorthand for calling [`Connection::wait_for_events`] with a
1107 /// queue list consisting of exactly this queue.
1108 ///
1109 /// # Example
1110 ///
1111 /// ```
1112 /// # use std::future::pending;
1113 /// # use std::sync::Arc;
1114 /// # use std::sync::atomic::AtomicBool;
1115 /// # use std::sync::atomic::Ordering::{Acquire, Release};
1116 /// # use wl_client::{proxy, Libwayland};
1117 /// # use wl_client::test_protocols::core::wl_callback::{WlCallback, WlCallbackEventHandler, WlCallbackRef};
1118 /// # use wl_client::test_protocols::core::wl_display::WlDisplay;
1119 /// #
1120 /// # tokio_test::block_on(async {
1121 /// let lib = Libwayland::open().unwrap();
1122 /// let con = lib.connect_to_default_display().unwrap();
1123 /// let queue = con.create_queue(c"queue name");
1124 /// let display: WlDisplay = queue.display();
1125 ///
1126 /// let done = Arc::new(AtomicBool::new(false));
1127 /// let done2 = done.clone();
1128 /// let sync = display.sync();
1129 /// proxy::set_event_handler(&sync, WlCallback::on_done(move |_, _| {
1130 /// done2.store(true, Release);
1131 /// }));
1132 ///
1133 /// while !done.load(Acquire) {
1134 /// queue.wait_for_events().await.unwrap();
1135 /// queue.dispatch_pending().unwrap();
1136 /// }
1137 /// # });
1138 /// ```
1139 pub async fn wait_for_events(&self) -> io::Result<()> {
1140 self.connection.wait_for_events(&[self]).await
1141 }
1142
1143 /// Returns the `wl_event_queue` representing this queue.
1144 ///
1145 /// This function returns `None` if and only if this queue is the default queue of the
1146 /// connection.
1147 ///
1148 /// The returned pointer, if any, remains valid as long as this object exists.
1149 ///
1150 /// # Example
1151 ///
1152 /// ```
1153 /// # use wl_client::Libwayland;
1154 /// #
1155 /// let lib = Libwayland::open().unwrap();
1156 /// let con = lib.connect_to_default_display().unwrap();
1157 /// let queue = con.create_queue(c"queue name");
1158 /// let default_queue = con.borrow_default_queue();
1159 ///
1160 /// assert_eq!((**queue).wl_event_queue(), Some(queue.wl_event_queue()));
1161 /// assert_eq!(default_queue.wl_event_queue(), None);
1162 /// ```
1163 pub fn wl_event_queue(&self) -> Option<NonNull<wl_event_queue>> {
1164 self.queue.map(|q| q.0)
1165 }
1166
1167 pub(crate) fn connection(&self) -> &Connection {
1168 &self.connection
1169 }
1170}
1171
1172impl Connection {
1173 /// Creates a new queue.
1174 ///
1175 /// The new queue is not a local queue. It can be dispatched from any thread. Event
1176 /// handlers attached to this queue must implement [`Send`]. See the documentation of
1177 /// [`Queue`] for a description of local and non-local queues.
1178 ///
1179 /// # Example
1180 ///
1181 /// ```
1182 /// # use wl_client::Libwayland;
1183 /// #
1184 /// let lib = Libwayland::open().unwrap();
1185 /// let con = lib.connect_to_default_display().unwrap();
1186 /// let _queue = con.create_queue(c"queue name");
1187 /// ```
1188 pub fn create_queue(&self, name: &CStr) -> QueueOwner {
1189 self.create_queue2(name, false, None, None)
1190 }
1191
1192 /// Creates a new local queue.
1193 ///
1194 /// The new queue is a local queue. It can only be dispatched from the thread that
1195 /// called this function. See the documentation of [`Queue`] for a description of
1196 /// local and non-local queues.
1197 ///
1198 /// # Example
1199 ///
1200 /// ```
1201 /// # use wl_client::Libwayland;
1202 /// #
1203 /// let lib = Libwayland::open().unwrap();
1204 /// let con = lib.connect_to_default_display().unwrap();
1205 /// let _queue = con.create_local_queue(c"queue name");
1206 /// ```
1207 pub fn create_local_queue(&self, name: &CStr) -> QueueOwner {
1208 self.create_queue2(name, true, None, None)
1209 }
1210
1211 /// Creates a new queue.
1212 fn create_queue2(
1213 &self,
1214 name: &CStr,
1215 local: bool,
1216 mut_data_type: Option<TypeId>,
1217 mut_data_type_name: Option<&'static str>,
1218 ) -> QueueOwner {
1219 // SAFETY: The display is valid and queue_name is a CString.
1220 let queue = unsafe {
1221 self.libwayland()
1222 .wl_display_create_queue_with_name(self.wl_display().as_ptr(), name.as_ptr())
1223 };
1224 let queue = NonNull::new(queue).unwrap();
1225 QueueOwner {
1226 queue: Queue {
1227 queue_data: Arc::new(QueueData {
1228 libwayland: self.libwayland(),
1229 borrowed: BorrowedQueue {
1230 connection: self.clone(),
1231 queue: Some(SyncNonNull(queue)),
1232 },
1233 name: name.to_owned(),
1234 queue: SyncNonNull(queue),
1235 mutex: match local {
1236 true => ReentrantMutex::new_thread_local(Default::default()),
1237 false => ReentrantMutex::new_shared(Default::default()),
1238 },
1239 mut_data_type,
1240 mut_data_type_name,
1241 mut_data: SyncCell::new(SyncPtr(ptr::from_mut(&mut ()).cast())),
1242 owned_proxy_registry: Default::default(),
1243 }),
1244 },
1245 }
1246 }
1247
1248 /// Creates a [`BorrowedQueue`] representing the default queue.
1249 pub fn borrow_default_queue(&self) -> BorrowedQueue {
1250 BorrowedQueue {
1251 connection: self.clone(),
1252 queue: None,
1253 }
1254 }
1255
1256 /// Creates a [`BorrowedQueue`] representing a `wl_event_queue` pointer.
1257 ///
1258 /// # Safety
1259 ///
1260 /// - The queue must be valid and stay valid for the lifetime of the [`BorrowedQueue`].
1261 /// - The queue must belong to this connection.
1262 pub unsafe fn borrow_foreign_queue(&self, queue: NonNull<wl_event_queue>) -> BorrowedQueue {
1263 BorrowedQueue {
1264 connection: self.clone(),
1265 queue: Some(SyncNonNull(queue)),
1266 }
1267 }
1268}
1269
1270impl Drop for QueueOwner {
1271 fn drop(&mut self) {
1272 // To catch errors early, acquire the lock unconditionally even if there are no
1273 // proxies to be destroyed.
1274 self.run_locked(|| ());
1275 self.queue.queue_data.owned_proxy_registry.destroy_all();
1276 }
1277}
1278
1279impl Drop for QueueData {
1280 fn drop(&mut self) {
1281 // SAFETY: - queue is always a valid pointer until this call
1282 // - all proxies attached to the queue hold a reference to the queue,
1283 // therefore this function does not run until all proxies are dropped,
1284 // which causes the proxies to be destroyed
1285 unsafe {
1286 self.libwayland.wl_event_queue_destroy(self.queue.as_ptr());
1287 }
1288 }
1289}
1290
1291impl PartialEq for Queue {
1292 fn eq(&self, other: &Queue) -> bool {
1293 self.queue_data.queue == other.queue_data.queue
1294 }
1295}
1296
1297impl Eq for Queue {}
1298
1299impl Debug for QueueOwner {
1300 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1301 self.queue.fmt(f)
1302 }
1303}
1304
1305impl Debug for Queue {
1306 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1307 f.debug_struct("Queue")
1308 .field("wl_event_queue", &self.wl_event_queue())
1309 .field("name", &self.queue_data.name)
1310 .finish_non_exhaustive()
1311 }
1312}
1313
1314impl Debug for DispatchLock<'_> {
1315 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1316 f.debug_struct("DispatchLock").finish_non_exhaustive()
1317 }
1318}
1319
1320impl Deref for Queue {
1321 type Target = BorrowedQueue;
1322
1323 fn deref(&self) -> &Self::Target {
1324 &self.queue_data.borrowed
1325 }
1326}