Struct wayland_client::Connection
source · 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:
- Obtaining the initial
WlDisplay
through thedisplay()
method. - Creating new
EventQueue
s with thenew_event_queue()
method.
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§
source§impl Connection
impl Connection
sourcepub fn connect_to_env() -> Result<Self, ConnectError>
pub fn connect_to_env() -> Result<Self, ConnectError>
Try to connect to the Wayland server following the environment
This is the standard way to initialize a Wayland connection.
sourcepub fn from_socket(stream: UnixStream) -> Result<Self, ConnectError>
pub fn from_socket(stream: UnixStream) -> Result<Self, ConnectError>
Initialize a Wayland connection from an already existing Unix stream
sourcepub fn display(&self) -> WlDisplay
pub fn display(&self) -> WlDisplay
Get the WlDisplay
associated with this connection
Examples found in repository?
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
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))
}
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)
}
sourcepub fn new_event_queue<State>(&self) -> EventQueue<State>
pub fn new_event_queue<State>(&self) -> EventQueue<State>
Create a new event queue
Examples found in repository?
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))
}
sourcepub fn from_backend(backend: Backend) -> Self
pub fn from_backend(backend: Backend) -> Self
Wrap an existing Backend
into a Connection
Examples found in repository?
More examples
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
}
sourcepub fn backend(&self) -> Backend
pub fn backend(&self) -> Backend
Get the Backend
underlying this Connection
sourcepub fn flush(&self) -> Result<(), WaylandError>
pub fn flush(&self) -> Result<(), WaylandError>
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?
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()
}
sourcepub fn prepare_read(&self) -> Result<ReadEventsGuard, WaylandError>
pub fn prepare_read(&self) -> Result<ReadEventsGuard, WaylandError>
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?
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()
}
sourcepub fn roundtrip(&self) -> Result<usize, WaylandError>
pub fn roundtrip(&self) -> Result<usize, WaylandError>
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?
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))
}
sourcepub fn protocol_error(&self) -> Option<ProtocolError>
pub fn protocol_error(&self) -> Option<ProtocolError>
Retrieve the protocol error that occured on the connection if any
If this method returns Some
, it means your Wayland connection is already dead.
sourcepub fn send_request<I: Proxy>(
&self,
proxy: &I,
request: I::Request,
data: Option<Arc<dyn ObjectData>>
) -> Result<ObjectId, InvalidId>
pub fn send_request<I: Proxy>(
&self,
proxy: &I,
request: I::Request,
data: Option<Arc<dyn ObjectData>>
) -> Result<ObjectId, InvalidId>
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?
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
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)
}
sourcepub fn object_info(&self, id: ObjectId) -> Result<ObjectInfo, InvalidId>
pub fn object_info(&self, id: ObjectId) -> Result<ObjectInfo, InvalidId>
Get the protocol information related to given object ID
sourcepub fn get_object_data(
&self,
id: ObjectId
) -> Result<Arc<dyn ObjectData>, InvalidId>
pub fn get_object_data(
&self,
id: ObjectId
) -> Result<Arc<dyn ObjectData>, InvalidId>
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§
source§impl Clone for Connection
impl Clone for Connection
source§fn clone(&self) -> Connection
fn clone(&self) -> Connection
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moreAuto Trait Implementations§
impl RefUnwindSafe for Connection
impl Send for Connection
impl Sync for Connection
impl Unpin for Connection
impl UnwindSafe for Connection
Blanket Implementations§
§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§fn into_any(self: Box<T, Global>) -> Box<dyn Any + 'static, Global>
fn into_any(self: Box<T, Global>) -> Box<dyn Any + 'static, Global>
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
.§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.