wl_client/connection/flush.rs
1use crate::Connection;
2#[expect(unused_imports)]
3use crate::QueueWatcher;
4use crate::connection::data::ConnectionData2;
5use crate::utils::executor::Executor;
6use crate::utils::os_error::OsError;
7use crate::utils::poller;
8use crate::utils::poller::Poller;
9use parking_lot::Mutex;
10use std::convert::Infallible;
11use std::future::poll_fn;
12use std::io;
13use std::io::ErrorKind;
14use std::sync::Arc;
15use std::task::Poll;
16use std::task::Waker;
17
18#[cfg(test)]
19mod tests;
20
21pub(super) struct Flusher {
22 data: Arc<Data1>,
23}
24
25#[derive(Default)]
26struct Data1 {
27 data: Mutex<Data2>,
28}
29
30#[derive(Default)]
31struct Data2 {
32 have_request: bool,
33 last_error: Option<OsError>,
34 waker: Option<Waker>,
35}
36
37impl Flusher {
38 pub(super) fn new(poller: &Poller, executor: &Executor, con: &Arc<ConnectionData2>) -> Self {
39 let slf = Self {
40 data: Default::default(),
41 };
42 let con = con.clone();
43 let poll_data = poller.data.clone();
44 let data = slf.data.clone();
45 executor.add(async move {
46 let res: io::Result<Infallible> = async {
47 loop {
48 while let Err(e) = con.try_flush() {
49 match e.kind() {
50 ErrorKind::WouldBlock => {}
51 ErrorKind::Interrupted => continue,
52 _ => return Err(e),
53 }
54 poller::writable(&poll_data).await?;
55 }
56 poll_fn(|ctx| {
57 let d = &mut *data.data.lock();
58 if d.have_request {
59 d.have_request = false;
60 d.waker = None;
61 Poll::Ready(())
62 } else {
63 d.waker = Some(ctx.waker().clone());
64 Poll::Pending
65 }
66 })
67 .await;
68 }
69 }
70 .await;
71 let err = res.unwrap_err();
72 let d = &mut *data.data.lock();
73 d.last_error = Some(err.into());
74 });
75 slf
76 }
77}
78
79impl Connection {
80 /// Schedules outgoing messages to be sent to the compositor.
81 ///
82 /// This function must be used if the application uses a [`QueueWatcher`] to integrate
83 /// the connection into an event loop. The blocking or async integration methods
84 /// perform a flush automatically.
85 ///
86 /// This function never blocks. It only schedules messages to be flushed on another
87 /// thread.
88 ///
89 /// # Example
90 ///
91 /// ```
92 /// # use std::os::fd::AsRawFd;
93 /// # use mio::Interest;
94 /// # use mio::unix::SourceFd;
95 /// # use wl_client::Libwayland;
96 /// # use wl_client::test_protocols::core::wl_display::WlDisplay;
97 /// #
98 /// let lib = Libwayland::open().unwrap();
99 /// let con = lib.connect_to_default_display().unwrap();
100 /// let queue = con.create_queue(c"queue name");
101 /// let watcher = queue.create_watcher().unwrap();
102 /// let token = mio::Token(0);
103 /// let mut events = mio::Events::with_capacity(2);
104 /// let mut poll = mio::Poll::new().unwrap();
105 /// poll
106 /// .registry()
107 /// .register(&mut SourceFd(&watcher.as_raw_fd()), token, Interest::READABLE)
108 /// .unwrap();
109 ///
110 /// // perform requests
111 /// // ...
112 /// # let _sync = queue.display::<WlDisplay>().sync();
113 ///
114 /// // flush the requests
115 /// con.flush().unwrap();
116 ///
117 /// // wait for new events
118 /// poll.poll(&mut events, None).unwrap();
119 /// ```
120 pub fn flush(&self) -> io::Result<()> {
121 let data = &self.data.flusher.data;
122 let d = &mut *data.data.lock();
123 if let Some(err) = d.last_error {
124 return Err(err.into());
125 }
126 d.have_request = true;
127 if let Some(waker) = d.waker.take() {
128 waker.wake();
129 }
130 Ok(())
131 }
132}
133
134impl ConnectionData2 {
135 fn try_flush(&self) -> io::Result<()> {
136 // SAFETY: The display function returns a valid pointer.
137 let ret = unsafe { self.libwayland.wl_display_flush(self.wl_display().as_ptr()) };
138 if ret == -1 {
139 return Err(io::Error::last_os_error());
140 }
141 Ok(())
142 }
143}