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

The Wayland connection

This is the main type representing your connection to the Wayland server, though most of the interaction with the protocol are actually done using other types. The two main uses a simple app has for the Connection are:

It can be created through the connect_to_env() method to follow the configuration from the environment (which is what you’ll do most of the time), or using the from_socket() method if you retrieved your connected Wayland socket through other means.

In case you need to plug yourself into an external Wayland connection that you don’t control, you’ll likely get access to it as a Backend, in which case you can create a Connection from it using the from_backend method.

Implementations§

Try to connect to the Wayland server following the environment

This is the standard way to initialize a Wayland connection.

Initialize a Wayland connection from an already existing Unix stream

Get the WlDisplay associated with this connection

Examples found in repository?
src/event_queue.rs (line 417)
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
    pub fn roundtrip(&mut self, data: &mut State) -> Result<usize, DispatchError> {
        let done = Arc::new(SyncData::default());

        let display = self.conn.display();
        self.conn
            .send_request(
                &display,
                crate::protocol::wl_display::Request::Sync {},
                Some(done.clone()),
            )
            .map_err(|_| WaylandError::Io(Error::EPIPE.into()))?;

        let mut dispatched = 0;

        while !done.done.load(Ordering::Relaxed) {
            dispatched += self.blocking_dispatch(data)?;
        }

        Ok(dispatched)
    }
More examples
Hide additional examples
src/globals.rs (line 84)
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
pub fn registry_queue_init<State>(
    conn: &Connection,
) -> Result<(GlobalList, EventQueue<State>), GlobalError>
where
    State: Dispatch<wl_registry::WlRegistry, GlobalListContents> + 'static,
{
    let event_queue = conn.new_event_queue();
    let display = conn.display();
    let data = Arc::new(RegistryState {
        globals: GlobalListContents { contents: Default::default() },
        handle: event_queue.handle(),
        initial_roundtrip_done: AtomicBool::new(false),
    });
    let registry = display.send_constructor(wl_display::Request::GetRegistry {}, data.clone())?;
    // We don't need to dispatch the event queue as for now nothing will be sent to it
    conn.roundtrip()?;
    data.initial_roundtrip_done.store(true, Ordering::Relaxed);
    Ok((GlobalList { registry }, event_queue))
}
src/conn.rs (line 152)
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
    pub fn roundtrip(&self) -> Result<usize, WaylandError> {
        let done = Arc::new(SyncData::default());
        let display = self.display();
        self.send_request(
            &display,
            crate::protocol::wl_display::Request::Sync {},
            Some(done.clone()),
        )
        .map_err(|_| WaylandError::Io(Error::EPIPE.into()))?;

        let mut dispatched = 0;

        loop {
            self.backend.flush()?;

            // first, prepare the read
            let guard = self.backend.prepare_read()?;

            // If another thread processed events prior to prepare_read, we might already be done.
            if done.done.load(Ordering::Relaxed) {
                break;
            }

            dispatched += blocking_read(guard)?;

            // see if the successful read included our callback
            if done.done.load(Ordering::Relaxed) {
                break;
            }
        }

        Ok(dispatched)
    }

Create a new event queue

Examples found in repository?
src/globals.rs (line 83)
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
pub fn registry_queue_init<State>(
    conn: &Connection,
) -> Result<(GlobalList, EventQueue<State>), GlobalError>
where
    State: Dispatch<wl_registry::WlRegistry, GlobalListContents> + 'static,
{
    let event_queue = conn.new_event_queue();
    let display = conn.display();
    let data = Arc::new(RegistryState {
        globals: GlobalListContents { contents: Default::default() },
        handle: event_queue.handle(),
        initial_roundtrip_done: AtomicBool::new(false),
    });
    let registry = display.send_constructor(wl_display::Request::GetRegistry {}, data.clone())?;
    // We don't need to dispatch the event queue as for now nothing will be sent to it
    conn.roundtrip()?;
    data.initial_roundtrip_done.store(true, Ordering::Relaxed);
    Ok((GlobalList { registry }, event_queue))
}

Wrap an existing Backend into a Connection

Examples found in repository?
src/lib.rs (line 380)
376
377
378
379
380
381
382
    pub fn upgrade(&self) -> Result<I, InvalidId> {
        let backend = self.backend.upgrade().ok_or(InvalidId)?;
        // Check if the object has been destroyed
        backend.info(self.id.clone())?;
        let conn = Connection::from_backend(backend);
        I::from_id(&conn, self.id.clone())
    }
More examples
Hide additional examples
src/globals.rs (line 267)
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
    fn event(
        self: Arc<Self>,
        backend: &Backend,
        msg: Message<ObjectId, OwnedFd>,
    ) -> Option<Arc<dyn ObjectData>> {
        let conn = Connection::from_backend(backend.clone());

        // The registry messages don't contain any fd, so use some type trickery to
        // clone the message
        #[derive(Debug, Clone)]
        enum Void {}
        let msg: Message<ObjectId, Void> = msg.map_fd(|_| unreachable!());
        let to_forward = if self.initial_roundtrip_done.load(Ordering::Relaxed) {
            Some(msg.clone().map_fd(|v| match v {}))
        } else {
            None
        };
        // and restore the type
        let msg = msg.map_fd(|v| match v {});

        // Can't do much if the server sends a malformed message
        if let Ok((_, event)) = wl_registry::WlRegistry::parse_event(&conn, msg) {
            match event {
                wl_registry::Event::Global { name, interface, version } => {
                    let mut guard = self.globals.contents.lock().unwrap();
                    guard.push(Global { name, interface, version });
                }

                wl_registry::Event::GlobalRemove { name: remove } => {
                    let mut guard = self.globals.contents.lock().unwrap();
                    guard.retain(|Global { name, .. }| name != &remove);
                }
            }
        };

        if let Some(msg) = to_forward {
            // forward the message to the event queue as normal
            self.handle
                .inner
                .lock()
                .unwrap()
                .enqueue_event::<wl_registry::WlRegistry, GlobalListContents>(msg, self.clone())
        }

        // We do not create any objects in this event handler.
        None
    }

Get the Backend underlying this Connection

Flush pending outgoing events to the server

This needs to be done regularly to ensure the server receives all your requests, though several dispatching methods do it implicitly (this is stated in their documentation when they do).

Examples found in repository?
src/event_queue.rs (line 392)
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
    pub fn blocking_dispatch(&mut self, data: &mut State) -> Result<usize, DispatchError> {
        let dispatched = self.dispatch_pending(data)?;
        if dispatched > 0 {
            return Ok(dispatched);
        }

        self.conn.flush()?;

        let guard = self.conn.prepare_read()?;

        // we need to check the queue again, just in case another thread did a read between
        // dispatch_pending and prepare_read
        if self.handle.inner.lock().unwrap().queue.is_empty() {
            crate::conn::blocking_read(guard)?;
        } else {
            drop(guard);
        }

        self.dispatch_pending(data)
    }

    /// Synchronous roundtrip
    ///
    /// This function will cause a synchronous round trip with the wayland server. This function will block
    /// until all requests in the queue are sent and processed by the server.
    ///
    /// This function may be useful during initial setup of your app. This function may also be useful
    /// where you need to guarantee all requests prior to calling this function are completed.
    pub fn roundtrip(&mut self, data: &mut State) -> Result<usize, DispatchError> {
        let done = Arc::new(SyncData::default());

        let display = self.conn.display();
        self.conn
            .send_request(
                &display,
                crate::protocol::wl_display::Request::Sync {},
                Some(done.clone()),
            )
            .map_err(|_| WaylandError::Io(Error::EPIPE.into()))?;

        let mut dispatched = 0;

        while !done.done.load(Ordering::Relaxed) {
            dispatched += self.blocking_dispatch(data)?;
        }

        Ok(dispatched)
    }

    /// Start a synchronized read from the socket
    ///
    /// This is needed if you plan to wait on readiness of the Wayland socket using an event
    /// loop. See the [`EventQueue`] and [`ReadEventsGuard`] docs for details. Once the events are received,
    /// you'll then need to dispatch them from the event queue using
    /// [`EventQueue::dispatch_pending()`](EventQueue::dispatch_pending).
    ///
    /// If you don't need to manage multiple event sources, see
    /// [`blocking_dispatch()`](EventQueue::blocking_dispatch) for a simpler mechanism.
    ///
    /// This method is identical to [`Connection::prepare_read()`].
    pub fn prepare_read(&self) -> Result<ReadEventsGuard, WaylandError> {
        self.conn.prepare_read()
    }

    /// Flush pending outgoing events to the server
    ///
    /// This needs to be done regularly to ensure the server receives all your requests.
    /// /// This method is identical to [`Connection::flush()`].
    pub fn flush(&self) -> Result<(), WaylandError> {
        self.conn.flush()
    }

Start a synchronized read from the socket

This is needed if you plan to wait on readiness of the Wayland socket using an event loop. See ReadEventsGuard for details. Once the events are received, you’ll then need to dispatch them from their event queues using EventQueue::dispatch_pending().

If you don’t need to manage multiple event sources, see blocking_dispatch() for a simpler mechanism.

Examples found in repository?
src/event_queue.rs (line 394)
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
    pub fn blocking_dispatch(&mut self, data: &mut State) -> Result<usize, DispatchError> {
        let dispatched = self.dispatch_pending(data)?;
        if dispatched > 0 {
            return Ok(dispatched);
        }

        self.conn.flush()?;

        let guard = self.conn.prepare_read()?;

        // we need to check the queue again, just in case another thread did a read between
        // dispatch_pending and prepare_read
        if self.handle.inner.lock().unwrap().queue.is_empty() {
            crate::conn::blocking_read(guard)?;
        } else {
            drop(guard);
        }

        self.dispatch_pending(data)
    }

    /// Synchronous roundtrip
    ///
    /// This function will cause a synchronous round trip with the wayland server. This function will block
    /// until all requests in the queue are sent and processed by the server.
    ///
    /// This function may be useful during initial setup of your app. This function may also be useful
    /// where you need to guarantee all requests prior to calling this function are completed.
    pub fn roundtrip(&mut self, data: &mut State) -> Result<usize, DispatchError> {
        let done = Arc::new(SyncData::default());

        let display = self.conn.display();
        self.conn
            .send_request(
                &display,
                crate::protocol::wl_display::Request::Sync {},
                Some(done.clone()),
            )
            .map_err(|_| WaylandError::Io(Error::EPIPE.into()))?;

        let mut dispatched = 0;

        while !done.done.load(Ordering::Relaxed) {
            dispatched += self.blocking_dispatch(data)?;
        }

        Ok(dispatched)
    }

    /// Start a synchronized read from the socket
    ///
    /// This is needed if you plan to wait on readiness of the Wayland socket using an event
    /// loop. See the [`EventQueue`] and [`ReadEventsGuard`] docs for details. Once the events are received,
    /// you'll then need to dispatch them from the event queue using
    /// [`EventQueue::dispatch_pending()`](EventQueue::dispatch_pending).
    ///
    /// If you don't need to manage multiple event sources, see
    /// [`blocking_dispatch()`](EventQueue::blocking_dispatch) for a simpler mechanism.
    ///
    /// This method is identical to [`Connection::prepare_read()`].
    pub fn prepare_read(&self) -> Result<ReadEventsGuard, WaylandError> {
        self.conn.prepare_read()
    }

Do a roundtrip to the server

This method will block until the Wayland server has processed and answered all your preceding requests. This is notably useful during the initial setup of an app, to wait for the initial state from the server.

See EventQueue::roundtrip() for a version that includes the dispatching of the event queue.

Examples found in repository?
src/globals.rs (line 92)
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
pub fn registry_queue_init<State>(
    conn: &Connection,
) -> Result<(GlobalList, EventQueue<State>), GlobalError>
where
    State: Dispatch<wl_registry::WlRegistry, GlobalListContents> + 'static,
{
    let event_queue = conn.new_event_queue();
    let display = conn.display();
    let data = Arc::new(RegistryState {
        globals: GlobalListContents { contents: Default::default() },
        handle: event_queue.handle(),
        initial_roundtrip_done: AtomicBool::new(false),
    });
    let registry = display.send_constructor(wl_display::Request::GetRegistry {}, data.clone())?;
    // We don't need to dispatch the event queue as for now nothing will be sent to it
    conn.roundtrip()?;
    data.initial_roundtrip_done.store(true, Ordering::Relaxed);
    Ok((GlobalList { registry }, event_queue))
}

Retrieve the protocol error that occured on the connection if any

If this method returns Some, it means your Wayland connection is already dead.

Send a request associated with the provided object

This is a low-level interface used by the code generated by wayland-scanner, you will likely instead use the methods of the types representing each interface, or the Proxy::send_request and Proxy::send_constructor

Examples found in repository?
src/event_queue.rs (lines 419-423)
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
    pub fn roundtrip(&mut self, data: &mut State) -> Result<usize, DispatchError> {
        let done = Arc::new(SyncData::default());

        let display = self.conn.display();
        self.conn
            .send_request(
                &display,
                crate::protocol::wl_display::Request::Sync {},
                Some(done.clone()),
            )
            .map_err(|_| WaylandError::Io(Error::EPIPE.into()))?;

        let mut dispatched = 0;

        while !done.done.load(Ordering::Relaxed) {
            dispatched += self.blocking_dispatch(data)?;
        }

        Ok(dispatched)
    }
More examples
Hide additional examples
src/conn.rs (lines 153-157)
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
    pub fn roundtrip(&self) -> Result<usize, WaylandError> {
        let done = Arc::new(SyncData::default());
        let display = self.display();
        self.send_request(
            &display,
            crate::protocol::wl_display::Request::Sync {},
            Some(done.clone()),
        )
        .map_err(|_| WaylandError::Io(Error::EPIPE.into()))?;

        let mut dispatched = 0;

        loop {
            self.backend.flush()?;

            // first, prepare the read
            let guard = self.backend.prepare_read()?;

            // If another thread processed events prior to prepare_read, we might already be done.
            if done.done.load(Ordering::Relaxed) {
                break;
            }

            dispatched += blocking_read(guard)?;

            // see if the successful read included our callback
            if done.done.load(Ordering::Relaxed) {
                break;
            }
        }

        Ok(dispatched)
    }

Get the protocol information related to given object ID

Get the object data for a given object ID

This is a low-level interface used by the code generated by wayland-scanner, a higher-level interface for manipulating the user-data assocated to Dispatch implementations is given as Proxy::data(). Also see Proxy::object_data().

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.

Returns the argument unchanged.

Calls U::from(self).

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

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.