Debian Codegraph @

src/sources/mod.rs

raw symbols SCIP
1 use std::{
2 cell::{Ref, RefCell, RefMut},
3 ops::{BitOr, BitOrAssign},
4 rc::Rc,
5 };
6
7 use crate::{sys::TokenFactory, Poll, Readiness, Token};
8
9 pub mod channel;
10 #[cfg(feature = "executor")]
11 #[cfg_attr(docsrs, doc(cfg(feature = "executor")))]
12 pub mod futures;
13 pub mod generic;
14 pub mod ping;
15 #[cfg(target_os = "linux")]
16 #[cfg_attr(docsrs, doc(cfg(target_os = "linux")))]
17 pub mod signals;
18 pub mod timer;
19 pub mod transient;
20
21 /// Possible actions that can be requested to the event loop by an
22 /// event source once its events have been processed.
23 ///
24 /// `PostAction` values can be combined with the `|` (bit-or) operator (or with
25 /// `|=`) with the result that:
26 /// - if both values are identical, the result is that value
27 /// - if they are different, the result is [`Reregister`](PostAction::Reregister)
28 ///
29 /// Bit-or-ing these results is useful for composed sources to combine the
30 /// results of their child sources, but note that it only applies to the child
31 /// sources. For example, if every child source returns `Continue`, the result
32 /// will be `Continue`, but the parent source might still need to return
33 /// `Reregister` or something else depending on any additional logic it uses.
34 #[derive(Debug, PartialEq, Copy, Clone)]
35 pub enum PostAction {
36 /// Continue listening for events on this source as before
37 Continue,
38 /// Trigger a re-registration of this source
39 Reregister,
40 /// Disable this source
41 ///
42 /// Has the same effect as [`LoopHandle::disable`](crate::LoopHandle#method.disable)
43 Disable,
44 /// Remove this source from the eventloop
45 ///
46 /// Has the same effect as [`LoopHandle::kill`](crate::LoopHandle#method.kill)
47 Remove,
48 }
49
50 /// Combines `PostAction` values returned from nested event sources.
51 impl BitOr for PostAction {
52 type Output = Self;
53
54 fn bitor(self, rhs: Self) -> Self::Output {
55 if matches!(self, x if x == rhs) {
56 self
57 } else {
58 Self::Reregister
59 }
60 }
61 }
62
63 /// Combines `PostAction` values returned from nested event sources.
64 impl BitOrAssign for PostAction {
65 fn bitor_assign(&mut self, rhs: Self) {
66 if *self != rhs {
67 *self = Self::Reregister;
68 }
69 }
70 }
71
72 /// Trait representing an event source
73 ///
74 /// This is the trait you need to implement if you wish to create your own
75 /// calloop-compatible event sources.
76 ///
77 /// The 3 associated types define the type of closure the user will need to
78 /// provide to process events for your event source.
79 ///
80 /// The `process_events` method will be called when one of the FD you registered
81 /// is ready, with the associated readiness and token.
82 ///
83 /// The `register`, `reregister` and `unregister` methods are plumbing to let your
84 /// source register itself with the polling system. See their documentation for details.
85 ///
86 /// In case your event source needs to do some special processing before or after a
87 /// polling session occurs (to prepare the underlying source for polling, and cleanup
88 /// after that), you can override the `pre_run` and `post_run`, that do nothing by
89 /// default. Depending on the underlying events, `process_events` may be invoked once,
90 /// several times, or none at all between `pre_run` and `post_run` are called, but when
91 /// it is invoked, it'll always be between those two.
92 pub trait EventSource {
93 /// The type of events generated by your source.
94 type Event;
95 /// Some metadata of your event source
96 ///
97 /// This is typically useful if your source contains some internal state that
98 /// the user may need to interact with when processing events. The user callback
99 /// will receive a `&mut Metadata` reference.
100 ///
101 /// Set to `()` if not needed.
102 type Metadata;
103 /// The return type of the user callback
104 ///
105 /// If the user needs to return some value back to your event source once its
106 /// processing is finshed (to indicate success or failure for example), you can
107 /// specify it using this type.
108 ///
109 /// Set to `()` if not needed.
110 type Ret;
111 /// The error type returned from
112 /// [`process_events()`](Self::process_events()) (not the user callback!).
113 type Error: Into<Box<dyn std::error::Error + Sync + Send>>;
114
115 /// Process any relevant events
116 ///
117 /// This method will be called every time one of the FD you registered becomes
118 /// ready, including the readiness details and the associated token.
119 ///
120 /// Your event source will then do some processing of the file descriptor(s) to generate
121 /// events, and call the provided `callback` for each one of them.
122 ///
123 /// You should ensure you drained the file descriptors of their events, especially if using
124 /// edge-triggered mode.
125 fn process_events<F>(
126 &mut self,
127 readiness: Readiness,
128 token: Token,
129 callback: F,
130 ) -> Result<PostAction, Self::Error>
131 where
132 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret;
133
134 /// Register yourself to this poll instance
135 ///
136 /// You should register all your relevant file descriptors to the provided [`Poll`](crate::Poll)
137 /// using its [`Poll::register`](crate::Poll#method.register) method.
138 ///
139 /// If you need to register more than one file descriptor, you can change the
140 /// `sub_id` field of the [`Token`](crate::Token) to differentiate between them.
141 fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()>;
142
143 /// Re-register your file descriptors
144 ///
145 /// Your should update the registration of all your relevant file descriptor to
146 /// the provided [`Poll`](crate::Poll) using its [`Poll::reregister`](crate::Poll#method.reregister),
147 /// if necessary.
148 fn reregister(
149 &mut self,
150 poll: &mut Poll,
151 token_factory: &mut TokenFactory,
152 ) -> crate::Result<()>;
153
154 /// Unregister your file descriptors
155 ///
156 /// You should unregister all your file descriptors from this [`Poll`](crate::Poll) using its
157 /// [`Poll::unregister`](crate::Poll#method.unregister) method.
158 fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()>;
159
160 /// Notification that a polling session is going to start
161 ///
162 /// You can generate events from this method as you would from `process_events`.
163 fn pre_run<F>(&mut self, _callback: F) -> crate::Result<()>
164 where
165 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
166 {
167 Ok(())
168 }
169
170 /// Notification that the current polling session ended
171 ///
172 /// You can generate events from this method as you would from `process_events`.
173 fn post_run<F>(&mut self, _callback: F) -> crate::Result<()>
174 where
175 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
176 {
177 Ok(())
178 }
179 }
180
181 /// Blanket implementation for boxed event sources. [`EventSource`] is not an
182 /// object safe trait, so this does not include trait objects.
183 impl<T: EventSource> EventSource for Box<T> {
184 type Event = T::Event;
185 type Metadata = T::Metadata;
186 type Ret = T::Ret;
187 type Error = T::Error;
188
189 fn process_events<F>(
190 &mut self,
191 readiness: Readiness,
192 token: Token,
193 callback: F,
194 ) -> Result<PostAction, Self::Error>
195 where
196 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
197 {
198 T::process_events(&mut **self, readiness, token, callback)
199 }
200
201 fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> {
202 T::register(&mut **self, poll, token_factory)
203 }
204
205 fn reregister(
206 &mut self,
207 poll: &mut Poll,
208 token_factory: &mut TokenFactory,
209 ) -> crate::Result<()> {
210 T::reregister(&mut **self, poll, token_factory)
211 }
212
213 fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> {
214 T::unregister(&mut **self, poll)
215 }
216
217 fn pre_run<F>(&mut self, callback: F) -> crate::Result<()>
218 where
219 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
220 {
221 T::pre_run(&mut **self, callback)
222 }
223
224 fn post_run<F>(&mut self, callback: F) -> crate::Result<()>
225 where
226 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
227 {
228 T::post_run(&mut **self, callback)
229 }
230 }
231
232 /// Blanket implementation for exclusive references to event sources.
233 /// [`EventSource`] is not an object safe trait, so this does not include trait
234 /// objects.
235 impl<T: EventSource> EventSource for &mut T {
236 type Event = T::Event;
237 type Metadata = T::Metadata;
238 type Ret = T::Ret;
239 type Error = T::Error;
240
241 fn process_events<F>(
242 &mut self,
243 readiness: Readiness,
244 token: Token,
245 callback: F,
246 ) -> Result<PostAction, Self::Error>
247 where
248 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
249 {
250 T::process_events(&mut **self, readiness, token, callback)
251 }
252
253 fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> {
254 T::register(&mut **self, poll, token_factory)
255 }
256
257 fn reregister(
258 &mut self,
259 poll: &mut Poll,
260 token_factory: &mut TokenFactory,
261 ) -> crate::Result<()> {
262 T::reregister(&mut **self, poll, token_factory)
263 }
264
265 fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> {
266 T::unregister(&mut **self, poll)
267 }
268
269 fn pre_run<F>(&mut self, callback: F) -> crate::Result<()>
270 where
271 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
272 {
273 T::pre_run(&mut **self, callback)
274 }
275
276 fn post_run<F>(&mut self, callback: F) -> crate::Result<()>
277 where
278 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
279 {
280 T::post_run(&mut **self, callback)
281 }
282 }
283
284 pub(crate) struct DispatcherInner<S, F> {
285 source: S,
286 callback: F,
287 }
288
289 impl<Data, S, F> EventDispatcher<Data> for RefCell<DispatcherInner<S, F>>
290 where
291 S: EventSource,
292 F: FnMut(S::Event, &mut S::Metadata, &mut Data) -> S::Ret,
293 {
294 fn process_events(
295 &self,
296 readiness: Readiness,
297 token: Token,
298 data: &mut Data,
299 ) -> crate::Result<PostAction> {
300 let mut disp = self.borrow_mut();
301 let DispatcherInner {
302 ref mut source,
303 ref mut callback,
304 } = *disp;
305 source
306 .process_events(readiness, token, |event, meta| callback(event, meta, data))
307 .map_err(|e| crate::Error::OtherError(e.into()))
308 }
309
310 fn register(&self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> {
311 self.borrow_mut().source.register(poll, token_factory)
312 }
313
314 fn reregister(&self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<bool> {
315 if let Ok(mut me) = self.try_borrow_mut() {
316 me.source.reregister(poll, token_factory)?;
317 Ok(true)
318 } else {
319 Ok(false)
320 }
321 }
322
323 fn unregister(&self, poll: &mut Poll) -> crate::Result<bool> {
324 if let Ok(mut me) = self.try_borrow_mut() {
325 me.source.unregister(poll)?;
326 Ok(true)
327 } else {
328 Ok(false)
329 }
330 }
331
332 fn pre_run(&self, data: &mut Data) -> crate::Result<()> {
333 let mut disp = self.borrow_mut();
334 let DispatcherInner {
335 ref mut source,
336 ref mut callback,
337 } = *disp;
338 source.pre_run(|event, meta| callback(event, meta, data))
339 }
340
341 fn post_run(&self, data: &mut Data) -> crate::Result<()> {
342 let mut disp = self.borrow_mut();
343 let DispatcherInner {
344 ref mut source,
345 ref mut callback,
346 } = *disp;
347 source.post_run(|event, meta| callback(event, meta, data))
348 }
349 }
350
351 pub(crate) trait EventDispatcher<Data> {
352 fn process_events(
353 &self,
354 readiness: Readiness,
355 token: Token,
356 data: &mut Data,
357 ) -> crate::Result<PostAction>;
358
359 fn register(&self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()>;
360
361 fn reregister(&self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<bool>;
362
363 fn unregister(&self, poll: &mut Poll) -> crate::Result<bool>;
364
365 fn pre_run(&self, data: &mut Data) -> crate::Result<()>;
366
367 fn post_run(&self, data: &mut Data) -> crate::Result<()>;
368 }
369
370 // An internal trait to erase the `F` type parameter of `DispatcherInner`
371 trait ErasedDispatcher<'a, S, Data> {
372 fn as_source_ref(&self) -> Ref<S>;
373 fn as_source_mut(&self) -> RefMut<S>;
374 fn into_source_inner(self: Rc<Self>) -> S;
375 fn into_event_dispatcher(self: Rc<Self>) -> Rc<dyn EventDispatcher<Data> + 'a>;
376 }
377
378 impl<'a, S, Data, F> ErasedDispatcher<'a, S, Data> for RefCell<DispatcherInner<S, F>>
379 where
380 S: EventSource + 'a,
381 F: FnMut(S::Event, &mut S::Metadata, &mut Data) -> S::Ret + 'a,
382 {
383 fn as_source_ref(&self) -> Ref<S> {
384 Ref::map(self.borrow(), |inner| &inner.source)
385 }
386
387 fn as_source_mut(&self) -> RefMut<S> {
388 RefMut::map(self.borrow_mut(), |inner| &mut inner.source)
389 }
390
391 fn into_source_inner(self: Rc<Self>) -> S {
392 if let Ok(ref_cell) = Rc::try_unwrap(self) {
393 ref_cell.into_inner().source
394 } else {
395 panic!("Dispatcher is still registered");
396 }
397 }
398
399 fn into_event_dispatcher(self: Rc<Self>) -> Rc<dyn EventDispatcher<Data> + 'a>
400 where
401 S: 'a,
402 {
403 self as Rc<dyn EventDispatcher<Data> + 'a>
404 }
405 }
406
407 /// An event source with its callback.
408 ///
409 /// The `Dispatcher` can be registered in an event loop.
410 /// Use the `as_source_{ref,mut}` functions to interact with the event source.
411 /// Use `into_source_inner` to get the event source back.
412 pub struct Dispatcher<'a, S, Data>(Rc<dyn ErasedDispatcher<'a, S, Data> + 'a>);
413
414 impl<'a, S, Data> std::fmt::Debug for Dispatcher<'a, S, Data> {
415 #[cfg_attr(coverage, no_coverage)]
416 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
417 f.write_str("Dispatcher { ... }")
418 }
419 }
420
421 impl<'a, S, Data> Dispatcher<'a, S, Data>
422 where
423 S: EventSource + 'a,
424 {
425 /// Builds a dispatcher.
426 ///
427 /// The resulting `Dispatcher`
428 pub fn new<F>(source: S, callback: F) -> Self
429 where
430 F: FnMut(S::Event, &mut S::Metadata, &mut Data) -> S::Ret + 'a,
431 {
432 Dispatcher(Rc::new(RefCell::new(DispatcherInner { source, callback })))
433 }
434
435 /// Returns an immutable reference to the event source.
436 ///
437 /// # Panics
438 ///
439 /// Has the same semantics as `RefCell::borrow()`.
440 ///
441 /// The dispatcher being mutably borrowed while its events are dispatched,
442 /// this method will panic if invoked from within the associated dispatching closure.
443 pub fn as_source_ref(&self) -> Ref<S> {
444 self.0.as_source_ref()
445 }
446
447 /// Returns a mutable reference to the event source.
448 ///
449 /// # Panics
450 ///
451 /// Has the same semantics as `RefCell::borrow_mut()`.
452 ///
453 /// The dispatcher being mutably borrowed while its events are dispatched,
454 /// this method will panic if invoked from within the associated dispatching closure.
455 pub fn as_source_mut(&self) -> RefMut<S> {
456 self.0.as_source_mut()
457 }
458
459 /// Consumes the Dispatcher and returns the inner event source.
460 ///
461 /// # Panics
462 ///
463 /// Panics if the `Dispatcher` is still registered.
464 pub fn into_source_inner(self) -> S {
465 self.0.into_source_inner()
466 }
467
468 pub(crate) fn clone_as_event_dispatcher(&self) -> Rc<dyn EventDispatcher<Data> + 'a> {
469 Rc::clone(&self.0).into_event_dispatcher()
470 }
471 }
472
473 impl<'a, S, Data> Clone for Dispatcher<'a, S, Data> {
474 fn clone(&self) -> Dispatcher<'a, S, Data> {
475 Dispatcher(Rc::clone(&self.0))
476 }
477 }
478
479 /// An idle callback that was inserted in this loop
480 ///
481 /// This handle allows you to cancel the callback. Dropping
482 /// it will *not* cancel it.
483 pub struct Idle<'i> {
484 pub(crate) callback: Rc<RefCell<dyn CancellableIdle + 'i>>,
485 }
486
487 impl<'i> std::fmt::Debug for Idle<'i> {
488 #[cfg_attr(coverage, no_coverage)]
489 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
490 f.write_str("Idle { ... }")
491 }
492 }
493
494 impl<'i> Idle<'i> {
495 /// Cancel the idle callback if it was not already run
496 pub fn cancel(self) {
497 self.callback.borrow_mut().cancel();
498 }
499 }
500
501 pub(crate) trait CancellableIdle {
502 fn cancel(&mut self);
503 }
504
505 impl<F> CancellableIdle for Option<F> {
506 fn cancel(&mut self) {
507 self.take();
508 }
509 }
510
511 pub(crate) trait IdleDispatcher<Data> {
512 fn dispatch(&mut self, data: &mut Data);
513 }
514
515 impl<Data, F> IdleDispatcher<Data> for Option<F>
516 where
517 F: FnMut(&mut Data),
518 {
519 fn dispatch(&mut self, data: &mut Data) {
520 if let Some(callabck) = self.as_mut() {
521 callabck(data);
522 }
523 }
524 }
525
526 #[cfg(test)]
527 mod tests {
528 use std::time::Duration;
529
530 use crate::{ping::make_ping, EventLoop};
531
532 // Test event source boxing.
533 #[test]
534 fn test_boxed_source() {
535 let mut fired = false;
536
537 let (pinger, source) = make_ping().unwrap();
538 let boxed = Box::new(source);
539
540 let mut event_loop = EventLoop::try_new().unwrap();
541 let handle = event_loop.handle();
542
543 let token = handle
544 .insert_source(boxed, |_, _, fired| *fired = true)
545 .unwrap();
546
547 pinger.ping();
548
549 event_loop
550 .dispatch(Duration::new(0, 0), &mut fired)
551 .unwrap();
552
553 assert!(fired);
554 fired = false;
555
556 handle.update(&token).unwrap();
557
558 pinger.ping();
559
560 event_loop
561 .dispatch(Duration::new(0, 0), &mut fired)
562 .unwrap();
563
564 assert!(fired);
565 fired = false;
566
567 handle.remove(token);
568
569 event_loop
570 .dispatch(Duration::new(0, 0), &mut fired)
571 .unwrap();
572
573 assert!(!fired);
574 }
575
576 // Test event source trait methods via mut ref.
577 #[test]
578 fn test_mut_ref_source() {
579 let mut fired = false;
580
581 let (pinger, mut source) = make_ping().unwrap();
582 let source_ref = &mut source;
583
584 let mut event_loop = EventLoop::try_new().unwrap();
585 let handle = event_loop.handle();
586
587 let token = handle
588 .insert_source(source_ref, |_, _, fired| *fired = true)
589 .unwrap();
590
591 pinger.ping();
592
593 event_loop
594 .dispatch(Duration::new(0, 0), &mut fired)
595 .unwrap();
596
597 assert!(fired);
598 fired = false;
599
600 handle.update(&token).unwrap();
601
602 pinger.ping();
603
604 event_loop
605 .dispatch(Duration::new(0, 0), &mut fired)
606 .unwrap();
607
608 assert!(fired);
609 fired = false;
610
611 handle.remove(token);
612
613 event_loop
614 .dispatch(Duration::new(0, 0), &mut fired)
615 .unwrap();
616
617 assert!(!fired);
618 }
619
620 // Test PostAction combinations.
621 #[test]
622 fn post_action_combine() {
623 use super::PostAction::*;
624 assert_eq!(Continue | Continue, Continue);
625 assert_eq!(Continue | Reregister, Reregister);
626 assert_eq!(Continue | Disable, Reregister);
627 assert_eq!(Continue | Remove, Reregister);
628
629 assert_eq!(Reregister | Continue, Reregister);
630 assert_eq!(Reregister | Reregister, Reregister);
631 assert_eq!(Reregister | Disable, Reregister);
632 assert_eq!(Reregister | Remove, Reregister);
633
634 assert_eq!(Disable | Continue, Reregister);
635 assert_eq!(Disable | Reregister, Reregister);
636 assert_eq!(Disable | Disable, Disable);
637 assert_eq!(Disable | Remove, Reregister);
638
639 assert_eq!(Remove | Continue, Reregister);
640 assert_eq!(Remove | Reregister, Reregister);
641 assert_eq!(Remove | Disable, Reregister);
642 assert_eq!(Remove | Remove, Remove);
643 }
644
645 // Test PostAction self-assignment.
646 #[test]
647 fn post_action_combine_assign() {
648 use super::PostAction::*;
649
650 let mut action = Continue;
651 action |= Continue;
652 assert_eq!(action, Continue);
653
654 let mut action = Continue;
655 action |= Reregister;
656 assert_eq!(action, Reregister);
657
658 let mut action = Continue;
659 action |= Disable;
660 assert_eq!(action, Reregister);
661
662 let mut action = Continue;
663 action |= Remove;
664 assert_eq!(action, Reregister);
665
666 let mut action = Reregister;
667 action |= Continue;
668 assert_eq!(action, Reregister);
669
670 let mut action = Reregister;
671 action |= Reregister;
672 assert_eq!(action, Reregister);
673
674 let mut action = Reregister;
675 action |= Disable;
676 assert_eq!(action, Reregister);
677
678 let mut action = Reregister;
679 action |= Remove;
680 assert_eq!(action, Reregister);
681
682 let mut action = Disable;
683 action |= Continue;
684 assert_eq!(action, Reregister);
685
686 let mut action = Disable;
687 action |= Reregister;
688 assert_eq!(action, Reregister);
689
690 let mut action = Disable;
691 action |= Disable;
692 assert_eq!(action, Disable);
693
694 let mut action = Disable;
695 action |= Remove;
696 assert_eq!(action, Reregister);
697
698 let mut action = Remove;
699 action |= Continue;
700 assert_eq!(action, Reregister);
701
702 let mut action = Remove;
703 action |= Reregister;
704 assert_eq!(action, Reregister);
705
706 let mut action = Remove;
707 action |= Disable;
708 assert_eq!(action, Reregister);
709
710 let mut action = Remove;
711 action |= Remove;
712 assert_eq!(action, Remove);
713 }
714 }