Connection

Struct Connection 

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

A connection to a wayland compositor.

You can create a connection by using one of the methods on Libwayland.

Each connection wraps a libwayland wl_display pointer. This pointer can be owned or borrowed. If the pointer is owned by the time the last reference to the connection is dropped, the wl_display is destroyed. If the connection owns the pointer, you can take ownership of the pointer by calling Connection::take_ownership.

§Example

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

Implementations§

Source§

impl Connection

Source

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

Schedules outgoing messages to be sent to the compositor.

This function must be used if the application uses a QueueWatcher to integrate the connection into an event loop. The blocking or async integration methods perform a flush automatically.

This function never blocks. It only schedules messages to be flushed on another thread.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let queue = con.create_queue(c"queue name");
let watcher = queue.create_watcher().unwrap();
let token = mio::Token(0);
let mut events = mio::Events::with_capacity(2);
let mut poll = mio::Poll::new().unwrap();
poll
    .registry()
    .register(&mut SourceFd(&watcher.as_raw_fd()), token, Interest::READABLE)
    .unwrap();

// perform requests
// ...

// flush the requests
con.flush().unwrap();

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

impl Connection

Source

pub async fn wait_for_events(&self, queues: &[&BorrowedQueue]) -> Result<()>

Waits for events on any number of event queues.

When this function returns Ok(()), at least one of the event queues has an event queued.

If no other thread is dispatching these queues, then this function will return Ok(()) as soon as this happens.

If the list of queues is empty, this function waits indefinitely.

This function flushes all requests made before this function call.

§Panic

This function panics if the queues do not all belong to this connection.

Source

pub fn create_watcher( &self, owned: &[&Queue], borrowed: impl IntoIterator<Item = BorrowedQueue>, ) -> Result<QueueWatcher>

Creates a QueueWatcher for event-loop integration.

See the documentation of QueueWatcher for details on when and how an application would use this.

§Panic

This function panics if the queues do not all belong to this connection.

Source§

impl Connection

Source

pub fn is_owned(&self) -> bool

Returns whether this connection owns the underlying wl_display.

When the last reference to the connection is dropped, the wl_display will be destroyed if and only if the display is owned at that time.

If this function returns false, then it will always return false.

If this function returns true, then it might return false in the future if ownership is consumed by calling Self::take_ownership.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
assert!(con.is_owned());
let wl_display = con.wl_display();
{
    // SAFETY: - We took the display from a freshly created Connection so it is valid.
    //         - We drop the connection before dropping the outer connection that
    //           owns the wl_display.
    let con = unsafe { lib.wrap_borrowed_pointer(wl_display).unwrap() };
    assert!(con.is_borrowed());
}
Source

pub fn is_borrowed(&self) -> bool

Returns whether this connection borrows the underlying wl_display.

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

Source

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

Returns the underlying wl_display pointer.

This is always a valid pointer.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let _wl_display = con.wl_display();
Source

pub fn take_ownership(&self) -> Option<NonNull<wl_display>>

Takes ownership of the underlying wl_display.

If this returns Some, then ownership has been transferred from the connection to the caller. After this function returns, the connection no longer has ownership of the underlying wl_display and will not destroy the display.

§Example
let lib = Libwayland::open().unwrap();
let wl_display = {
    let con = lib.connect_to_default_display().unwrap();
    con.take_ownership().unwrap()
};
// SAFETY: We took the display from a freshly created Connection so it is valid
//         and has no queues or proxies attached.
let _con = unsafe { lib.wrap_owned_pointer(wl_display) };
Source

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

Returns a reference to the Libwayland singleton.

Source

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

Returns the last error that occurred on the connection, if any.

Since all errors are fatal, if this function returns an error, the connection can no longer be used.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
assert!(con.error().is_ok());
Source§

impl Connection

Source

pub fn create_queue_with_data<T>( &self, name: &CStr, ) -> (QueueOwner, QueueWithData<T>)
where T: 'static,

Creates a new queue with mutable data.

This function is the same as Connection::create_queue except that event handlers attached to this queue can receive a &mut T. When dispatching the queue, a &mut T must be passed into one of the dispatcher functions of QueueWithData. The dispatcher functions declared on Queue cannot be used to dispatch this queue.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let (_queue_owner, _queue) = con.create_queue_with_data::<State>(c"queue name");

struct State {
    // ...
}
Examples found in repository?
examples/get-registry-with-data/main.rs (line 25)
22fn main() {
23    let lib = Libwayland::open().unwrap();
24    let con = lib.connect_to_default_display().unwrap();
25    let (_queue, queue) = con.create_queue_with_data::<State>(c"get-registry");
26
27    // Create a new registry that will receive the globals and can later be used to
28    // bind them.
29    let mut state = State {
30        registry: queue.display::<WlDisplay>().get_registry(),
31        globals: vec![],
32    };
33
34    // Since we only want to create a snapshot, we don't care about
35    // global_remove events. This allows us to use the functional event handler
36    // form.
37    proxy::set_event_handler(
38        &state.registry,
39        WlRegistry::on_global(|state: &mut State, _, name, interface, version| {
40            state.globals.push(Global {
41                name,
42                interface: interface.to_string(),
43                version,
44            });
45        }),
46    );
47    queue.dispatch_roundtrip_blocking(&mut state).unwrap();
48
49    println!("{:#?}", state.globals);
50}
Source

pub fn create_local_queue_with_data<T>( &self, name: &CStr, ) -> (QueueOwner, QueueWithData<T>)
where T: 'static,

Creates a new queue with mutable data.

This function is the same as Connection::create_local_queue except that event handlers attached to this queue can receive a &mut T. When dispatching the queue, a &mut T must be passed into one of the dispatcher functions of QueueWithData. The dispatcher functions declared on Queue cannot be used to dispatch this queue.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let (_queue_owner, _queue) = con.create_local_queue_with_data::<State>(c"queue name");

struct State {
    // ...
}
Source§

impl Connection

Source

pub fn create_queue(&self, name: &CStr) -> QueueOwner

Creates a new queue.

The new queue is not a local queue. It can be dispatched from any thread. Event handlers attached to this queue must implement Send. See the documentation of Queue for a description of local and non-local queues.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let _queue = con.create_queue(c"queue name");
Examples found in repository?
examples/get-registry/main.rs (line 13)
10fn main() {
11    let lib = Libwayland::open().unwrap();
12    let con = lib.connect_to_default_display().unwrap();
13    let queue = con.create_queue(c"get-registry");
14
15    let (_, snapshot) = get_registry_snapshot(&queue);
16    println!("{:#?}", snapshot);
17}
More examples
Hide additional examples
examples/hello-wayland/main.rs (line 16)
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 fn create_local_queue(&self, name: &CStr) -> QueueOwner

Creates a new local queue.

The new queue is a local queue. It can only be dispatched from the thread that called this function. See the documentation of Queue for a description of local and non-local queues.

§Example
let lib = Libwayland::open().unwrap();
let con = lib.connect_to_default_display().unwrap();
let _queue = con.create_local_queue(c"queue name");
Examples found in repository?
examples/async-wait/main.rs (line 13)
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-wait");
14
15    create_sync(&queue, 1);
16
17    loop {
18        queue.wait_for_events().await.unwrap();
19        queue.dispatch_pending().unwrap();
20    }
21}
More examples
Hide additional examples
examples/simple-window/main.rs (line 9)
6fn main() {
7    let lib = Libwayland::open().unwrap();
8    let con = lib.connect_to_default_display().unwrap();
9    let queue = con.create_local_queue(c"simple-window");
10    let singletons = get_singletons(&queue.display());
11    let simple_window = simple_window::prepare(singletons);
12    while !simple_window.exit.get() {
13        queue.dispatch_blocking().unwrap();
14    }
15}
examples/async-window/main.rs (line 12)
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 29)
26fn main() {
27    let lib = Libwayland::open().unwrap();
28    let con = lib.connect_to_default_display().unwrap();
29    let queue = con.create_local_queue(c"keyboard-events");
30    let singletons = get_singletons(&queue.display());
31    let simple_window = simple_window::prepare(singletons);
32
33    let wl_registry = queue.display::<WlDisplay>().get_registry();
34    proxy::set_event_handler_local(
35        &wl_registry,
36        RegistryEventHandler {
37            wl_registry: wl_registry.clone(),
38            seats: Default::default(),
39        },
40    );
41
42    while !simple_window.exit.get() {
43        queue.dispatch_blocking().unwrap();
44    }
45}
examples/async-roundtrip/main.rs (line 14)
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-roundtrip");
15    let registry = queue.display::<WlDisplay>().get_registry();
16    let num_globals = Cell::new(0);
17    queue
18        .dispatch_scope_async(async |scope| {
19            scope.set_event_handler_local(
20                &registry,
21                WlRegistry::on_global(|_, _, _, _| {
22                    num_globals.set(num_globals.get() + 1);
23                }),
24            );
25            // This function can be used to perform an async roundtrip. It is
26            // compatible with any async runtime. This example also demonstrates
27            // that this works in combination with scoped event handlers.
28            queue.dispatch_roundtrip_async().await.unwrap();
29        })
30        .await;
31    println!("number of globals: {}", num_globals.get());
32}
examples/poll-integration/main.rs (line 14)
11fn main() {
12    let lib = Libwayland::open().unwrap();
13    let con = lib.connect_to_default_display().unwrap();
14    let queue = con.create_local_queue(c"poll-integration");
15
16    // The watcher exposes a file descriptor that will become readable when the queue
17    // has new events.
18    let watcher = queue.create_watcher().unwrap();
19    let token = Token(0);
20
21    create_sync(&queue, 1);
22
23    let mut events = mio::Events::with_capacity(2);
24    let mut poll = mio::Poll::new().unwrap();
25    poll.registry()
26        .register(
27            &mut SourceFd(&watcher.as_raw_fd()),
28            token,
29            Interest::READABLE,
30        )
31        .unwrap();
32
33    loop {
34        // Flush requests before polling.
35        con.flush().unwrap();
36        poll.poll(&mut events, None).unwrap();
37        for event in events.iter() {
38            if event.token() == token {
39                queue.dispatch_pending().unwrap();
40                // Reset the watcher to clear the readability status.
41                watcher.reset().unwrap();
42            }
43        }
44        events.clear();
45    }
46}
Source

pub fn borrow_default_queue(&self) -> BorrowedQueue

Creates a BorrowedQueue representing the default queue.

Source

pub unsafe fn borrow_foreign_queue( &self, queue: NonNull<wl_event_queue>, ) -> BorrowedQueue

Creates a BorrowedQueue representing a wl_event_queue pointer.

§Safety
  • The queue must be valid and stay valid for the lifetime of the BorrowedQueue.
  • The queue must belong to this connection.

Trait Implementations§

Source§

impl Clone for Connection

Source§

fn clone(&self) -> Connection

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Connection

Source§

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

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

impl PartialEq for Connection

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Connection

Auto Trait Implementations§

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<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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.