wl_client/connection/wait_for_events.rs
1use crate::BorrowedQueue;
2use crate::Connection;
3use crate::Queue;
4use crate::utils::eventfd::Eventfd;
5use crate::utils::executor::TaskId;
6use crate::utils::os_error::OsError;
7use crate::utils::poller;
8use parking_lot::Condvar;
9use parking_lot::Mutex;
10use run_on_drop::on_drop;
11use std::convert::Infallible;
12use std::future::poll_fn;
13use std::io;
14use std::os::fd::AsFd;
15use std::os::fd::AsRawFd;
16use std::os::fd::BorrowedFd;
17use std::os::fd::RawFd;
18use std::sync::Arc;
19use std::sync::atomic::AtomicBool;
20use std::sync::atomic::Ordering::Relaxed;
21use std::task::Poll;
22use std::task::Waker;
23
24#[cfg(test)]
25mod tests;
26
27/// A file descriptor for event-loop integration.
28///
29/// This type wraps a file descriptor that will signal readability when there are events
30/// to be dispatched on one or more queues.
31///
32/// You can construct this type by calling [`Connection::create_watcher`],
33/// [`Queue::create_watcher`], or [`BorrowedQueue::create_watcher`].
34///
35/// The contained file descriptor is opaque. You should not interact with it except by
36/// polling it for readability.
37///
38/// Once the file descriptor signals readability, the application should
39///
40/// 1. dispatch the queue(s) by calling [`Queue::dispatch_pending`],
41/// 2. reset the readability by calling [`QueueWatcher::reset`],
42/// 3. flush outgoing requests by calling [`Connection::flush`],
43/// 3. wait for the file descriptor to become readable again.
44///
45/// If not all events were dispatched before calling [`QueueWatcher::reset`], then the
46/// file descriptor will become readable again immediately after being reset.
47///
48/// # Example
49///
50/// ```
51/// # use std::os::fd::AsRawFd;
52/// # use mio::Interest;
53/// # use mio::unix::SourceFd;
54/// # use wl_client::Libwayland;
55/// # use wl_client::test_protocols::core::wl_display::WlDisplay;
56/// #
57/// let lib = Libwayland::open().unwrap();
58/// let con = lib.connect_to_default_display().unwrap();
59/// let queue = con.create_queue(c"queue name");
60/// let watcher = queue.create_watcher().unwrap();
61/// let token = mio::Token(0);
62/// # let _sync = queue.display::<WlDisplay>().sync();
63///
64/// let mut events = mio::Events::with_capacity(2);
65/// let mut poll = mio::Poll::new().unwrap();
66/// poll
67/// .registry()
68/// .register(&mut SourceFd(&watcher.as_raw_fd()), token, Interest::READABLE)
69/// .unwrap();
70/// // register other application file descriptors
71///
72/// loop {
73/// // flush outgoing messages before going to sleep
74/// con.flush().unwrap();
75///
76/// poll.poll(&mut events, None).unwrap();
77/// for event in events.iter() {
78/// if event.token() == token {
79/// // dispatch new events
80/// queue.dispatch_pending().unwrap();
81/// // reset the watcher
82/// watcher.reset().unwrap();
83/// }
84/// // handle other file descriptors
85/// }
86/// events.clear();
87/// # break;
88/// }
89/// ```
90#[derive(Clone)]
91pub struct QueueWatcher {
92 data: Arc<QueueWatcherData>,
93}
94
95struct QueueWatcherData {
96 task_id: TaskId,
97 connection: Connection,
98 data: Arc<QueueWatcherShared>,
99}
100
101struct QueueWatcherShared {
102 eventfd: Eventfd,
103 has_error: AtomicBool,
104 data: Mutex<QueueWatcherMutable>,
105 cancellation: Condvar,
106}
107
108#[derive(Default)]
109struct QueueWatcherMutable {
110 wait_for_reset: bool,
111 waker: Option<Waker>,
112 last_error: Option<OsError>,
113 cancelled: bool,
114}
115
116impl Connection {
117 /// Waits for events on any number of event queues.
118 ///
119 /// When this function returns `Ok(())`, at least one of the event queues has an event
120 /// queued.
121 ///
122 /// If no other thread is dispatching these queues, then this function will return
123 /// `Ok(())` as soon as this happens.
124 ///
125 /// If the list of queues is empty, this function waits indefinitely.
126 ///
127 /// This function flushes all requests made before this function call.
128 ///
129 /// # Panic
130 ///
131 /// This function panics if the queues do not all belong to this connection.
132 pub async fn wait_for_events(&self, queues: &[&BorrowedQueue]) -> io::Result<()> {
133 self.flush()?;
134 self.wait_for_events_without_flush(queues).await
135 }
136
137 pub(crate) async fn wait_for_events_without_flush(
138 &self,
139 queues: &[&BorrowedQueue],
140 ) -> io::Result<()> {
141 for queue in queues {
142 if queue.connection() != self {
143 wrong_con();
144 }
145 }
146 loop {
147 let mut lock = None;
148 if let Some((first, other)) = queues.split_first() {
149 let Some(l) = self.acquire_read_lock_async(first).await else {
150 return Ok(());
151 };
152 lock = Some(l);
153 for queue in other {
154 if self.queue_has_events(queue) {
155 return Ok(());
156 }
157 }
158 }
159 self.data.data.ensure_no_error()?;
160 let poll_data = self.data.poller.data.clone();
161 // NOTE: We cannot hold on to the lock on this thread since that could cause
162 // a deadlock when another task on this thread calls
163 // wl_display_read_events. Instead we move the lock and the wait to
164 // the executor thread which will make progress and call
165 // wl_display_read_events as soon as there are new events, even if this
166 // thread is blocked.
167 self.data
168 .executor
169 .execute::<io::Result<()>, _>(async move {
170 poller::readable(&poll_data).await?;
171 if let Some(lock) = lock {
172 lock.read_events().await?;
173 }
174 Ok(())
175 })
176 .await?;
177 }
178 }
179
180 /// Creates a [`QueueWatcher`] for event-loop integration.
181 ///
182 /// See the documentation of [`QueueWatcher`] for details on when and how an
183 /// application would use this.
184 ///
185 /// # Panic
186 ///
187 /// This function panics if the queues do not all belong to this connection.
188 pub fn create_watcher(
189 &self,
190 owned: &[&Queue],
191 borrowed: impl IntoIterator<Item = BorrowedQueue>,
192 ) -> io::Result<QueueWatcher> {
193 self.create_watcher_(owned, borrowed.into_iter().collect())
194 }
195
196 /// Creates a [`QueueWatcher`] for event-loop integration.
197 ///
198 /// See the documentation of [`QueueWatcher`] for details on when and how an
199 /// application would use this.
200 ///
201 /// # Panic
202 ///
203 /// This function panics if the queues do not all belong to this connection.
204 fn create_watcher_(
205 &self,
206 owned: &[&Queue],
207 borrowed: Vec<BorrowedQueue>,
208 ) -> io::Result<QueueWatcher> {
209 for q in owned {
210 if q.connection() != self {
211 wrong_con();
212 }
213 }
214 for q in &borrowed {
215 if q.connection() != self {
216 wrong_con();
217 }
218 }
219 let shared = Arc::new(QueueWatcherShared {
220 eventfd: Eventfd::new()?,
221 has_error: Default::default(),
222 data: Default::default(),
223 cancellation: Default::default(),
224 });
225 /// This type contains the queues that are transferred into the task of a [`QueueWatcher`].
226 ///
227 /// This type exists so that [`QueueWatcherData::drop`] can block until these objects
228 /// have definitely been dropped by the executor. This is achieved as follows: Rust
229 /// guarantees that fields are dropped from top to bottom. Therefore, when the drop impl
230 /// of `_f` runs, `owned` and `borrowed` have already been dropped.
231 ///
232 /// Blocking is required for two reasons:
233 ///
234 /// 1. The user of [`QueueWatcher`] must keep the underlying queues alive while any of the
235 /// [`BorrowedQueue`] still exist. If the drop impl did not block, the user would be
236 /// unable to determine when the [`BorrowedQueue`] have been dropped.
237 /// 2. The queues contain clones of the [`Connection`]. The last clone of the connection
238 /// must not be dropped in the executor thread since the executor thread would then try
239 /// to join itself.
240 struct CancelData<F> {
241 connection: Connection,
242 shared: Arc<QueueWatcherShared>,
243 owned: Vec<Queue>,
244 borrowed: Vec<BorrowedQueue>,
245 _f: F,
246 }
247 let cancel_data = CancelData {
248 connection: self.clone(),
249 shared: shared.clone(),
250 owned: owned.iter().map(|q| (*q).clone()).collect(),
251 borrowed,
252 _f: on_drop({
253 let shared = shared.clone();
254 move || {
255 shared.data.lock().cancelled = true;
256 shared.cancellation.notify_all();
257 }
258 }),
259 };
260 let task_id = self.data.executor.add(async move {
261 let cancel_data = cancel_data;
262 let mut qs = vec![];
263 for q in &cancel_data.owned {
264 qs.push(&**q);
265 }
266 for q in &cancel_data.borrowed {
267 qs.push(q);
268 }
269 let res: io::Result<Infallible> = async {
270 loop {
271 cancel_data
272 .connection
273 .wait_for_events_without_flush(&qs)
274 .await?;
275 cancel_data.shared.eventfd.bump()?;
276 poll_fn(|ctx| {
277 let d = &mut *cancel_data.shared.data.lock();
278 if d.wait_for_reset {
279 d.waker = Some(ctx.waker().clone());
280 Poll::Pending
281 } else {
282 d.wait_for_reset = true;
283 d.waker = None;
284 Poll::Ready(())
285 }
286 })
287 .await;
288 }
289 }
290 .await;
291 let e = res.unwrap_err();
292 cancel_data.shared.data.lock().last_error = Some(e.into());
293 cancel_data.shared.has_error.store(true, Relaxed);
294 });
295 let data = Arc::new(QueueWatcherData {
296 task_id,
297 connection: self.clone(),
298 data: shared,
299 });
300 Ok(QueueWatcher { data })
301 }
302}
303
304impl QueueWatcher {
305 /// Resets the file descriptor readability.
306 ///
307 /// The file descriptor will become readable again when there are events to be
308 /// dispatched.
309 pub fn reset(&self) -> io::Result<()> {
310 let data = &*self.data.data;
311 if data.has_error.load(Relaxed)
312 && let Some(e) = data.data.lock().last_error
313 {
314 return Err(e.into());
315 }
316 data.eventfd.clear()?;
317 let d = &mut *data.data.lock();
318 if let Some(e) = d.last_error {
319 let _ = data.eventfd.bump();
320 return Err(e.into());
321 }
322 d.wait_for_reset = false;
323 if let Some(waker) = d.waker.take() {
324 waker.wake()
325 }
326 Ok(())
327 }
328}
329
330impl Drop for QueueWatcherData {
331 fn drop(&mut self) {
332 self.connection.data.executor.cancel(self.task_id);
333 let mut lock = self.data.data.lock();
334 while !lock.cancelled {
335 self.data.cancellation.wait(&mut lock);
336 }
337 }
338}
339
340impl AsFd for QueueWatcher {
341 fn as_fd(&self) -> BorrowedFd<'_> {
342 self.data.data.eventfd.as_fd()
343 }
344}
345
346impl AsRawFd for QueueWatcher {
347 fn as_raw_fd(&self) -> RawFd {
348 self.as_fd().as_raw_fd()
349 }
350}
351
352impl AsRawFd for &'_ QueueWatcher {
353 fn as_raw_fd(&self) -> RawFd {
354 self.as_fd().as_raw_fd()
355 }
356}
357
358#[cold]
359fn wrong_con() -> ! {
360 panic!("queue does not belong to this connection");
361}