| 1 | //! Thread-safe terminal event reader. |
| 2 | //! |
| 3 | //! This module provides an `Arc<Mutex<T>>` wrapper around the platform event source. That lets a |
| 4 | //! reader live on a terminal handle and also be shared with the optional async stream, rather than |
| 5 | //! being stored globally. |
| 6 | //! |
| 7 | //! # Implementation Notes |
| 8 | //! |
| 9 | //! This is adapted from [crossterm's event reader]. The shared reader is mostly an |
| 10 | //! `Arc<Mutex<T>>` wrapper around the same shape as crossterm's internal event reader. This lets |
| 11 | //! it live on a [`Terminal`] and on an `EventStream` instead of being stored globally. Termina uses |
| 12 | //! `Fn(&Event) -> bool` filters instead of a dedicated filter trait so callers can pass ordinary |
| 13 | //! closures. |
| 14 | //! |
| 15 | //! [crossterm's event reader]: https://docs.rs/crossterm/latest/crossterm/event/index.html |
| 16 | //! [`Terminal`]: crate::Terminal |
| 17 | |
| 18 | use std::{collections::VecDeque, io, sync::Arc, time::Duration}; |
| 19 | |
| 20 | use parking_lot::Mutex; |
| 21 | |
| 22 | use super::{ |
| 23 | source::{EventSource as _, PlatformEventSource, PlatformWaker, PollTimeout}, |
| 24 | Event, |
| 25 | }; |
| 26 | |
| 27 | /// A reader of events from the terminal's input handle. |
| 28 | /// |
| 29 | /// Note that this type wraps an `Arc` and is cheap to clone. If the `event-stream` feature is |
| 30 | /// enabled then this value should be passed to `EventStream::new`. |
| 31 | /// |
| 32 | /// [`Self::read`] and [`Self::poll`] both take filters. Events rejected by a filter remain buffered |
| 33 | /// so a caller can wait for a key press without discarding protocol responses, mouse events, or |
| 34 | /// other input that another part of the application may read later. Filtering preserves rejected |
| 35 | /// events for later reads, but callers should not rely on rejected events being re-buffered in exact |
| 36 | /// stream order across multiple filtered reads. |
| 37 | /// |
| 38 | /// # Examples |
| 39 | /// |
| 40 | /// Read every event and branch on the event kind: |
| 41 | /// |
| 42 | /// ```no_run |
| 43 | /// use std::io; |
| 44 | /// |
| 45 | /// use termina::{ |
| 46 | /// event::{Event, KeyCode, KeyEventKind}, |
| 47 | /// PlatformTerminal, Terminal, |
| 48 | /// }; |
| 49 | /// |
| 50 | /// fn main() -> io::Result<()> { |
| 51 | /// let reader = PlatformTerminal::new()?.event_reader(); |
| 52 | /// loop { |
| 53 | /// let event = reader.read(|_| true)?; |
| 54 | /// match event { |
| 55 | /// Event::Key(key) |
| 56 | /// if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') => |
| 57 | /// { |
| 58 | /// break |
| 59 | /// } |
| 60 | /// Event::Mouse(mouse) => eprintln!("mouse at {},{}", mouse.column, mouse.row), |
| 61 | /// Event::Csi(csi) => eprintln!("CSI response: {csi:?}"), |
| 62 | /// _ => {} |
| 63 | /// } |
| 64 | /// } |
| 65 | /// Ok(()) |
| 66 | /// } |
| 67 | /// ``` |
| 68 | /// |
| 69 | /// Use a filter when a call should wait for a specific class of event: |
| 70 | /// |
| 71 | /// ```no_run |
| 72 | /// use std::io; |
| 73 | /// |
| 74 | /// use termina::{ |
| 75 | /// event::{Event, KeyEventKind}, |
| 76 | /// PlatformTerminal, Terminal, |
| 77 | /// }; |
| 78 | /// |
| 79 | /// fn main() -> io::Result<()> { |
| 80 | /// let reader = PlatformTerminal::new()?.event_reader(); |
| 81 | /// let event = reader.read(|event| { |
| 82 | /// matches!(event, Event::Key(key) if key.kind == KeyEventKind::Press) |
| 83 | /// })?; |
| 84 | /// println!("received {event:?}"); |
| 85 | /// Ok(()) |
| 86 | /// } |
| 87 | /// ``` |
| 88 | #[derive(Debug, Clone)] |
| 89 | pub struct EventReader { |
| 90 | shared: Arc<Mutex<Shared>>, |
| 91 | } |
| 92 | |
| 93 | impl EventReader { |
| 94 | pub(crate) fn new(source: PlatformEventSource) -> Self { |
| 95 | let shared = Shared { |
| 96 | events: VecDeque::with_capacity(32), |
| 97 | source, |
| 98 | skipped_events: Vec::with_capacity(32), |
| 99 | }; |
| 100 | Self { |
| 101 | shared: Arc::new(Mutex::new(shared)), |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | /// Returns a platform-specific waker that can unblock [`poll`](Self::poll) calls. |
| 106 | pub fn waker(&self) -> PlatformWaker { |
| 107 | let reader = self.shared.lock(); |
| 108 | reader.source.waker() |
| 109 | } |
| 110 | |
| 111 | /// Polls for availability of an event matching `filter`. |
| 112 | /// |
| 113 | /// When `timeout` is `None`, this call blocks indefinitely. Events rejected by `filter` are |
| 114 | /// retained so a later call can still return them. Use the same filter with [`Self::read`] if |
| 115 | /// the follow-up read should consume the event that made this method return `true`. |
| 116 | pub fn poll<F>(&self, timeout: Option<Duration>, filter: F) -> io::Result<bool> |
| 117 | where |
| 118 | F: FnMut(&Event) -> bool, |
| 119 | { |
| 120 | let (mut reader, timeout) = if let Some(timeout) = timeout { |
| 121 | let poll_timeout = PollTimeout::new(Some(timeout)); |
| 122 | if let Some(reader) = self.shared.try_lock_for(timeout) { |
| 123 | (reader, poll_timeout.leftover()) |
| 124 | } else { |
| 125 | return Ok(false); |
| 126 | } |
| 127 | } else { |
| 128 | (self.shared.lock(), None) |
| 129 | }; |
| 130 | reader.poll(timeout, filter) |
| 131 | } |
| 132 | |
| 133 | /// Blocks until an event matching `filter` is available. |
| 134 | /// |
| 135 | /// Events rejected by `filter` are retained for later reads. For keyboard shortcuts, filter on |
| 136 | /// `Event::Key(key) if key.kind == KeyEventKind::Press` unless the application intentionally |
| 137 | /// handles release or repeat events. |
| 138 | pub fn read<F>(&self, filter: F) -> io::Result<Event> |
| 139 | where |
| 140 | F: FnMut(&Event) -> bool, |
| 141 | { |
| 142 | let mut reader = self.shared.lock(); |
| 143 | reader.read(filter) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | #[derive(Debug)] |
| 148 | struct Shared { |
| 149 | events: VecDeque<Event>, |
| 150 | source: PlatformEventSource, |
| 151 | skipped_events: Vec<Event>, |
| 152 | } |
| 153 | |
| 154 | impl Shared { |
| 155 | fn poll<F>(&mut self, timeout: Option<Duration>, mut filter: F) -> io::Result<bool> |
| 156 | where |
| 157 | F: FnMut(&Event) -> bool, |
| 158 | { |
| 159 | if self.events.iter().any(&mut (filter)) { |
| 160 | return Ok(true); |
| 161 | } |
| 162 | |
| 163 | let timeout = PollTimeout::new(timeout); |
| 164 | |
| 165 | loop { |
| 166 | let maybe_event = match self.source.try_read(timeout.leftover()) { |
| 167 | Ok(None) => None, |
| 168 | Ok(Some(event)) => { |
| 169 | if (filter)(&event) { |
| 170 | Some(event) |
| 171 | } else { |
| 172 | self.skipped_events.push(event); |
| 173 | None |
| 174 | } |
| 175 | } |
| 176 | Err(err) if err.kind() == io::ErrorKind::Interrupted => return Ok(false), |
| 177 | Err(err) => return Err(err), |
| 178 | }; |
| 179 | |
| 180 | if timeout.elapsed() || maybe_event.is_some() { |
| 181 | self.events.extend(self.skipped_events.drain(..)); |
| 182 | |
| 183 | if let Some(event) = maybe_event { |
| 184 | self.events.push_front(event); |
| 185 | return Ok(true); |
| 186 | } |
| 187 | |
| 188 | return Ok(false); |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | fn read<F>(&mut self, mut filter: F) -> io::Result<Event> |
| 194 | where |
| 195 | F: FnMut(&Event) -> bool, |
| 196 | { |
| 197 | let mut skipped_events = VecDeque::new(); |
| 198 | |
| 199 | loop { |
| 200 | while let Some(event) = self.events.pop_front() { |
| 201 | if (filter)(&event) { |
| 202 | self.events.extend(skipped_events.drain(..)); |
| 203 | return Ok(event); |
| 204 | } else { |
| 205 | skipped_events.push_back(event); |
| 206 | } |
| 207 | } |
| 208 | let _ = self.poll(None, &mut filter)?; |
| 209 | } |
| 210 | } |
| 211 | } |