| 1 | //! Terminal input ingestion and fairness controls for the TUI event loop. |
| 2 | |
| 3 | use std::cell::{Cell, RefCell}; |
| 4 | use std::io; |
| 5 | use std::sync::{ |
| 6 | Arc, Mutex, |
| 7 | atomic::{AtomicBool, Ordering}, |
| 8 | }; |
| 9 | use std::thread::{self, JoinHandle}; |
| 10 | use std::time::{Duration, Instant}; |
| 11 | |
| 12 | use crossterm::event::{self, Event}; |
| 13 | |
| 14 | const TERMINAL_INPUT_POLL_INTERVAL: Duration = Duration::from_millis(50); |
| 15 | const TERMINAL_INPUT_IDLE_POLL_INTERVAL: Duration = Duration::from_millis(200); |
| 16 | const TERMINAL_INPUT_IDLE_AFTER: Duration = Duration::from_secs(5); |
| 17 | const TERMINAL_INPUT_HEARTBEAT_INTERVAL: Duration = Duration::from_millis(500); |
| 18 | pub(super) const TERMINAL_INPUT_STALL_TIMEOUT: Duration = Duration::from_secs(5); |
| 19 | pub(super) const TERMINAL_INPUT_RECOVERY_COOLDOWN: Duration = Duration::from_secs(10); |
| 20 | const TERMINAL_INPUT_CHILD_PAUSE_TIMEOUT: Duration = Duration::from_millis(500); |
| 21 | const TERMINAL_INPUT_CHILD_PAUSE_POLL_INTERVAL: Duration = Duration::from_millis(5); |
| 22 | const MAX_RETIRED_INPUT_READERS: usize = 4; |
| 23 | const RETIRED_INPUT_POLL_SLICE: Duration = Duration::from_millis(25); |
| 24 | const MAX_CHILD_TERMINAL_WINDOWS: usize = 8; |
| 25 | /// Upper bound on engine events processed before yielding to terminal input. |
| 26 | pub(super) const MAX_ENGINE_EVENTS_PER_DRAIN: usize = 16; |
| 27 | /// Wall-clock budget for one engine drain batch (#1830 / #2317 input fairness). |
| 28 | pub(super) const ENGINE_DRAIN_TIME_BUDGET: Duration = Duration::from_millis(8); |
| 29 | |
| 30 | pub(super) enum TerminalInputMessage { |
| 31 | Event(ObservedTerminalEvent), |
| 32 | Heartbeat, |
| 33 | Error(io::Error), |
| 34 | } |
| 35 | |
| 36 | /// A terminal event paired with the instant the input thread's `event::read` |
| 37 | /// returned. That is read completion, not the instant the key arrived and not |
| 38 | /// what the user meant it for: crossterm hands back a buffered key only on the |
| 39 | /// next read. |
| 40 | /// |
| 41 | /// The event loop can lag behind this thread under load. Keeping receipt time |
| 42 | /// prevents that backlog from collapsing a deliberate pause between a raw |
| 43 | /// paste and Enter into a paste-speed sequence. |
| 44 | pub(crate) struct ObservedTerminalEvent { |
| 45 | pub(crate) event: Event, |
| 46 | pub(crate) observed_at: Instant, |
| 47 | } |
| 48 | |
| 49 | impl ObservedTerminalEvent { |
| 50 | pub(crate) fn new(event: Event, observed_at: Instant) -> Self { |
| 51 | Self { event, observed_at } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /// Process-wide handle on the one terminal input pump's pause flags. |
| 56 | /// |
| 57 | /// There is one stdin per process and exactly one [`TerminalInputPump`] |
| 58 | /// reading it, so this is a singleton by construction rather than by |
| 59 | /// convention. It exists so that *handing the terminal to a child* can be one |
| 60 | /// operation instead of a rule every call site has to remember (#6165): |
| 61 | /// suspending raw mode and the alternate screen does not stop the pump |
| 62 | /// thread, which keeps calling `event::read()` on the same tty and splits the |
| 63 | /// user's keystrokes between the child and the composer. |
| 64 | /// |
| 65 | /// Known limitation: the gate only stops the pump reading. It cannot drain |
| 66 | /// input the pump already buffered, and it cannot refuse the handoff when a |
| 67 | /// cancellation key is pending — both need the receiver and the event loop's |
| 68 | /// pending queue, so they stay with [`super::prepare_terminal_input_handoff`] |
| 69 | /// at the call sites that have them. |
| 70 | static CHILD_TERMINAL_GATE: Mutex<Option<ChildTerminalGate>> = Mutex::new(None); |
| 71 | |
| 72 | #[derive(Clone, Copy)] |
| 73 | pub(super) struct ChildTerminalWindow(u64); |
| 74 | |
| 75 | struct ChildTerminalWindowRecord { |
| 76 | id: u64, |
| 77 | start: Instant, |
| 78 | end: Option<Instant>, |
| 79 | } |
| 80 | |
| 81 | struct ChildTerminalWindows { |
| 82 | next_id: u64, |
| 83 | windows: Vec<ChildTerminalWindowRecord>, |
| 84 | } |
| 85 | |
| 86 | static CHILD_TERMINAL_WINDOWS: Mutex<ChildTerminalWindows> = Mutex::new(ChildTerminalWindows { |
| 87 | next_id: 0, |
| 88 | windows: Vec::new(), |
| 89 | }); |
| 90 | |
| 91 | pub(super) fn child_terminal_window_begin() -> Option<ChildTerminalWindow> { |
| 92 | let mut registry = CHILD_TERMINAL_WINDOWS.lock().ok()?; |
| 93 | let id = registry.next_id; |
| 94 | registry.next_id += 1; |
| 95 | registry.windows.push(ChildTerminalWindowRecord { |
| 96 | id, |
| 97 | start: Instant::now(), |
| 98 | end: None, |
| 99 | }); |
| 100 | Some(ChildTerminalWindow(id)) |
| 101 | } |
| 102 | |
| 103 | pub(super) fn child_terminal_window_end(window: Option<ChildTerminalWindow>) { |
| 104 | let Some(ChildTerminalWindow(id)) = window else { |
| 105 | return; |
| 106 | }; |
| 107 | if let Ok(mut registry) = CHILD_TERMINAL_WINDOWS.lock() |
| 108 | && let Some(record) = registry |
| 109 | .windows |
| 110 | .iter_mut() |
| 111 | .find(|record| record.id == id && record.end.is_none()) |
| 112 | { |
| 113 | record.end = Some(Instant::now()); |
| 114 | let mut completed = registry |
| 115 | .windows |
| 116 | .iter() |
| 117 | .filter(|window| window.end.is_some()) |
| 118 | .count(); |
| 119 | registry.windows.retain(|window| { |
| 120 | if completed > MAX_CHILD_TERMINAL_WINDOWS && window.end.is_some() { |
| 121 | completed -= 1; |
| 122 | false |
| 123 | } else { |
| 124 | true |
| 125 | } |
| 126 | }); |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | fn child_owned_terminal_at(observed_at: Instant) -> bool { |
| 131 | CHILD_TERMINAL_WINDOWS.lock().is_ok_and(|registry| { |
| 132 | registry.windows.iter().any(|record| { |
| 133 | observed_at >= record.start && record.end.is_none_or(|end| observed_at <= end) |
| 134 | }) |
| 135 | }) |
| 136 | } |
| 137 | |
| 138 | #[derive(Clone)] |
| 139 | struct ChildTerminalGate { |
| 140 | paused: Arc<AtomicBool>, |
| 141 | paused_ack: Arc<AtomicBool>, |
| 142 | } |
| 143 | |
| 144 | /// Publish this pump as the process's terminal input owner. |
| 145 | pub(super) fn publish_child_terminal_gate(paused: &Arc<AtomicBool>, paused_ack: &Arc<AtomicBool>) { |
| 146 | if let Ok(mut gate) = CHILD_TERMINAL_GATE.lock() { |
| 147 | *gate = Some(ChildTerminalGate { |
| 148 | paused: Arc::clone(paused), |
| 149 | paused_ack: Arc::clone(paused_ack), |
| 150 | }); |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | /// Retract `paused`'s pump, but only if it is still the published one — a |
| 155 | /// detached wedged thread must not unpublish the replacement that took over. |
| 156 | fn retract_child_terminal_gate(paused: &Arc<AtomicBool>) { |
| 157 | if let Ok(mut gate) = CHILD_TERMINAL_GATE.lock() |
| 158 | && gate |
| 159 | .as_ref() |
| 160 | .is_some_and(|current| Arc::ptr_eq(¤t.paused, paused)) |
| 161 | { |
| 162 | *gate = None; |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /// The terminal input pump, paused for as long as this guard is alive. |
| 167 | /// |
| 168 | /// Held by [`crate::tui::external_editor::with_suspended_tui`] across the |
| 169 | /// whole child handoff, so the pump resumes on every path out — including a |
| 170 | /// child that failed to spawn or a panic unwinding through it. |
| 171 | pub(crate) struct ChildTerminalInputPause { |
| 172 | gate: Option<ChildTerminalGate>, |
| 173 | window: Option<ChildTerminalWindow>, |
| 174 | } |
| 175 | |
| 176 | /// Stop the process's terminal input pump before a child takes the tty. |
| 177 | /// |
| 178 | /// Fails closed: if the pump does not acknowledge the pause, the caller must |
| 179 | /// not run the child, because that is exactly the keystroke-splitting state |
| 180 | /// this guards against. A process with no pump published (tests, non-TUI |
| 181 | /// callers) has nothing to pause and succeeds with an inert guard, matching |
| 182 | /// [`TerminalInputPump::pause_for_child_terminal`]'s `handle.is_none()` case. |
| 183 | pub(crate) fn pause_terminal_input_for_child() -> io::Result<ChildTerminalInputPause> { |
| 184 | let Some(gate) = CHILD_TERMINAL_GATE |
| 185 | .lock() |
| 186 | .ok() |
| 187 | .and_then(|gate| gate.clone()) |
| 188 | else { |
| 189 | return Ok(ChildTerminalInputPause { |
| 190 | gate: None, |
| 191 | window: None, |
| 192 | }); |
| 193 | }; |
| 194 | gate.paused.store(true, Ordering::Release); |
| 195 | let deadline = Instant::now() + TERMINAL_INPUT_CHILD_PAUSE_TIMEOUT; |
| 196 | while !gate.paused_ack.load(Ordering::Acquire) { |
| 197 | if Instant::now() >= deadline { |
| 198 | gate.paused_ack.store(false, Ordering::Release); |
| 199 | gate.paused.store(false, Ordering::Release); |
| 200 | return Err(io::Error::new( |
| 201 | io::ErrorKind::TimedOut, |
| 202 | "terminal input pump did not pause before child terminal handoff", |
| 203 | )); |
| 204 | } |
| 205 | // Blocking-call convention (#6149): a bounded retry, capped by |
| 206 | // `TERMINAL_INPUT_CHILD_PAUSE_TIMEOUT`, in a synchronous API whose |
| 207 | // caller is about to block this very thread on a foreground editor |
| 208 | // for as long as the user keeps it open. `tokio::time` is not |
| 209 | // reachable from here and would not change what the thread does. |
| 210 | thread::sleep(TERMINAL_INPUT_CHILD_PAUSE_POLL_INTERVAL); |
| 211 | } |
| 212 | let window = child_terminal_window_begin(); |
| 213 | Ok(ChildTerminalInputPause { |
| 214 | gate: Some(gate), |
| 215 | window, |
| 216 | }) |
| 217 | } |
| 218 | |
| 219 | impl Drop for ChildTerminalInputPause { |
| 220 | fn drop(&mut self) { |
| 221 | child_terminal_window_end(self.window.take()); |
| 222 | if let Some(gate) = self.gate.take() { |
| 223 | gate.paused_ack.store(false, Ordering::Release); |
| 224 | gate.paused.store(false, Ordering::Release); |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | pub(crate) struct TerminalInputPump { |
| 230 | pub(super) rx: std::sync::mpsc::Receiver<TerminalInputMessage>, |
| 231 | pub(super) retired_rx: RefCell<RetiredInputReaders>, |
| 232 | pub(super) child_windows: RefCell<Vec<ChildTerminalWindow>>, |
| 233 | pub(super) stop: Arc<AtomicBool>, |
| 234 | pub(super) paused: Arc<AtomicBool>, |
| 235 | pub(super) paused_ack: Arc<AtomicBool>, |
| 236 | pub(super) handle: Option<JoinHandle<()>>, |
| 237 | pub(super) last_alive_at: Cell<Instant>, |
| 238 | } |
| 239 | |
| 240 | #[derive(Default)] |
| 241 | pub(super) struct RetiredInputReaders { |
| 242 | receivers: Vec<std::sync::mpsc::Receiver<TerminalInputMessage>>, |
| 243 | stash: Option<ObservedTerminalEvent>, |
| 244 | } |
| 245 | |
| 246 | pub(super) struct TerminalInputPumpParts { |
| 247 | pub(super) rx: std::sync::mpsc::Receiver<TerminalInputMessage>, |
| 248 | pub(super) stop: Arc<AtomicBool>, |
| 249 | pub(super) paused: Arc<AtomicBool>, |
| 250 | pub(super) paused_ack: Arc<AtomicBool>, |
| 251 | pub(super) handle: JoinHandle<()>, |
| 252 | } |
| 253 | |
| 254 | impl TerminalInputPump { |
| 255 | pub(super) fn spawn() -> io::Result<Self> { |
| 256 | let parts = Self::spawn_parts()?; |
| 257 | publish_child_terminal_gate(&parts.paused, &parts.paused_ack); |
| 258 | Ok(Self { |
| 259 | rx: parts.rx, |
| 260 | retired_rx: RefCell::default(), |
| 261 | child_windows: RefCell::default(), |
| 262 | stop: parts.stop, |
| 263 | paused: parts.paused, |
| 264 | paused_ack: parts.paused_ack, |
| 265 | handle: Some(parts.handle), |
| 266 | last_alive_at: Cell::new(Instant::now()), |
| 267 | }) |
| 268 | } |
| 269 | |
| 270 | fn spawn_parts() -> io::Result<TerminalInputPumpParts> { |
| 271 | let (tx, rx) = std::sync::mpsc::channel(); |
| 272 | let stop = Arc::new(AtomicBool::new(false)); |
| 273 | let paused = Arc::new(AtomicBool::new(false)); |
| 274 | let paused_ack = Arc::new(AtomicBool::new(false)); |
| 275 | let thread_stop = Arc::clone(&stop); |
| 276 | let thread_paused = Arc::clone(&paused); |
| 277 | let thread_paused_ack = Arc::clone(&paused_ack); |
| 278 | let handle = thread::Builder::new() |
| 279 | .name("codewhale-terminal-input".to_string()) |
| 280 | .spawn(move || { |
| 281 | let mut last_heartbeat = Instant::now(); |
| 282 | let mut last_event = last_heartbeat; |
| 283 | while !thread_stop.load(Ordering::Acquire) { |
| 284 | if thread_paused.load(Ordering::Acquire) { |
| 285 | thread_paused_ack.store(true, Ordering::Release); |
| 286 | thread::sleep(TERMINAL_INPUT_CHILD_PAUSE_POLL_INTERVAL); |
| 287 | continue; |
| 288 | } |
| 289 | thread_paused_ack.store(false, Ordering::Release); |
| 290 | let poll_interval = if last_event.elapsed() < TERMINAL_INPUT_IDLE_AFTER { |
| 291 | TERMINAL_INPUT_POLL_INTERVAL |
| 292 | } else { |
| 293 | TERMINAL_INPUT_IDLE_POLL_INTERVAL |
| 294 | }; |
| 295 | match event::poll(poll_interval) { |
| 296 | Ok(true) if thread_stop.load(Ordering::Acquire) => break, |
| 297 | Ok(true) => match event::read() { |
| 298 | Ok(event) => { |
| 299 | last_heartbeat = Instant::now(); |
| 300 | last_event = last_heartbeat; |
| 301 | let observed = ObservedTerminalEvent::new(event, last_heartbeat); |
| 302 | if tx.send(TerminalInputMessage::Event(observed)).is_err() { |
| 303 | break; |
| 304 | } |
| 305 | } |
| 306 | Err(err) => { |
| 307 | let _ = tx.send(TerminalInputMessage::Error(err)); |
| 308 | break; |
| 309 | } |
| 310 | }, |
| 311 | Ok(false) => { |
| 312 | let now = Instant::now(); |
| 313 | if now.duration_since(last_heartbeat) |
| 314 | >= TERMINAL_INPUT_HEARTBEAT_INTERVAL |
| 315 | { |
| 316 | last_heartbeat = now; |
| 317 | if tx.send(TerminalInputMessage::Heartbeat).is_err() { |
| 318 | break; |
| 319 | } |
| 320 | } |
| 321 | } |
| 322 | Err(err) => { |
| 323 | let _ = tx.send(TerminalInputMessage::Error(err)); |
| 324 | break; |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | })?; |
| 329 | Ok(TerminalInputPumpParts { |
| 330 | rx, |
| 331 | stop, |
| 332 | paused, |
| 333 | paused_ack, |
| 334 | handle, |
| 335 | }) |
| 336 | } |
| 337 | |
| 338 | fn has_retired_readers(&self) -> bool { |
| 339 | !self.retired_rx.borrow().receivers.is_empty() |
| 340 | } |
| 341 | |
| 342 | fn take_retired_event(&self) -> Option<ObservedTerminalEvent> { |
| 343 | let mut retired = self.retired_rx.borrow_mut(); |
| 344 | let mut found = None; |
| 345 | retired.receivers.retain(|receiver| { |
| 346 | if found.is_some() { |
| 347 | return true; |
| 348 | } |
| 349 | loop { |
| 350 | match receiver.try_recv() { |
| 351 | Ok(TerminalInputMessage::Event(event)) => { |
| 352 | if child_owned_terminal_at(event.observed_at) { |
| 353 | continue; |
| 354 | } |
| 355 | found = Some(event); |
| 356 | return true; |
| 357 | } |
| 358 | Ok(TerminalInputMessage::Heartbeat | TerminalInputMessage::Error(_)) => {} |
| 359 | Err(std::sync::mpsc::TryRecvError::Empty) => return true, |
| 360 | Err(std::sync::mpsc::TryRecvError::Disconnected) => return false, |
| 361 | } |
| 362 | } |
| 363 | }); |
| 364 | found |
| 365 | } |
| 366 | |
| 367 | fn take_ready_event(&self) -> Option<ObservedTerminalEvent> { |
| 368 | self.take_retired_event() |
| 369 | .or_else(|| self.retired_rx.borrow_mut().stash.take()) |
| 370 | } |
| 371 | |
| 372 | fn deliver_fresh(&self, event: ObservedTerminalEvent) -> ObservedTerminalEvent { |
| 373 | match self.take_retired_event() { |
| 374 | Some(retired) => { |
| 375 | self.retired_rx.borrow_mut().stash = Some(event); |
| 376 | retired |
| 377 | } |
| 378 | None => event, |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | pub(super) fn recv_timeout( |
| 383 | &self, |
| 384 | timeout: Duration, |
| 385 | ) -> io::Result<Option<ObservedTerminalEvent>> { |
| 386 | let deadline = Instant::now() + timeout; |
| 387 | loop { |
| 388 | if let Some(event) = self.take_ready_event() { |
| 389 | self.mark_alive(); |
| 390 | return Ok(Some(event)); |
| 391 | } |
| 392 | let remaining = deadline.saturating_duration_since(Instant::now()); |
| 393 | let wait = if self.has_retired_readers() { |
| 394 | remaining.min(RETIRED_INPUT_POLL_SLICE) |
| 395 | } else { |
| 396 | remaining |
| 397 | }; |
| 398 | match self.rx.recv_timeout(wait) { |
| 399 | Ok(TerminalInputMessage::Event(event)) => { |
| 400 | self.mark_alive(); |
| 401 | return Ok(Some(self.deliver_fresh(event))); |
| 402 | } |
| 403 | Ok(TerminalInputMessage::Heartbeat) => { |
| 404 | self.mark_alive(); |
| 405 | if remaining.is_zero() { |
| 406 | return Ok(self.take_ready_event()); |
| 407 | } |
| 408 | } |
| 409 | Ok(TerminalInputMessage::Error(err)) => { |
| 410 | self.mark_alive(); |
| 411 | return Err(err); |
| 412 | } |
| 413 | Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { |
| 414 | if Instant::now() >= deadline { |
| 415 | return Ok(self.take_ready_event()); |
| 416 | } |
| 417 | } |
| 418 | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { |
| 419 | return Err(io::Error::new( |
| 420 | io::ErrorKind::BrokenPipe, |
| 421 | "terminal input pump disconnected", |
| 422 | )); |
| 423 | } |
| 424 | } |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | pub(super) fn try_recv(&self) -> io::Result<Option<ObservedTerminalEvent>> { |
| 429 | loop { |
| 430 | if let Some(event) = self.take_ready_event() { |
| 431 | self.mark_alive(); |
| 432 | return Ok(Some(event)); |
| 433 | } |
| 434 | match self.rx.try_recv() { |
| 435 | Ok(TerminalInputMessage::Event(event)) => { |
| 436 | self.mark_alive(); |
| 437 | return Ok(Some(self.deliver_fresh(event))); |
| 438 | } |
| 439 | Ok(TerminalInputMessage::Heartbeat) => { |
| 440 | self.mark_alive(); |
| 441 | } |
| 442 | Ok(TerminalInputMessage::Error(err)) => { |
| 443 | self.mark_alive(); |
| 444 | return Err(err); |
| 445 | } |
| 446 | Err(std::sync::mpsc::TryRecvError::Empty) => return Ok(None), |
| 447 | Err(std::sync::mpsc::TryRecvError::Disconnected) => return Ok(None), |
| 448 | } |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | pub(super) fn mark_alive(&self) { |
| 453 | self.last_alive_at.set(Instant::now()); |
| 454 | } |
| 455 | |
| 456 | pub(super) fn stalled_for(&self, now: Instant) -> Duration { |
| 457 | now.saturating_duration_since(self.last_alive_at.get()) |
| 458 | } |
| 459 | |
| 460 | /// Async: callers are on the event-loop task, so the ack wait uses |
| 461 | /// `tokio::time::sleep` — a `thread::sleep` here would park a Tokio |
| 462 | /// worker for up to `TERMINAL_INPUT_CHILD_PAUSE_TIMEOUT`. |
| 463 | pub(super) async fn pause_for_child_terminal(&self) -> io::Result<()> { |
| 464 | self.paused.store(true, Ordering::Release); |
| 465 | if self.handle.is_none() { |
| 466 | self.paused_ack.store(true, Ordering::Release); |
| 467 | self.claim_child_terminal_window(); |
| 468 | self.mark_alive(); |
| 469 | return Ok(()); |
| 470 | } |
| 471 | |
| 472 | let deadline = Instant::now() + TERMINAL_INPUT_CHILD_PAUSE_TIMEOUT; |
| 473 | while !self.paused_ack.load(Ordering::Acquire) { |
| 474 | if Instant::now() >= deadline { |
| 475 | self.paused_ack.store(false, Ordering::Release); |
| 476 | self.paused.store(false, Ordering::Release); |
| 477 | return Err(io::Error::new( |
| 478 | io::ErrorKind::TimedOut, |
| 479 | "terminal input pump did not pause before child terminal handoff", |
| 480 | )); |
| 481 | } |
| 482 | tokio::time::sleep(TERMINAL_INPUT_CHILD_PAUSE_POLL_INTERVAL).await; |
| 483 | } |
| 484 | self.claim_child_terminal_window(); |
| 485 | self.mark_alive(); |
| 486 | Ok(()) |
| 487 | } |
| 488 | |
| 489 | fn claim_child_terminal_window(&self) { |
| 490 | if let Some(window) = child_terminal_window_begin() { |
| 491 | self.child_windows.borrow_mut().push(window); |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | pub(super) fn resume_after_child_terminal(&self) { |
| 496 | let window = self.child_windows.borrow_mut().pop(); |
| 497 | child_terminal_window_end(window); |
| 498 | self.paused_ack.store(false, Ordering::Release); |
| 499 | self.paused.store(false, Ordering::Release); |
| 500 | self.mark_alive(); |
| 501 | } |
| 502 | |
| 503 | /// Replace a wedged pump thread with a freshly spawned one. |
| 504 | /// |
| 505 | /// The old thread may be blocked forever inside crossterm's blocking |
| 506 | /// `event::read` (a stalled Windows console poll, or a Unix tty that |
| 507 | /// stopped delivering bytes), so it can never be joined. Instead it is |
| 508 | /// detached: `stop` is flagged and the `JoinHandle` dropped, so if the |
| 509 | /// thread ever wakes its loop observes `stop` and exits on its own. |
| 510 | /// |
| 511 | /// A thread already inside `event::read` cannot be stopped and holds |
| 512 | /// crossterm's reader lock, so the one event it returns when the tty wakes |
| 513 | /// is the user's next input. The replaced channel is therefore kept as a |
| 514 | /// retired receiver. While one exists, waits run in short slices and every |
| 515 | /// slice, and every fresh event, checks the retired receivers first, so a |
| 516 | /// retired event is normally delivered ahead of the fresh reader's and without |
| 517 | /// waiting out the caller's deadline; a fresh event read in the meantime |
| 518 | /// is held and delivered next. Retired heartbeats and errors describe a |
| 519 | /// reader that no longer owns input and are ignored, and a retired event |
| 520 | /// whose read completed inside a child terminal window is discarded. That |
| 521 | /// test is read completion, not the moment the key arrived: a composer key |
| 522 | /// the reader had already buffered when the handoff began is discarded if |
| 523 | /// its read completed inside the window, and a key the child's session |
| 524 | /// consumed is still delivered to the composer if the reader only returned |
| 525 | /// after the window closed. At most `MAX_RETIRED_INPUT_READERS` are kept, |
| 526 | /// oldest dropped first, and a receiver whose thread has exited is pruned. |
| 527 | pub(super) fn restart_detached(&mut self) -> io::Result<()> { |
| 528 | self.detach_current_thread(); |
| 529 | let parts = Self::spawn_parts()?; |
| 530 | self.install_parts(parts); |
| 531 | Ok(()) |
| 532 | } |
| 533 | |
| 534 | /// Flag the current pump thread to stop and drop its handle without |
| 535 | /// joining (the thread may be wedged in a blocking terminal read). |
| 536 | pub(super) fn detach_current_thread(&mut self) { |
| 537 | self.stop.store(true, Ordering::Release); |
| 538 | let _ = self.handle.take(); |
| 539 | retract_child_terminal_gate(&self.paused); |
| 540 | } |
| 541 | |
| 542 | /// Adopt freshly spawned pump parts and reset the liveness clock; see |
| 543 | /// [`Self::restart_detached`]. |
| 544 | pub(super) fn install_parts(&mut self, parts: TerminalInputPumpParts) { |
| 545 | publish_child_terminal_gate(&parts.paused, &parts.paused_ack); |
| 546 | let replaced = std::mem::replace(&mut self.rx, parts.rx); |
| 547 | let retired = &mut self.retired_rx.get_mut().receivers; |
| 548 | retired.push(replaced); |
| 549 | if retired.len() > MAX_RETIRED_INPUT_READERS { |
| 550 | retired.remove(0); |
| 551 | } |
| 552 | self.stop = parts.stop; |
| 553 | self.paused = parts.paused; |
| 554 | self.paused_ack = parts.paused_ack; |
| 555 | self.handle = Some(parts.handle); |
| 556 | self.last_alive_at.set(Instant::now()); |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | impl Drop for TerminalInputPump { |
| 561 | fn drop(&mut self) { |
| 562 | // `event::read` can remain blocked forever after a tty disconnect on |
| 563 | // every supported desktop platform. Joining here would turn an input |
| 564 | // failure into an application shutdown hang. Flag the cooperative |
| 565 | // stop and detach; if the read ever wakes, the loop observes `stop` |
| 566 | // (or its send fails because `rx` was dropped) and exits on its own. |
| 567 | self.stop.store(true, Ordering::Release); |
| 568 | let _ = self.handle.take(); |
| 569 | for window in self.child_windows.get_mut().drain(..) { |
| 570 | child_terminal_window_end(Some(window)); |
| 571 | } |
| 572 | retract_child_terminal_gate(&self.paused); |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | pub(super) fn engine_drain_budget_exhausted( |
| 577 | events_drained: usize, |
| 578 | started: Instant, |
| 579 | now: Instant, |
| 580 | ) -> bool { |
| 581 | events_drained >= MAX_ENGINE_EVENTS_PER_DRAIN |
| 582 | || now.saturating_duration_since(started) >= ENGINE_DRAIN_TIME_BUDGET |
| 583 | } |
| 584 |