From adb19083ad4c2b81618f26c791ad448791623e2a Mon Sep 17 00:00:00 2001 From: MaxVerevkin Date: Thu, 18 Apr 2024 08:39:02 +0300 Subject: [PATCH] client: add exmaple of how to use custom transports --- wayrs-client/examples/custom_transport.rs | 87 +++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 wayrs-client/examples/custom_transport.rs diff --git a/wayrs-client/examples/custom_transport.rs b/wayrs-client/examples/custom_transport.rs new file mode 100644 index 0000000..244ab41 --- /dev/null +++ b/wayrs-client/examples/custom_transport.rs @@ -0,0 +1,87 @@ +//! An example of how to use your own custom transport implementation. +//! Here, the transport keeps track of how much bytes were sent/received. + +use std::collections::VecDeque; +use std::env; +use std::io; +use std::os::fd::{OwnedFd, RawFd}; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; + +use wayrs_client::core::transport::Transport; +use wayrs_client::protocol::wl_registry; +use wayrs_client::{ConnectionBuilder, IoMode}; + +fn main() { + let mut conn = ConnectionBuilder::with_transport(MyTransport::connect()).build(); + + conn.add_registry_cb(|_conn, _state, event| match event { + wl_registry::Event::Global(g) => println!( + "global ({}) {} added", + g.name, + g.interface.to_string_lossy(), + ), + wl_registry::Event::GlobalRemove(name) => println!("global ({name}) removed"), + _ => unreachable!(), + }); + + loop { + conn.flush(IoMode::Blocking).unwrap(); + conn.recv_events(IoMode::Blocking).unwrap(); + conn.dispatch_events(&mut ()); + + let t = conn.transport::().unwrap(); + eprintln!("up: {}b down: {}b", t.bytes_sent, t.bytes_read); + } +} + +struct MyTransport { + socket: UnixStream, + bytes_read: usize, + bytes_sent: usize, +} + +impl Transport for MyTransport { + fn pollable_fd(&self) -> RawFd { + self.socket.pollable_fd() + } + + fn send( + &mut self, + bytes: &[std::io::IoSlice], + fds: &[OwnedFd], + mode: IoMode, + ) -> io::Result { + let n = self.socket.send(bytes, fds, mode)?; + self.bytes_sent += n; + Ok(n) + } + + fn recv( + &mut self, + bytes: &mut [std::io::IoSliceMut], + fds: &mut VecDeque, + mode: IoMode, + ) -> io::Result { + let n = self.socket.recv(bytes, fds, mode)?; + self.bytes_read += n; + Ok(n) + } +} + +impl MyTransport { + fn connect() -> Self { + let runtime_dir = env::var_os("XDG_RUNTIME_DIR").unwrap(); + let wayland_disp = env::var_os("WAYLAND_DISPLAY").unwrap(); + + let mut path = PathBuf::new(); + path.push(runtime_dir); + path.push(wayland_disp); + + Self { + socket: UnixStream::connect(path).unwrap(), + bytes_read: 0, + bytes_sent: 0, + } + } +}