Debian Codegraph @

debian/rust-vendor/crossterm/src/event/stream.rs

raw
1 use std::{
2 io,
3 pin::Pin,
4 sync::{
5 atomic::{AtomicBool, Ordering},
6 mpsc::{self, SyncSender},
7 Arc,
8 },
9 task::{Context, Poll},
10 thread,
11 time::Duration,
12 };
13
14 use futures_core::stream::Stream;
15
16 use crate::event::{
17 filter::EventFilter, lock_internal_event_reader, poll_internal, read_internal, sys::Waker,
18 Event, InternalEvent,
19 };
20
21 /// A stream of `Result<Event>`.
22 ///
23 /// **This type is not available by default. You have to use the `event-stream` feature flag
24 /// to make it available.**
25 ///
26 /// It implements the [Stream](futures_core::stream::Stream)
27 /// trait and allows you to receive [`Event`]s with [`async-std`](https://crates.io/crates/async-std)
28 /// or [`tokio`](https://crates.io/crates/tokio) crates.
29 ///
30 /// Check the [examples](https://github.com/crossterm-rs/crossterm/tree/master/examples) folder to see how to use
31 /// it (`event-stream-*`).
32 #[derive(Debug)]
33 pub struct EventStream {
34 poll_internal_waker: Waker,
35 stream_wake_task_executed: Arc<AtomicBool>,
36 stream_wake_task_should_shutdown: Arc<AtomicBool>,
37 task_sender: SyncSender<Task>,
38 }
39
40 impl Default for EventStream {
41 fn default() -> Self {
42 let (task_sender, receiver) = mpsc::sync_channel::<Task>(1);
43
44 thread::spawn(move || {
45 while let Ok(task) = receiver.recv() {
46 loop {
47 if let Ok(true) = poll_internal(None, &EventFilter) {
48 break;
49 }
50
51 if task.stream_wake_task_should_shutdown.load(Ordering::SeqCst) {
52 break;
53 }
54 }
55 task.stream_wake_task_executed
56 .store(false, Ordering::SeqCst);
57 task.stream_waker.wake();
58 }
59 });
60
61 EventStream {
62 poll_internal_waker: lock_internal_event_reader().waker(),
63 stream_wake_task_executed: Arc::new(AtomicBool::new(false)),
64 stream_wake_task_should_shutdown: Arc::new(AtomicBool::new(false)),
65 task_sender,
66 }
67 }
68 }
69
70 impl EventStream {
71 /// Constructs a new instance of `EventStream`.
72 pub fn new() -> EventStream {
73 EventStream::default()
74 }
75 }
76
77 struct Task {
78 stream_waker: std::task::Waker,
79 stream_wake_task_executed: Arc<AtomicBool>,
80 stream_wake_task_should_shutdown: Arc<AtomicBool>,
81 }
82
83 // Note to future me
84 //
85 // We need two wakers in order to implement EventStream correctly.
86 //
87 // 1. futures::Stream waker
88 //
89 // Stream::poll_next can return Poll::Pending which means that there's no
90 // event available. We are going to spawn a thread with the
91 // poll_internal(None, &EventFilter) call. This call blocks until an
92 // event is available and then we have to wake up the executor with notification
93 // that the task can be resumed.
94 //
95 // 2. poll_internal waker
96 //
97 // There's no event available, Poll::Pending was returned, stream waker thread
98 // is up and sitting in the poll_internal. User wants to drop the EventStream.
99 // We have to wake up the poll_internal (force it to return Ok(false)) and quit
100 // the thread before we drop.
101 impl Stream for EventStream {
102 type Item = io::Result<Event>;
103
104 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
105 let result = match poll_internal(Some(Duration::from_secs(0)), &EventFilter) {
106 Ok(true) => match read_internal(&EventFilter) {
107 Ok(InternalEvent::Event(event)) => Poll::Ready(Some(Ok(event))),
108 Err(e) => Poll::Ready(Some(Err(e))),
109 #[cfg(unix)]
110 _ => unreachable!(),
111 },
112 Ok(false) => {
113 if !self
114 .stream_wake_task_executed
115 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
116 // https://github.com/rust-lang/rust/issues/80486#issuecomment-752244166
117 .unwrap_or_else(|x| x)
118 {
119 let stream_waker = cx.waker().clone();
120 let stream_wake_task_executed = self.stream_wake_task_executed.clone();
121 let stream_wake_task_should_shutdown =
122 self.stream_wake_task_should_shutdown.clone();
123
124 stream_wake_task_should_shutdown.store(false, Ordering::SeqCst);
125
126 let _ = self.task_sender.send(Task {
127 stream_waker,
128 stream_wake_task_executed,
129 stream_wake_task_should_shutdown,
130 });
131 }
132 Poll::Pending
133 }
134 Err(e) => Poll::Ready(Some(Err(e))),
135 };
136 result
137 }
138 }
139
140 impl Drop for EventStream {
141 fn drop(&mut self) {
142 self.stream_wake_task_should_shutdown
143 .store(true, Ordering::SeqCst);
144 let _ = self.poll_internal_waker.wake();
145 }
146 }