Skip to main content

Queue

Struct Queue 

Source
pub struct Queue { /* private fields */ }
Expand description

An event queue.

An event queue stores events that have been sent by the compositor but whose callbacks have not yet been invoked. Invoking these callbacks is called dispatching the queue.

A connection can have many queues that can be dispatched in parallel, but the events in a single queue are always dispatched in series. That is, the callback for the next event will not start executing until after the callback for the previous event.

New queues are created by calling Connection::create_local_queue or Connection::create_queue.

§Proxies attached to a queue

Each proxy is attached to a queue. This queue is determined as follows:

  • When Queue::display is called, the returned proxy is attached to that queue.
  • When Queue::wrap_proxy is called, the returned proxy is attached to that queue.
  • When a constructor request is called on an owned proxy P, e.g. WlDisplay::sync, the returned proxy is attached to the same queue as P.
  • When a constructor request is called on a borrowed proxy, e.g. WlDisplayRef::sync, the request takes a queue argument and the returned proxy is attached to that queue.

See the documentation of the proxy module for more information about proxies.

§Queue ownership

Each queue is owned by a QueueOwner which is returned when you call Connection::create_local_queue or Connection::create_queue.

When a QueueOwner is dropped, it will automatically destroy some of the proxies attached to the queue. This ensures that, when the QueueOwner is dropped, all reference cycles between proxies and their event handlers are broken and no memory is leaked. (Normally these cycles are broken when a destructor request is sent or the proxy is destroyed with proxy::destroy, but for long-lived proxies, such as wl_registry, it is more convenient for this to happen automatically.)

A queue and the attached proxies should no longer be used after its QueueOwner has been dropped. Doing so might lead to panics or memory leaks.

To ensure that the QueueOwner is eventually dropped, the queue owner should never be reachable from an event handler.

fn main() {
    let lib = Libwayland::open().unwrap();
    let con = lib.connect_to_default_display().unwrap();
    let queue: QueueOwner = con.create_queue(c"queue name");

    // the queue owner is stored on the stack and will be dropped when this function
    // returns
    application_logic(&queue);
}

§Local and non-local queues

Each queue is either local or non-local. Local queues are created with Connection::create_local_queue. Non-local queues are created with Connection::create_queue.

Local queues have the following advantage:

  • Event handlers attached to local queues do not have to implement Send.

This allows such events handlers to contain Rc<T> where the same event handler on a non-local queue would have to use Arc<T>.

To ensure that these event handlers are not accessed or dropped on different threads, this advantage comes with the following restrictions:

  • If a local queue was created on a thread X:
    • Event handlers must be attached on X.
    • The queue must only be dispatched on X.
    • The QueueOwner owning the queue must be dropped on X.
    • Proxies attached to the queue must only be destroyed on X.
      • Note: Proxies are destroyed when proxy::destroy is called or when a destructor request is sent or implicitly when the last reference to the proxy is dropped.

These restrictions are checked at runtime and will lead to panics if violated.

let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();

// Create a local queue.
let queue = con.create_local_queue(c"queue name");
let display: WlDisplay = queue.display();

// Create an `Rc` and use it as an event handler.
let done = Rc::new(Cell::new(false));
let done2 = done.clone();
let sync = display.sync();
proxy::set_event_handler_local(&sync, WlCallback::on_done(move |_, _| done2.set(true)));

// Calling this function from another thread would panic.
queue.dispatch_roundtrip_blocking().unwrap();

assert!(done.get());

§Locking

Each queue contains a re-entrant mutex. Re-entrant means that a thread that already holds the lock can acquire it again.

This lock can be acquired explicitly by calling Queue::lock_dispatch. You might want to use this function if you’re dispatching the queue from multiple threads to avoid lock inversion. For example, consider the following situation:

  • Thread 1: Acquires the lock of some shared state.
  • Thread 2: Starts dispatching and acquires the queue’s re-entrant lock.
  • Thread 2: Calls an event handler which tries to lock the shared state and blocks.
  • Thread 1: Destroys a proxy which will implicitly acquire the queue’s re-entrant lock. This deadlocks.

Instead, thread 1 could call Queue::lock_dispatch before locking the shared state to prevent the lock inversion.

This deadlock concern does not apply if the queue is only ever used from a single thread or if the queue is a local queue. If you need to poll the wayland socket on a separate thread, you can use BorrowedQueue::wait_for_events and send a message to the main thread when the future completes.

The lock is acquired implicitly in the following situations:

Implementations§

Source§

impl Queue

Source

pub fn dispatch_scope_blocking<'env, T, F>(&self, f: F) -> T
where F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> T,

Creates a blocking scope for event handlers with shorter than 'static lifetime.

The scope can be used to attach event handlers to proxies. The following restriction applies: Such event handlers will only be invoked while inside this function. Once this function returns, the OwnedProxy::NO_OP_EVENT_HANDLER of the proxy is invoked instead.

§Panic

Panics if this is a local queue and the current thread is not the thread that this queue was created in.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_local_queue(c"queue name");

let sync = queue.display::<WlDisplay>().sync();
let done = Cell::new(false);
queue.dispatch_scope_blocking(|scope| {
    scope.set_event_handler_local(&sync, WlCallback::on_done(|_, _| done.set(true)));
    queue.dispatch_roundtrip_blocking().unwrap();
});
assert!(done.get());
Examples found in repository?
examples/get-registry/../common/singletons.rs (lines 61-69)
55pub fn get_singletons(display: &WlDisplay) -> Singletons {
56    let map = Mutex::new(HashMap::new());
57
58    let queue = proxy::queue(display);
59    let wl_registry = display.get_registry();
60
61    queue.dispatch_scope_blocking(|scope| {
62        scope.set_event_handler(
63            &wl_registry,
64            WlRegistry::on_global(|_, name, interface, version| {
65                map.lock().insert(interface.to_owned(), (name, version));
66            }),
67        );
68        queue.dispatch_roundtrip_blocking().unwrap();
69    });
70
71    Singletons {
72        wl_registry,
73        map: map.into_inner(),
74    }
75}
More examples
Hide additional examples
examples/get-registry/main.rs (lines 35-50)
27fn get_registry_snapshot(queue: &Queue) -> (WlRegistry, Vec<Global>) {
28    // Create a new registry that will receive the globals and can later be used to
29    // bind them.
30    let registry = queue.display::<WlDisplay>().get_registry();
31    let globals = Mutex::new(vec![]);
32    // Since we don't care about registry events after this function returns, we can
33    // use a dispatch scope. The event handlers in this scope will not be called after
34    // the function returns.
35    queue.dispatch_scope_blocking(|scope| {
36        scope.set_event_handler(
37            &registry,
38            // Since we only want to create a snapshot, we don't care about
39            // global_remove events. This allows us to use the functional event handler
40            // form.
41            WlRegistry::on_global(|_, name, interface, version| {
42                globals.lock().push(Global {
43                    name,
44                    interface: interface.to_string(),
45                    version,
46                });
47            }),
48        );
49        queue.dispatch_roundtrip_blocking().unwrap();
50    });
51    // The event handler will no longer be called after this function returns but
52    // the registry can still be used to bind globals.
53    (registry, globals.into_inner())
54}
Source

pub async fn dispatch_scope_async<'env, T, F>(&self, f: F) -> T
where F: for<'scope> AsyncFnOnce(&'scope Scope<'scope, 'env>) -> T,

Creates an async scope for event handlers with shorter than 'static lifetime.

The scope can be used to attach event handlers to proxies. The following restriction applies: Such event handlers will only be invoked while the future is being polled. If an event needs to be dispatched in any other situation, the OwnedProxy::NO_OP_EVENT_HANDLER of the proxy is invoked instead.

In particular, dispatching the queue from a outside this future while this future exists is unlikely to have the desired effect.

§Panic

Panics if this is a local queue and the thread polling the future is not the thread that this queue was created in.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_local_queue(c"queue name");

let sync = queue.display::<WlDisplay>().sync();
let done = Cell::new(false);
queue.dispatch_scope_async(async |scope| {
    scope.set_event_handler_local(&sync, WlCallback::on_done(|_, _| done.set(true)));
    queue.dispatch_roundtrip_async().await.unwrap();
}).await;
assert!(done.get());
Examples found in repository?
examples/get-registry/../common/singletons.rs (lines 84-92)
77pub async fn get_singletons_async(display: &WlDisplay) -> Singletons {
78    let map = Mutex::new(HashMap::new());
79
80    let queue = proxy::queue(display);
81    let wl_registry = display.get_registry();
82
83    queue
84        .dispatch_scope_async(async |scope| {
85            scope.set_event_handler(
86                &wl_registry,
87                WlRegistry::on_global(|_, name, interface, version| {
88                    map.lock().insert(interface.to_owned(), (name, version));
89                }),
90            );
91            queue.dispatch_roundtrip_async().await.unwrap();
92        })
93        .await;
94
95    Singletons {
96        wl_registry,
97        map: map.into_inner(),
98    }
99}
More examples
Hide additional examples
examples/async-roundtrip/main.rs (lines 17-28)
10async fn main() {
11    let lib = Libwayland::open().unwrap();
12    let con = lib.connect_to_default_display().unwrap();
13    let queue = con.create_local_queue(c"async-roundtrip");
14    let registry = queue.display::<WlDisplay>().get_registry();
15    let num_globals = Cell::new(0);
16    queue
17        .dispatch_scope_async(async |scope| {
18            scope.set_event_handler_local(
19                &registry,
20                WlRegistry::on_global(|_, _, _, _| {
21                    num_globals.set(num_globals.get() + 1);
22                }),
23            );
24            // This function can be used to perform an async roundtrip. It is
25            // compatible with any async runtime. This example also demonstrates
26            // that this works in combination with scoped event handlers.
27            queue.dispatch_roundtrip_async().await.unwrap();
28        })
29        .await;
30    println!("number of globals: {}", num_globals.get());
31}
Source§

impl Queue

Source

pub fn with_data<T>(&self) -> QueueWithData<T>
where T: 'static,

Creates an adapter for queues with mutable data.

If the queue was created with Connection::create_queue_with_data or Connection::create_local_queue_with_data, then this function can only be used with the same T that was used in those function calls.

For convenience, if this queue was created without data, this function can be used with any T.

§Panic

This function panics if this queue

Source§

impl Queue

Source

pub fn libwayland(&self) -> &'static Libwayland

Returns a reference to the Libwayland singleton.

Examples found in repository?
examples/get-registry/../common/protocols/wayland/wl_display.rs (line 368)
351    unsafe fn handle_event(
352        &self,
353        queue: &Queue,
354        data: *mut u8,
355        slf: &UntypedBorrowedProxy,
356        opcode: u32,
357        args: *mut wl_argument,
358    ) {
359        // SAFETY: This function requires that slf has the interface INTERFACE
360        let slf = unsafe { proxy::low_level::from_untyped_borrowed::<WlDisplayRef>(slf) };
361        match opcode {
362            0 => {
363                // SAFETY: INTERFACE requires that there are 3 arguments
364                let args = unsafe { &*args.cast::<[wl_argument; 3]>() };
365                // SAFETY: - INTERFACE requires that args[0] contains an object
366                let arg0 = unsafe {
367                    if let Some(p) = NonNull::new(args[0].o.cast()) {
368                        Some(UntypedBorrowedProxy::new_immutable(queue.libwayland(), p))
369                    } else {
370                        None
371                    }
372                };
373                let arg0 = arg0.as_ref();
374                // SAFETY: - INTERFACE requires that args[1] contains a uint
375                let arg1 = unsafe { args[1].u };
376                // SAFETY: - INTERFACE requires that args[2] contains a string
377                //         - if the pointer is not null, then it is a c string
378                let arg2 = unsafe { convert_string_arg("wl_display", "message", args[2].s) };
379                self.0.error(slf, arg0, arg1, arg2);
380            }
381            1 => {
382                // SAFETY: INTERFACE requires that there are 1 arguments
383                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
384                // SAFETY: - INTERFACE requires that args[0] contains a uint
385                let arg0 = unsafe { args[0].u };
386                self.0.delete_id(slf, arg0);
387            }
388            _ => {
389                invalid_opcode("wl_display", opcode);
390            }
391        }
392    }
More examples
Hide additional examples
examples/get-registry/../common/protocols_data/wayland/wl_display.rs (line 385)
364    unsafe fn handle_event(
365        &self,
366        queue: &Queue,
367        data: *mut u8,
368        slf: &UntypedBorrowedProxy,
369        opcode: u32,
370        args: *mut wl_argument,
371    ) {
372        // SAFETY: This function requires that slf has the interface INTERFACE
373        let slf = unsafe { proxy::low_level::from_untyped_borrowed::<WlDisplayRef>(slf) };
374        // SAFETY: This function requires that data is `&mut T` where `T`
375        //         has the type id returned by `Self::mutable_type`, i.e.,
376        //         `T = H::Data`.
377        let data: &mut H::Data = unsafe { &mut *data.cast() };
378        match opcode {
379            0 => {
380                // SAFETY: INTERFACE requires that there are 3 arguments
381                let args = unsafe { &*args.cast::<[wl_argument; 3]>() };
382                // SAFETY: - INTERFACE requires that args[0] contains an object
383                let arg0 = unsafe {
384                    if let Some(p) = NonNull::new(args[0].o.cast()) {
385                        Some(UntypedBorrowedProxy::new_immutable(queue.libwayland(), p))
386                    } else {
387                        None
388                    }
389                };
390                let arg0 = arg0.as_ref();
391                // SAFETY: - INTERFACE requires that args[1] contains a uint
392                let arg1 = unsafe { args[1].u };
393                // SAFETY: - INTERFACE requires that args[2] contains a string
394                //         - if the pointer is not null, then it is a c string
395                let arg2 = unsafe { convert_string_arg("wl_display", "message", args[2].s) };
396                self.0.error(data, slf, arg0, arg1, arg2);
397            }
398            1 => {
399                // SAFETY: INTERFACE requires that there are 1 arguments
400                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
401                // SAFETY: - INTERFACE requires that args[0] contains a uint
402                let arg0 = unsafe { args[0].u };
403                self.0.delete_id(data, slf, arg0);
404            }
405            _ => {
406                invalid_opcode("wl_display", opcode);
407            }
408        }
409    }
examples/get-registry/../common/protocols/wayland/wl_surface.rs (line 1025)
1008    unsafe fn handle_event(
1009        &self,
1010        queue: &Queue,
1011        data: *mut u8,
1012        slf: &UntypedBorrowedProxy,
1013        opcode: u32,
1014        args: *mut wl_argument,
1015    ) {
1016        // SAFETY: This function requires that slf has the interface INTERFACE
1017        let slf = unsafe { proxy::low_level::from_untyped_borrowed::<WlSurfaceRef>(slf) };
1018        match opcode {
1019            0 => {
1020                // SAFETY: INTERFACE requires that there are 1 arguments
1021                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
1022                // SAFETY: - INTERFACE requires that args[0] contains an object
1023                let arg0 = unsafe {
1024                    if let Some(p) = NonNull::new(args[0].o.cast()) {
1025                        Some(UntypedBorrowedProxy::new_immutable(queue.libwayland(), p))
1026                    } else {
1027                        None
1028                    }
1029                };
1030                // SAFETY: - INTERFACE requires that the object has the interface WlOutput::WL_INTERFACE
1031                let arg0 = arg0.as_ref().map(|arg0| unsafe {
1032                    proxy::low_level::from_untyped_borrowed::<WlOutputRef>(arg0)
1033                });
1034                self.0.enter(slf, arg0);
1035            }
1036            1 => {
1037                // SAFETY: INTERFACE requires that there are 1 arguments
1038                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
1039                // SAFETY: - INTERFACE requires that args[0] contains an object
1040                let arg0 = unsafe {
1041                    if let Some(p) = NonNull::new(args[0].o.cast()) {
1042                        Some(UntypedBorrowedProxy::new_immutable(queue.libwayland(), p))
1043                    } else {
1044                        None
1045                    }
1046                };
1047                // SAFETY: - INTERFACE requires that the object has the interface WlOutput::WL_INTERFACE
1048                let arg0 = arg0.as_ref().map(|arg0| unsafe {
1049                    proxy::low_level::from_untyped_borrowed::<WlOutputRef>(arg0)
1050                });
1051                self.0.leave(slf, arg0);
1052            }
1053            2 => {
1054                // SAFETY: INTERFACE requires that there are 1 arguments
1055                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
1056                // SAFETY: - INTERFACE requires that args[0] contains an int
1057                let arg0 = unsafe { args[0].i };
1058                self.0.preferred_buffer_scale(slf, arg0);
1059            }
1060            3 => {
1061                // SAFETY: INTERFACE requires that there are 1 arguments
1062                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
1063                // SAFETY: - INTERFACE requires that args[0] contains a uint
1064                let arg0 = unsafe { WlOutputTransform(args[0].u) };
1065                self.0.preferred_buffer_transform(slf, arg0);
1066            }
1067            _ => {
1068                invalid_opcode("wl_surface", opcode);
1069            }
1070        }
1071    }
examples/get-registry/../common/protocols_data/wayland/wl_surface.rs (line 1046)
1025    unsafe fn handle_event(
1026        &self,
1027        queue: &Queue,
1028        data: *mut u8,
1029        slf: &UntypedBorrowedProxy,
1030        opcode: u32,
1031        args: *mut wl_argument,
1032    ) {
1033        // SAFETY: This function requires that slf has the interface INTERFACE
1034        let slf = unsafe { proxy::low_level::from_untyped_borrowed::<WlSurfaceRef>(slf) };
1035        // SAFETY: This function requires that data is `&mut T` where `T`
1036        //         has the type id returned by `Self::mutable_type`, i.e.,
1037        //         `T = H::Data`.
1038        let data: &mut H::Data = unsafe { &mut *data.cast() };
1039        match opcode {
1040            0 => {
1041                // SAFETY: INTERFACE requires that there are 1 arguments
1042                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
1043                // SAFETY: - INTERFACE requires that args[0] contains an object
1044                let arg0 = unsafe {
1045                    if let Some(p) = NonNull::new(args[0].o.cast()) {
1046                        Some(UntypedBorrowedProxy::new_immutable(queue.libwayland(), p))
1047                    } else {
1048                        None
1049                    }
1050                };
1051                // SAFETY: - INTERFACE requires that the object has the interface WlOutput::WL_INTERFACE
1052                let arg0 = arg0.as_ref().map(|arg0| unsafe {
1053                    proxy::low_level::from_untyped_borrowed::<WlOutputRef>(arg0)
1054                });
1055                self.0.enter(data, slf, arg0);
1056            }
1057            1 => {
1058                // SAFETY: INTERFACE requires that there are 1 arguments
1059                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
1060                // SAFETY: - INTERFACE requires that args[0] contains an object
1061                let arg0 = unsafe {
1062                    if let Some(p) = NonNull::new(args[0].o.cast()) {
1063                        Some(UntypedBorrowedProxy::new_immutable(queue.libwayland(), p))
1064                    } else {
1065                        None
1066                    }
1067                };
1068                // SAFETY: - INTERFACE requires that the object has the interface WlOutput::WL_INTERFACE
1069                let arg0 = arg0.as_ref().map(|arg0| unsafe {
1070                    proxy::low_level::from_untyped_borrowed::<WlOutputRef>(arg0)
1071                });
1072                self.0.leave(data, slf, arg0);
1073            }
1074            2 => {
1075                // SAFETY: INTERFACE requires that there are 1 arguments
1076                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
1077                // SAFETY: - INTERFACE requires that args[0] contains an int
1078                let arg0 = unsafe { args[0].i };
1079                self.0.preferred_buffer_scale(data, slf, arg0);
1080            }
1081            3 => {
1082                // SAFETY: INTERFACE requires that there are 1 arguments
1083                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
1084                // SAFETY: - INTERFACE requires that args[0] contains a uint
1085                let arg0 = unsafe { WlOutputTransform(args[0].u) };
1086                self.0.preferred_buffer_transform(data, slf, arg0);
1087            }
1088            _ => {
1089                invalid_opcode("wl_surface", opcode);
1090            }
1091        }
1092    }
examples/get-registry/../common/protocols/wayland/wl_touch.rs (line 444)
423    unsafe fn handle_event(
424        &self,
425        queue: &Queue,
426        data: *mut u8,
427        slf: &UntypedBorrowedProxy,
428        opcode: u32,
429        args: *mut wl_argument,
430    ) {
431        // SAFETY: This function requires that slf has the interface INTERFACE
432        let slf = unsafe { proxy::low_level::from_untyped_borrowed::<WlTouchRef>(slf) };
433        match opcode {
434            0 => {
435                // SAFETY: INTERFACE requires that there are 6 arguments
436                let args = unsafe { &*args.cast::<[wl_argument; 6]>() };
437                // SAFETY: - INTERFACE requires that args[0] contains a uint
438                let arg0 = unsafe { args[0].u };
439                // SAFETY: - INTERFACE requires that args[1] contains a uint
440                let arg1 = unsafe { args[1].u };
441                // SAFETY: - INTERFACE requires that args[2] contains an object
442                let arg2 = unsafe {
443                    if let Some(p) = NonNull::new(args[2].o.cast()) {
444                        Some(UntypedBorrowedProxy::new_immutable(queue.libwayland(), p))
445                    } else {
446                        None
447                    }
448                };
449                // SAFETY: - INTERFACE requires that the object has the interface WlSurface::WL_INTERFACE
450                let arg2 = arg2.as_ref().map(|arg2| unsafe {
451                    proxy::low_level::from_untyped_borrowed::<WlSurfaceRef>(arg2)
452                });
453                // SAFETY: - INTERFACE requires that args[3] contains an int
454                let arg3 = unsafe { args[3].i };
455                // SAFETY: - INTERFACE requires that args[4] contains a fixed
456                let arg4 = unsafe { Fixed::from_wire(args[4].f) };
457                // SAFETY: - INTERFACE requires that args[5] contains a fixed
458                let arg5 = unsafe { Fixed::from_wire(args[5].f) };
459                self.0.down(slf, arg0, arg1, arg2, arg3, arg4, arg5);
460            }
461            1 => {
462                // SAFETY: INTERFACE requires that there are 3 arguments
463                let args = unsafe { &*args.cast::<[wl_argument; 3]>() };
464                // SAFETY: - INTERFACE requires that args[0] contains a uint
465                let arg0 = unsafe { args[0].u };
466                // SAFETY: - INTERFACE requires that args[1] contains a uint
467                let arg1 = unsafe { args[1].u };
468                // SAFETY: - INTERFACE requires that args[2] contains an int
469                let arg2 = unsafe { args[2].i };
470                self.0.up(slf, arg0, arg1, arg2);
471            }
472            2 => {
473                // SAFETY: INTERFACE requires that there are 4 arguments
474                let args = unsafe { &*args.cast::<[wl_argument; 4]>() };
475                // SAFETY: - INTERFACE requires that args[0] contains a uint
476                let arg0 = unsafe { args[0].u };
477                // SAFETY: - INTERFACE requires that args[1] contains an int
478                let arg1 = unsafe { args[1].i };
479                // SAFETY: - INTERFACE requires that args[2] contains a fixed
480                let arg2 = unsafe { Fixed::from_wire(args[2].f) };
481                // SAFETY: - INTERFACE requires that args[3] contains a fixed
482                let arg3 = unsafe { Fixed::from_wire(args[3].f) };
483                self.0.motion(slf, arg0, arg1, arg2, arg3);
484            }
485            3 => {
486                self.0.frame(slf);
487            }
488            4 => {
489                self.0.cancel(slf);
490            }
491            5 => {
492                // SAFETY: INTERFACE requires that there are 3 arguments
493                let args = unsafe { &*args.cast::<[wl_argument; 3]>() };
494                // SAFETY: - INTERFACE requires that args[0] contains an int
495                let arg0 = unsafe { args[0].i };
496                // SAFETY: - INTERFACE requires that args[1] contains a fixed
497                let arg1 = unsafe { Fixed::from_wire(args[1].f) };
498                // SAFETY: - INTERFACE requires that args[2] contains a fixed
499                let arg2 = unsafe { Fixed::from_wire(args[2].f) };
500                self.0.shape(slf, arg0, arg1, arg2);
501            }
502            6 => {
503                // SAFETY: INTERFACE requires that there are 2 arguments
504                let args = unsafe { &*args.cast::<[wl_argument; 2]>() };
505                // SAFETY: - INTERFACE requires that args[0] contains an int
506                let arg0 = unsafe { args[0].i };
507                // SAFETY: - INTERFACE requires that args[1] contains a fixed
508                let arg1 = unsafe { Fixed::from_wire(args[1].f) };
509                self.0.orientation(slf, arg0, arg1);
510            }
511            _ => {
512                invalid_opcode("wl_touch", opcode);
513            }
514        }
515    }
examples/get-registry/../common/protocols_data/wayland/wl_touch.rs (line 476)
451    unsafe fn handle_event(
452        &self,
453        queue: &Queue,
454        data: *mut u8,
455        slf: &UntypedBorrowedProxy,
456        opcode: u32,
457        args: *mut wl_argument,
458    ) {
459        // SAFETY: This function requires that slf has the interface INTERFACE
460        let slf = unsafe { proxy::low_level::from_untyped_borrowed::<WlTouchRef>(slf) };
461        // SAFETY: This function requires that data is `&mut T` where `T`
462        //         has the type id returned by `Self::mutable_type`, i.e.,
463        //         `T = H::Data`.
464        let data: &mut H::Data = unsafe { &mut *data.cast() };
465        match opcode {
466            0 => {
467                // SAFETY: INTERFACE requires that there are 6 arguments
468                let args = unsafe { &*args.cast::<[wl_argument; 6]>() };
469                // SAFETY: - INTERFACE requires that args[0] contains a uint
470                let arg0 = unsafe { args[0].u };
471                // SAFETY: - INTERFACE requires that args[1] contains a uint
472                let arg1 = unsafe { args[1].u };
473                // SAFETY: - INTERFACE requires that args[2] contains an object
474                let arg2 = unsafe {
475                    if let Some(p) = NonNull::new(args[2].o.cast()) {
476                        Some(UntypedBorrowedProxy::new_immutable(queue.libwayland(), p))
477                    } else {
478                        None
479                    }
480                };
481                // SAFETY: - INTERFACE requires that the object has the interface WlSurface::WL_INTERFACE
482                let arg2 = arg2.as_ref().map(|arg2| unsafe {
483                    proxy::low_level::from_untyped_borrowed::<WlSurfaceRef>(arg2)
484                });
485                // SAFETY: - INTERFACE requires that args[3] contains an int
486                let arg3 = unsafe { args[3].i };
487                // SAFETY: - INTERFACE requires that args[4] contains a fixed
488                let arg4 = unsafe { Fixed::from_wire(args[4].f) };
489                // SAFETY: - INTERFACE requires that args[5] contains a fixed
490                let arg5 = unsafe { Fixed::from_wire(args[5].f) };
491                self.0.down(data, slf, arg0, arg1, arg2, arg3, arg4, arg5);
492            }
493            1 => {
494                // SAFETY: INTERFACE requires that there are 3 arguments
495                let args = unsafe { &*args.cast::<[wl_argument; 3]>() };
496                // SAFETY: - INTERFACE requires that args[0] contains a uint
497                let arg0 = unsafe { args[0].u };
498                // SAFETY: - INTERFACE requires that args[1] contains a uint
499                let arg1 = unsafe { args[1].u };
500                // SAFETY: - INTERFACE requires that args[2] contains an int
501                let arg2 = unsafe { args[2].i };
502                self.0.up(data, slf, arg0, arg1, arg2);
503            }
504            2 => {
505                // SAFETY: INTERFACE requires that there are 4 arguments
506                let args = unsafe { &*args.cast::<[wl_argument; 4]>() };
507                // SAFETY: - INTERFACE requires that args[0] contains a uint
508                let arg0 = unsafe { args[0].u };
509                // SAFETY: - INTERFACE requires that args[1] contains an int
510                let arg1 = unsafe { args[1].i };
511                // SAFETY: - INTERFACE requires that args[2] contains a fixed
512                let arg2 = unsafe { Fixed::from_wire(args[2].f) };
513                // SAFETY: - INTERFACE requires that args[3] contains a fixed
514                let arg3 = unsafe { Fixed::from_wire(args[3].f) };
515                self.0.motion(data, slf, arg0, arg1, arg2, arg3);
516            }
517            3 => {
518                self.0.frame(data, slf);
519            }
520            4 => {
521                self.0.cancel(data, slf);
522            }
523            5 => {
524                // SAFETY: INTERFACE requires that there are 3 arguments
525                let args = unsafe { &*args.cast::<[wl_argument; 3]>() };
526                // SAFETY: - INTERFACE requires that args[0] contains an int
527                let arg0 = unsafe { args[0].i };
528                // SAFETY: - INTERFACE requires that args[1] contains a fixed
529                let arg1 = unsafe { Fixed::from_wire(args[1].f) };
530                // SAFETY: - INTERFACE requires that args[2] contains a fixed
531                let arg2 = unsafe { Fixed::from_wire(args[2].f) };
532                self.0.shape(data, slf, arg0, arg1, arg2);
533            }
534            6 => {
535                // SAFETY: INTERFACE requires that there are 2 arguments
536                let args = unsafe { &*args.cast::<[wl_argument; 2]>() };
537                // SAFETY: - INTERFACE requires that args[0] contains an int
538                let arg0 = unsafe { args[0].i };
539                // SAFETY: - INTERFACE requires that args[1] contains a fixed
540                let arg1 = unsafe { Fixed::from_wire(args[1].f) };
541                self.0.orientation(data, slf, arg0, arg1);
542            }
543            _ => {
544                invalid_opcode("wl_touch", opcode);
545            }
546        }
547    }
Source

pub fn connection(&self) -> &Connection

Returns the connection that this queue belongs to.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"queue name");
assert_eq!(queue.connection(), &con);
Source

pub fn lock_dispatch(&self) -> DispatchLock<'_>

Acquires the queue’s re-entrant lock.

See the description of Queue for why you might use this.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"queue name");

let lock = queue.lock_dispatch();

let thread = {
    let queue = queue.clone();
    thread::spawn(move || {
        // this dispatch will not start until the lock is dropped.
        queue.dispatch_roundtrip_blocking().unwrap();
    })
};

// this dispatch starts immediately since the lock is re-entrant
queue.dispatch_roundtrip_blocking().unwrap();

drop(lock);
thread.join().unwrap();
Source

pub fn display<T>(&self) -> T
where T: OwnedProxy,

Creates a wrapper proxy around the singleton wl_display object.

The proxy is a wrapper and no event handler can be attached to it.

The proxy is attached to this queue.

§Panic

Panics if the interface of T is not compatible with the wl_display interface.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"queue name");
let display: WlDisplay = queue.display();
assert_eq!(proxy::queue(&display), &*queue);
assert_eq!(proxy::id(&*display), 1);
Examples found in repository?
examples/async-wait/main.rs (line 25)
24fn create_sync(queue: &Queue, n: u64) {
25    let sync = queue.display::<WlDisplay>().sync();
26    proxy::set_event_handler(
27        &sync.clone(),
28        WlCallback::on_done(move |_, _| {
29            println!("done! ({n})");
30            proxy::destroy(&sync);
31            create_sync(proxy::queue(&sync), n + 1);
32        }),
33    );
34}
More examples
Hide additional examples
examples/poll-integration/main.rs (line 52)
51fn create_sync(queue: &Queue, n: u64) {
52    let sync = queue.display::<WlDisplay>().sync();
53    proxy::set_event_handler(
54        &sync.clone(),
55        WlCallback::on_done(move |_, _| {
56            println!("done! ({n})");
57            proxy::destroy(&sync);
58            create_sync(proxy::queue(&sync), n + 1);
59        }),
60    );
61}
examples/simple-window/main.rs (line 12)
8fn main() {
9    let lib = Libwayland::open().unwrap();
10    let con = lib.connect_to_default_display().unwrap();
11    let queue = con.create_local_queue(c"simple-window");
12    let singletons = get_singletons(&queue.display());
13    let simple_window = simple_window::prepare(singletons);
14    while !simple_window.exit.get() {
15        queue.dispatch_blocking().unwrap();
16    }
17}
examples/async-window/main.rs (line 13)
9async fn main() {
10    let lib = Libwayland::open().unwrap();
11    let con = lib.connect_to_default_display().unwrap();
12    let queue = con.create_local_queue(c"async-window");
13    let singletons = get_singletons_async(&queue.display()).await;
14    let simple_window = simple_window::prepare(singletons);
15    while !simple_window.exit.get() {
16        queue.dispatch_async().await.unwrap();
17    }
18}
examples/keyboard-events/main.rs (line 32)
28fn main() {
29    let lib = Libwayland::open().unwrap();
30    let con = lib.connect_to_default_display().unwrap();
31    let queue = con.create_local_queue(c"keyboard-events");
32    let singletons = get_singletons(&queue.display());
33    let simple_window = simple_window::prepare(singletons);
34
35    let wl_registry = queue.display::<WlDisplay>().get_registry();
36    proxy::set_event_handler_local(
37        &wl_registry,
38        RegistryEventHandler {
39            wl_registry: wl_registry.clone(),
40            seats: Default::default(),
41        },
42    );
43
44    while !simple_window.exit.get() {
45        queue.dispatch_blocking().unwrap();
46    }
47}
examples/async-roundtrip/main.rs (line 14)
10async fn main() {
11    let lib = Libwayland::open().unwrap();
12    let con = lib.connect_to_default_display().unwrap();
13    let queue = con.create_local_queue(c"async-roundtrip");
14    let registry = queue.display::<WlDisplay>().get_registry();
15    let num_globals = Cell::new(0);
16    queue
17        .dispatch_scope_async(async |scope| {
18            scope.set_event_handler_local(
19                &registry,
20                WlRegistry::on_global(|_, _, _, _| {
21                    num_globals.set(num_globals.get() + 1);
22                }),
23            );
24            // This function can be used to perform an async roundtrip. It is
25            // compatible with any async runtime. This example also demonstrates
26            // that this works in combination with scoped event handlers.
27            queue.dispatch_roundtrip_async().await.unwrap();
28        })
29        .await;
30    println!("number of globals: {}", num_globals.get());
31}
Source

pub fn is_local(&self) -> bool

Returns whether this is a local queue.

The documentation of the Queue type explains the difference between local and non-local queues.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue1 = con.create_queue(c"non-local queue");
let queue2 = con.create_local_queue(c"local queue");

assert!(queue1.is_non_local());
assert!(queue2.is_local());
Source

pub fn is_non_local(&self) -> bool

Returns whether this is not a local queue.

This is the same as !self.is_local().

The documentation of the Queue type explains the difference between local and non-local queues.

Source

pub fn wl_event_queue(&self) -> NonNull<wl_event_queue>

Returns the wl_event_queue pointer of this queue.

The returned pointer is valid for as long as this queue exists.

You must not dispatch the queue except through the Queue interface. Otherwise the behavior is undefined.

Source

pub fn dispatch_blocking(&self) -> Result<u64>

Blocks the current thread until at least one event has been dispatched.

If you are in an async context, then you might want to use Queue::dispatch_async instead.

This function should not be used when integrating with an existing, poll-based event loop, as it might block indefinitely. Use Connection::create_watcher and Queue::dispatch_pending instead.

This function cannot be used if the queue was created with Connection::create_queue_with_data or Connection::create_local_queue_with_data. Use QueueWithData::dispatch_blocking instead.

The returned number is the number of events that have been dispatched by this call. The number can be zero if another thread dispatched the events before us.

§Panic
§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"queue name");

// For this example, ensure that the compositor sends an event in the near future.
let _sync = queue.display::<WlDisplay>().sync();

queue.dispatch_blocking().unwrap();
Examples found in repository?
examples/simple-window/main.rs (line 15)
8fn main() {
9    let lib = Libwayland::open().unwrap();
10    let con = lib.connect_to_default_display().unwrap();
11    let queue = con.create_local_queue(c"simple-window");
12    let singletons = get_singletons(&queue.display());
13    let simple_window = simple_window::prepare(singletons);
14    while !simple_window.exit.get() {
15        queue.dispatch_blocking().unwrap();
16    }
17}
More examples
Hide additional examples
examples/keyboard-events/main.rs (line 45)
28fn main() {
29    let lib = Libwayland::open().unwrap();
30    let con = lib.connect_to_default_display().unwrap();
31    let queue = con.create_local_queue(c"keyboard-events");
32    let singletons = get_singletons(&queue.display());
33    let simple_window = simple_window::prepare(singletons);
34
35    let wl_registry = queue.display::<WlDisplay>().get_registry();
36    proxy::set_event_handler_local(
37        &wl_registry,
38        RegistryEventHandler {
39            wl_registry: wl_registry.clone(),
40            seats: Default::default(),
41        },
42    );
43
44    while !simple_window.exit.get() {
45        queue.dispatch_blocking().unwrap();
46    }
47}
Source

pub async fn dispatch_async(&self) -> Result<u64>

Completes when at least one event has been dispatched.

This function is the same as Queue::dispatch_blocking except that it is async and does not block the current thread.

§Panic
§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"queue name");

// For this example, ensure that the compositor sends an event in the near future.
let _sync = queue.display::<WlDisplay>().sync();

queue.dispatch_async().await.unwrap();
Examples found in repository?
examples/async-window/main.rs (line 16)
9async fn main() {
10    let lib = Libwayland::open().unwrap();
11    let con = lib.connect_to_default_display().unwrap();
12    let queue = con.create_local_queue(c"async-window");
13    let singletons = get_singletons_async(&queue.display()).await;
14    let simple_window = simple_window::prepare(singletons);
15    while !simple_window.exit.get() {
16        queue.dispatch_async().await.unwrap();
17    }
18}
Source

pub fn dispatch_pending(&self) -> Result<u64>

Dispatches enqueued events.

This function does not read new events from the file descriptor.

This function can be used together with BorrowedQueue::wait_for_events or Queue::create_watcher to dispatch the queue in an async context or event loop respectively.

This function cannot be used if the queue was created with Connection::create_queue_with_data or Connection::create_local_queue_with_data. Use QueueWithData::dispatch_pending instead.

The returned number is the number of events that were dispatched.

§Panic
§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"queue name");
let display: WlDisplay = queue.display();

let done = Arc::new(AtomicBool::new(false));
let done2 = done.clone();
let sync = display.sync();
proxy::set_event_handler(&sync, WlCallback::on_done(move |_, _| {
    done2.store(true, Relaxed);
}));

while !done.load(Relaxed) {
    queue.wait_for_events().await.unwrap();
    // Dispatch the events.
    queue.dispatch_pending().unwrap();
}
Examples found in repository?
examples/async-wait/main.rs (line 20)
11async fn main() {
12    let lib = Libwayland::open().unwrap();
13    let con = lib.connect_to_default_display().unwrap();
14    let queue = con.create_local_queue(c"async-wait");
15
16    create_sync(&queue, 1);
17
18    loop {
19        queue.wait_for_events().await.unwrap();
20        queue.dispatch_pending().unwrap();
21    }
22}
More examples
Hide additional examples
examples/poll-integration/main.rs (line 42)
14fn main() {
15    let lib = Libwayland::open().unwrap();
16    let con = lib.connect_to_default_display().unwrap();
17    let queue = con.create_local_queue(c"poll-integration");
18
19    // The watcher exposes a file descriptor that will become readable when the queue
20    // has new events.
21    let watcher = queue.create_watcher().unwrap();
22    let token = Token(0);
23
24    create_sync(&queue, 1);
25
26    let mut events = mio::Events::with_capacity(2);
27    let mut poll = mio::Poll::new().unwrap();
28    poll.registry()
29        .register(
30            &mut SourceFd(&watcher.as_raw_fd()),
31            token,
32            Interest::READABLE,
33        )
34        .unwrap();
35
36    loop {
37        // Flush requests before polling.
38        con.flush().unwrap();
39        poll.poll(&mut events, None).unwrap();
40        for event in events.iter() {
41            if event.token() == token {
42                queue.dispatch_pending().unwrap();
43                // Reset the watcher to clear the readability status.
44                watcher.reset().unwrap();
45            }
46        }
47        events.clear();
48    }
49}
Source

pub fn dispatch_roundtrip_blocking(&self) -> Result<()>

Blocks the current thread until the compositor has processed all previous requests and all of its response events have been dispatched.

If you are in an async context, then you might want to use Queue::dispatch_roundtrip_async instead.

Since this function usually returns quickly, you might use this function even when integrating a wayland connection into an existing event loop and even in an async context. For example, a library that creates buffers might use this function during initialization to receive the full list of supported formats before returning.

This function cannot be used if the queue was created with Connection::create_queue_with_data or Connection::create_local_queue_with_data. Use QueueWithData::dispatch_roundtrip_blocking instead.

If this function returns Ok(()), then the function returns after (in the sense of the C++ memory model) the event handlers of all previous events have been invoked.

§Panic
§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"");
let display: WlDisplay = queue.display();

// send some messages to the compositor
let done = Arc::new(AtomicBool::new(false));
let done2 = done.clone();
let sync = display.sync();
proxy::set_event_handler(&sync, WlCallback::on_done(move |_, _| {
    done2.store(true, Relaxed);
}));

// perform a roundtrip
queue.dispatch_roundtrip_blocking().unwrap();

// assert that we've received the response
assert!(done.load(Relaxed));
Examples found in repository?
examples/get-registry/../common/singletons.rs (line 68)
55pub fn get_singletons(display: &WlDisplay) -> Singletons {
56    let map = Mutex::new(HashMap::new());
57
58    let queue = proxy::queue(display);
59    let wl_registry = display.get_registry();
60
61    queue.dispatch_scope_blocking(|scope| {
62        scope.set_event_handler(
63            &wl_registry,
64            WlRegistry::on_global(|_, name, interface, version| {
65                map.lock().insert(interface.to_owned(), (name, version));
66            }),
67        );
68        queue.dispatch_roundtrip_blocking().unwrap();
69    });
70
71    Singletons {
72        wl_registry,
73        map: map.into_inner(),
74    }
75}
More examples
Hide additional examples
examples/get-registry/main.rs (line 49)
27fn get_registry_snapshot(queue: &Queue) -> (WlRegistry, Vec<Global>) {
28    // Create a new registry that will receive the globals and can later be used to
29    // bind them.
30    let registry = queue.display::<WlDisplay>().get_registry();
31    let globals = Mutex::new(vec![]);
32    // Since we don't care about registry events after this function returns, we can
33    // use a dispatch scope. The event handlers in this scope will not be called after
34    // the function returns.
35    queue.dispatch_scope_blocking(|scope| {
36        scope.set_event_handler(
37            &registry,
38            // Since we only want to create a snapshot, we don't care about
39            // global_remove events. This allows us to use the functional event handler
40            // form.
41            WlRegistry::on_global(|_, name, interface, version| {
42                globals.lock().push(Global {
43                    name,
44                    interface: interface.to_string(),
45                    version,
46                });
47            }),
48        );
49        queue.dispatch_roundtrip_blocking().unwrap();
50    });
51    // The event handler will no longer be called after this function returns but
52    // the registry can still be used to bind globals.
53    (registry, globals.into_inner())
54}
examples/hello-wayland/main.rs (line 32)
9fn main() {
10    // Load the `libwayland-client.so` dynamic library.
11    let lib = Libwayland::open().unwrap();
12    // Connect to the default display determined by the `WAYLAND_DISPLAY` env var.
13    let con = lib.connect_to_default_display().unwrap();
14    // Create a new event queue with the name `hello-wayland`. This name will show up
15    // when debugging applications with `WAYLAND_DEBUG=1`.
16    let queue = con.create_queue(c"hello-wayland");
17    // Get a reference to the `wl_display` singleton. This type was generated with the
18    // `wl-client-builder` crate.
19    let display: WlDisplay = queue.display();
20    // Create a `wl_callback` object. The compositor will immediately respond with a
21    // `wl_callback.done` event.
22    let sync = display.sync();
23    // Set the event handler of the proxy.
24    proxy::set_event_handler(
25        &sync,
26        // When only handling a single event, the following functional form can be used.
27        // In general, and when handling more than one event, the event handler trait must
28        // be implemented. In this case, `WlCallbackEventHandler`.
29        WlCallback::on_done(|_, _| println!("Hello wayland!")),
30    );
31    // Perform a roundtrip to ensure that the `done` event has been dispatched.
32    queue.dispatch_roundtrip_blocking().unwrap();
33}
Source

pub async fn dispatch_roundtrip_async(&self) -> Result<()>

Completes when the compositor has processed all previous requests and all of its response events have been dispatched.

This function is the same as Queue::dispatch_roundtrip_blocking except that it is async and does not block the current thread.

If the future completes with Ok(()), then the future completes after (in the sense of the C++ memory model) the event handlers of all previous events have been invoked.

§Panic
§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"queue name");
let display: WlDisplay = queue.display();

// send some messages to the compositor
let done = Arc::new(AtomicBool::new(false));
let done2 = done.clone();
let sync = display.sync();
proxy::set_event_handler(&sync, WlCallback::on_done(move |_, _| {
    done2.store(true, Relaxed);
}));

// perform a roundtrip
queue.dispatch_roundtrip_async().await.unwrap();

// assert that we've received the response
assert!(done.load(Relaxed));
Examples found in repository?
examples/get-registry/../common/singletons.rs (line 91)
77pub async fn get_singletons_async(display: &WlDisplay) -> Singletons {
78    let map = Mutex::new(HashMap::new());
79
80    let queue = proxy::queue(display);
81    let wl_registry = display.get_registry();
82
83    queue
84        .dispatch_scope_async(async |scope| {
85            scope.set_event_handler(
86                &wl_registry,
87                WlRegistry::on_global(|_, name, interface, version| {
88                    map.lock().insert(interface.to_owned(), (name, version));
89                }),
90            );
91            queue.dispatch_roundtrip_async().await.unwrap();
92        })
93        .await;
94
95    Singletons {
96        wl_registry,
97        map: map.into_inner(),
98    }
99}
More examples
Hide additional examples
examples/async-roundtrip/main.rs (line 27)
10async fn main() {
11    let lib = Libwayland::open().unwrap();
12    let con = lib.connect_to_default_display().unwrap();
13    let queue = con.create_local_queue(c"async-roundtrip");
14    let registry = queue.display::<WlDisplay>().get_registry();
15    let num_globals = Cell::new(0);
16    queue
17        .dispatch_scope_async(async |scope| {
18            scope.set_event_handler_local(
19                &registry,
20                WlRegistry::on_global(|_, _, _, _| {
21                    num_globals.set(num_globals.get() + 1);
22                }),
23            );
24            // This function can be used to perform an async roundtrip. It is
25            // compatible with any async runtime. This example also demonstrates
26            // that this works in combination with scoped event handlers.
27            queue.dispatch_roundtrip_async().await.unwrap();
28        })
29        .await;
30    println!("number of globals: {}", num_globals.get());
31}
Source

pub fn wrap_proxy<P>(&self, proxy: &P) -> P::Owned
where P: BorrowedProxy,

Creates a wrapper for an existing proxy.

The wrapper will be assigned to this queue. No event handler can be assigned to the wrapper.

§Panic
  • Panics if the proxy and this queue don’t belong to the same wl_display.
  • Panics if the proxy is already destroyed.
§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();

let queue1 = con.create_queue(c"queue name");
let display1: WlDisplay = queue1.display();
assert_eq!(proxy::queue(&display1), &*queue1);

let queue2 = con.create_queue(c"second queue");
let display2 = queue2.wrap_proxy(&*display1);
assert_eq!(proxy::queue(&display2), &*queue2);
Source

pub unsafe fn wrap_wl_proxy<P>(&self, proxy: NonNull<wl_proxy>) -> P
where P: OwnedProxy,

Creates a wrapper for an existing wl_proxy.

The wrapper will be assigned to this queue. No event handler can be assigned to the wrapper.

If the wl_proxy already has a safe wrapper, the Queue::wrap_proxy function can be used instead.

§Panic
  • Panics if the proxy and this queue don’t belong to the same wl_display.
§Safety
  • proxy must be a valid pointer.
  • proxy must have an interface compatible with P::WL_INTERFACE.
§Example

Some frameworks, e.g. winit, expose libwayland wl_display and wl_surface pointers. These can be imported into this crate as follows:

unsafe fn wrap_foreign_surface(display: NonNull<c_void>, wl_surface: NonNull<c_void>) {
    let lib = Libwayland::open().unwrap();
    // SAFETY: ...
    let con = unsafe { lib.wrap_borrowed_pointer(display.cast()).unwrap() };
    let queue = con.create_queue(c"queue name");
    // SAFETY: ...
    let surface: WlSurface = unsafe { queue.wrap_wl_proxy(wl_surface.cast()) };
}
Source

pub fn create_watcher(&self) -> Result<QueueWatcher>

Creates a QueueWatcher for event-loop integration.

This is a shorthand for calling Connection::create_watcher with a queue list containing exactly this queue.

Examples found in repository?
examples/poll-integration/main.rs (line 21)
14fn main() {
15    let lib = Libwayland::open().unwrap();
16    let con = lib.connect_to_default_display().unwrap();
17    let queue = con.create_local_queue(c"poll-integration");
18
19    // The watcher exposes a file descriptor that will become readable when the queue
20    // has new events.
21    let watcher = queue.create_watcher().unwrap();
22    let token = Token(0);
23
24    create_sync(&queue, 1);
25
26    let mut events = mio::Events::with_capacity(2);
27    let mut poll = mio::Poll::new().unwrap();
28    poll.registry()
29        .register(
30            &mut SourceFd(&watcher.as_raw_fd()),
31            token,
32            Interest::READABLE,
33        )
34        .unwrap();
35
36    loop {
37        // Flush requests before polling.
38        con.flush().unwrap();
39        poll.poll(&mut events, None).unwrap();
40        for event in events.iter() {
41            if event.token() == token {
42                queue.dispatch_pending().unwrap();
43                // Reset the watcher to clear the readability status.
44                watcher.reset().unwrap();
45            }
46        }
47        events.clear();
48    }
49}

Methods from Deref<Target = BorrowedQueue>§

Source

pub async fn wait_for_events(&self) -> Result<()>

Completes when there are new events in this queue.

When this function returns Ok(()), this queue has an event queued.

This is a shorthand for calling Connection::wait_for_events with a queue list consisting of exactly this queue.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"queue name");
let display: WlDisplay = queue.display();

let done = Arc::new(AtomicBool::new(false));
let done2 = done.clone();
let sync = display.sync();
proxy::set_event_handler(&sync, WlCallback::on_done(move |_, _| {
    done2.store(true, Release);
}));

while !done.load(Acquire) {
    queue.wait_for_events().await.unwrap();
    queue.dispatch_pending().unwrap();
}
Examples found in repository?
examples/async-wait/main.rs (line 19)
11async fn main() {
12    let lib = Libwayland::open().unwrap();
13    let con = lib.connect_to_default_display().unwrap();
14    let queue = con.create_local_queue(c"async-wait");
15
16    create_sync(&queue, 1);
17
18    loop {
19        queue.wait_for_events().await.unwrap();
20        queue.dispatch_pending().unwrap();
21    }
22}
Source

pub fn wl_event_queue(&self) -> Option<NonNull<wl_event_queue>>

Returns the wl_event_queue representing this queue.

This function returns None if and only if this queue is the default queue of the connection.

The returned pointer, if any, remains valid as long as this object exists.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"queue name");
let default_queue = con.borrow_default_queue();

assert_eq!((**queue).wl_event_queue(), Some(queue.wl_event_queue()));
assert_eq!(default_queue.wl_event_queue(), None);

Trait Implementations§

Source§

impl Clone for Queue

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Queue

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for Queue

Source§

type Target = BorrowedQueue

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl Eq for Queue

Source§

impl PartialEq for Queue

Source§

fn eq(&self, other: &Queue) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Queue

§

impl !UnwindSafe for Queue

§

impl Forget for Queue

§

impl Freeze for Queue
where *const ArcInner<QueueData> is !null: Freeze, PhantomData<ArcInner<QueueData>>: Freeze,

§

impl Move for Queue

§

impl Send for Queue
where Arc<QueueData>: Send,

§

impl Sync for Queue
where Arc<QueueData>: Sync,

§

impl Unpin for Queue
where Arc<QueueData>: Unpin,

§

impl UnsafeUnpin for Queue
where *const ArcInner<QueueData> is !null: UnsafeUnpin, PhantomData<ArcInner<QueueData>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<Lhs, Rhs> IsntPartialEqExt<Lhs, Rhs> for Lhs
where Lhs: PartialEq<Rhs> + ?Sized, Rhs: ?Sized,

Source§

fn not_eq(&self, other: &Rhs) -> bool

The negation of eq
Source§

fn not_ne(&self, other: &Rhs) -> bool

The negation of ne
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.