tern-sdk 0.2.0

Talk to Tern over the Tern Surface Protocol: typed node builders, diffing with derived ids, flow control, event routing, print/ask helpers and a plain-text fallback.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! The terminal a session talks through.
//!
//! [`Terminal`] lets tests and custom transports drive a session over
//! in-memory pipes; [`Tty`] is the process's own stdin/stdout in raw mode
//! (`poll(2)` on Unix, a console wait on Windows). `Tty` and tty detection
//! are available only on Unix and Windows; [`Terminal`] is portable.
//! [`Waker`] interrupts a session's wait for input from another thread.

use std::{
	io,
	sync::{
		Arc,
		atomic::{AtomicBool, Ordering},
	},
	time::Duration,
};

/// Wakes a session blocked in [`Session::next`](crate::Session::next) from
/// any thread: the wait returns `Ok(None)`.
#[derive(Clone, Debug)]
pub struct Waker(Arc<WakeInner>);

/// The shared state of a [`Waker`].
#[derive(Debug)]
struct WakeInner {
	/// Woken since the last [`Waker::take`].
	woken: AtomicBool,
	/// What interrupts a blocked [`Tty`] read.
	#[cfg(any(unix, windows))]
	sys:   sys::Wake,
}

impl Waker {
	/// A new waker, not woken.
	///
	/// # Errors
	/// When the OS can't create its wake handle (a pipe, an event).
	pub fn new() -> io::Result<Self> {
		Ok(Self(Arc::new(WakeInner {
			woken: AtomicBool::new(false),
			#[cfg(any(unix, windows))]
			sys: sys::Wake::new()?,
		})))
	}

	/// Interrupts the session's current or next wait for input.
	pub fn wake(&self) {
		self.0.woken.store(true, Ordering::Release);
		#[cfg(any(unix, windows))]
		self.0.sys.signal();
	}

	/// Whether it was woken since the last call; clears the flag.
	pub(crate) fn take(&self) -> bool {
		self.0.woken.swap(false, Ordering::AcqRel)
	}
}

/// Process-global terminal ownership, acquired before touching platform state.
#[cfg(any(unix, windows))]
static OWNED: AtomicBool = AtomicBool::new(false);

/// Releases exclusive tty ownership after restoration (also on setup failure).
#[cfg(any(unix, windows))]
#[derive(Debug)]
struct Ownership;

#[cfg(any(unix, windows))]
impl Ownership {
	fn acquire() -> io::Result<Self> {
		OWNED
			.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
			.map(|_| Self)
			.map_err(|_| {
				io::Error::new(io::ErrorKind::AlreadyExists, "the process tty is already in use")
			})
	}
}

#[cfg(any(unix, windows))]
impl Drop for Ownership {
	fn drop(&mut self) {
		OWNED.store(false, Ordering::Release);
	}
}

/// A byte stream to a terminal with a timed read.
pub trait Terminal {
	/// Writes all of `bytes` and flushes.
	///
	/// # Errors
	/// When the output fails.
	fn write(&mut self, bytes: &[u8]) -> io::Result<()>;

	/// Reads available input into `buf`, waiting at most `timeout` (`None`
	/// waits for input). `Ok(None)` means the wait timed out; `Ok(Some(0))`
	/// that the input is closed.
	///
	/// # Errors
	/// When the input fails.
	fn read(&mut self, buf: &mut [u8], timeout: Option<Duration>) -> io::Result<Option<usize>>;

	/// Puts the terminal back as it was (leaves raw mode). Called once, when
	/// the session closes or fails to connect.
	///
	/// # Errors
	/// When the terminal can't be restored.
	fn restore(&mut self) -> io::Result<()> {
		Ok(())
	}

	/// Notes which input modes the session enabled, so a process killed by a
	/// signal can still undo them.
	fn modes(&mut self, _paste: bool, _kitty: bool) {}

	/// The waker that interrupts [`read`](Self::read), when the terminal has
	/// one. A session reports a wake as `Ok(None)` from its wait.
	fn waker(&self) -> Option<Waker> {
		None
	}
}

/// Whether stdin and stdout are both terminals.
#[cfg(any(unix, windows))]
pub fn is_tty() -> bool {
	sys::is_tty()
}

/// Whether stdout is a terminal.
#[cfg(any(unix, windows))]
pub fn stdout_is_tty() -> bool {
	sys::stdout_is_tty()
}

/// The width of the terminal on stdout in columns, when it is one.
#[cfg(any(unix, windows))]
pub fn columns() -> Option<u16> {
	sys::columns()
}

/// The process's own terminal (stdin and stdout), in raw mode while it
/// lives.
#[cfg(any(unix, windows))]
#[derive(Debug)]
pub struct Tty {
	/// The platform state.
	inner:     sys::Raw,
	/// Restored already.
	restored:  bool,
	/// Held until restoration finishes.
	ownership: Option<Ownership>,
	/// Interrupts a blocked read.
	waker:     Waker,
}

#[cfg(any(unix, windows))]
impl Tty {
	/// Switches the terminal to raw input: no echo, no line editing, no
	/// signals from keys (Ctrl+C is a key). Output processing stays on.
	///
	/// # Errors
	/// When stdin is not a terminal or its mode can't be changed.
	pub fn open() -> io::Result<Self> {
		let ownership = Ownership::acquire()?;
		let waker = Waker::new()?;
		Ok(Self { inner: sys::Raw::enter()?, restored: false, ownership: Some(ownership), waker })
	}
}

#[cfg(any(unix, windows))]
impl Terminal for Tty {
	fn write(&mut self, bytes: &[u8]) -> io::Result<()> {
		use io::Write as _;
		let mut out = io::stdout().lock();
		out.write_all(bytes)?;
		out.flush()
	}

	fn read(&mut self, buf: &mut [u8], timeout: Option<Duration>) -> io::Result<Option<usize>> {
		self.inner.read(buf, timeout, &self.waker.0.sys)
	}

	fn waker(&self) -> Option<Waker> {
		Some(self.waker.clone())
	}

	fn restore(&mut self) -> io::Result<()> {
		if self.restored {
			return Ok(());
		}
		self.restored = true;
		let result = self.inner.leave();
		self.ownership.take();
		result
	}

	fn modes(&mut self, paste: bool, kitty: bool) {
		sys::set_modes(paste, kitty);
	}
}

#[cfg(any(unix, windows))]
impl Drop for Tty {
	fn drop(&mut self) {
		if let Err(err) = self.restore() {
			tracing::warn!(%err, "could not restore the terminal");
		}
	}
}

#[cfg(all(test, any(unix, windows)))]
mod tests {
	use super::Ownership;

	#[test]
	fn tty_ownership_is_exclusive_and_released_by_drop() {
		let first = Ownership::acquire().expect("first owner");
		assert!(Ownership::acquire().is_err());
		drop(first);
		assert!(Ownership::acquire().is_ok());
	}
}

/// Writes console text `units` (UTF-16) into `buf` as UTF-8 and returns the
/// bytes written: a high surrogate `high` held from the last read goes
/// first, one `units` ends on is held there for the next, and unpaired
/// surrogates become U+FFFD. `buf` takes 3 bytes per unit, plus 3.
#[cfg(any(windows, test))]
fn utf16_to_utf8(high: &mut Option<u16>, units: &[u16], buf: &mut [u8]) -> usize {
	let mut units = high
		.take()
		.into_iter()
		.chain(units.iter().copied())
		.peekable();
	let mut n = 0;
	while let Some(unit) = units.next() {
		let ch = if (0xd800..0xdc00).contains(&unit) {
			match units.peek().copied() {
				None => {
					*high = Some(unit);
					break;
				},
				Some(low) if (0xdc00..0xe000).contains(&low) => {
					units.next();
					char::decode_utf16([unit, low])
						.next()
						.and_then(Result::ok)
						.unwrap_or(char::REPLACEMENT_CHARACTER)
				},
				Some(_) => char::REPLACEMENT_CHARACTER,
			}
		} else {
			char::from_u32(u32::from(unit)).unwrap_or(char::REPLACEMENT_CHARACTER)
		};
		n += ch.encode_utf8(&mut buf[n..]).len();
	}
	n
}

#[cfg(test)]
mod utf16_tests {
	use super::utf16_to_utf8;

	/// UTF-8 of `units` read in the given pieces, one buffer per read.
	fn read(pieces: &[&[u16]]) -> String {
		let mut high = None;
		let mut out = Vec::new();
		for units in pieces {
			let mut buf = [0u8; 64];
			let n = utf16_to_utf8(&mut high, units, &mut buf);
			out.extend_from_slice(&buf[..n]);
		}
		String::from_utf8(out).expect("UTF-8")
	}

	#[test]
	fn console_text_reaches_the_program_as_utf8() {
		let units = |s: &str| s.encode_utf16().collect::<Vec<_>>();
		// One committed Chinese character, as a Pinyin input method types it.
		assert_eq!(read(&[&units("中")]), "中");
		assert_eq!(read(&[&units("\x1b[Aa中文")]), "\x1b[Aa中文");
		// A pair split across two reads is held, not lost.
		let emoji = units("😀");
		assert_eq!(read(&[&emoji[..1], &emoji[1..]]), "😀");
		assert_eq!(read(&[&[0xdc00], &[0xd800, 0x61]]), "\u{fffd}\u{fffd}a");
	}
}

/// The bytes that undo the input modes a session enabled.
pub(crate) const fn mode_reset(paste: bool, kitty: bool) -> &'static [u8] {
	match (paste, kitty) {
		(true, true) => b"\x1b[<u\x1b[?2004l",
		(false, true) => b"\x1b[<u",
		(true, false) => b"\x1b[?2004l",
		(false, false) => b"",
	}
}

#[cfg(unix)]
mod sys {
	use std::{
		cell::UnsafeCell,
		io,
		mem::MaybeUninit,
		sync::atomic::{AtomicBool, AtomicU8, Ordering},
		time::Duration,
	};

	/// The termios to restore from a signal handler.
	struct Saved(UnsafeCell<MaybeUninit<libc::termios>>);

	// SAFETY: written once before `ARMED` is set (release) and only read after
	// `ARMED` is seen set (acquire); never written while armed.
	unsafe impl Sync for Saved {}

	/// The termios saved by the live [`Raw`].
	static SAVED: Saved = Saved(UnsafeCell::new(MaybeUninit::uninit()));
	/// Whether a signal should restore `SAVED`.
	static ARMED: AtomicBool = AtomicBool::new(false);
	/// Input modes enabled: bit 0 bracketed paste, bit 1 kitty keys.
	static MODES: AtomicU8 = AtomicU8::new(0);

	/// The signals that restore the terminal before the process ends.
	const SIGNALS: [libc::c_int; 4] = [libc::SIGTERM, libc::SIGHUP, libc::SIGINT, libc::SIGQUIT];

	/// A non-blocking pipe: a byte written to `write` makes `read` readable.
	#[derive(Debug)]
	pub(super) struct Wake {
		/// The end polled beside stdin.
		read:  libc::c_int,
		/// The end [`signal`](Self::signal) writes.
		write: libc::c_int,
	}

	impl Wake {
		pub(super) fn new() -> io::Result<Self> {
			let mut fds = [0; 2];
			// SAFETY: pipe writes two descriptors into the array.
			if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
				return Err(io::Error::last_os_error());
			}
			let wake = Self { read: fds[0], write: fds[1] };
			for fd in fds {
				// SAFETY: fd is an open descriptor this value owns.
				let ok = unsafe {
					let flags = libc::fcntl(fd, libc::F_GETFL);
					flags >= 0
						&& libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) == 0
						&& libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) == 0
				};
				if !ok {
					return Err(io::Error::last_os_error());
				}
			}
			Ok(wake)
		}

		/// Makes the read end readable; a full pipe (`EAGAIN`) is already so.
		pub(super) fn signal(&self) {
			// SAFETY: writes one byte from a valid buffer to an owned descriptor.
			unsafe { libc::write(self.write, [1u8].as_ptr().cast(), 1) };
		}

		/// Empties the read end.
		fn drain(&self) {
			let mut buf = [0u8; 64];
			// SAFETY: reads at most buf.len() bytes into buf from an owned,
			// non-blocking descriptor.
			while unsafe { libc::read(self.read, buf.as_mut_ptr().cast(), buf.len()) } > 0 {}
		}
	}

	impl Drop for Wake {
		fn drop(&mut self) {
			// SAFETY: both descriptors are owned and closed once.
			unsafe {
				libc::close(self.read);
				libc::close(self.write);
			}
		}
	}

	/// Raw mode on stdin, with the previous state to restore.
	#[derive(Debug)]
	pub(super) struct Raw {
		/// The termios before raw mode.
		saved:    libc::termios,
		/// The signal dispositions before ours.
		previous: Vec<(libc::c_int, libc::sigaction)>,
	}

	pub(super) fn is_tty() -> bool {
		// SAFETY: isatty only inspects the descriptors.
		unsafe { libc::isatty(0) == 1 && libc::isatty(1) == 1 }
	}

	pub(super) fn stdout_is_tty() -> bool {
		// SAFETY: isatty only inspects the descriptor.
		unsafe { libc::isatty(1) == 1 }
	}

	pub(super) fn columns() -> Option<u16> {
		let mut size = MaybeUninit::<libc::winsize>::zeroed();
		// SAFETY: TIOCGWINSZ writes a winsize through the pointer.
		let ok = unsafe { libc::ioctl(1, libc::TIOCGWINSZ, size.as_mut_ptr()) } == 0;
		// SAFETY: zero-initialized, and filled in when the call succeeded.
		let size = unsafe { size.assume_init() };
		(ok && size.ws_col > 0).then_some(size.ws_col)
	}

	pub(super) fn set_modes(paste: bool, kitty: bool) {
		MODES.store(u8::from(paste) | (u8::from(kitty) << 1), Ordering::Release);
	}

	/// Restores the terminal and undoes the modes, then dies of the signal.
	extern "C" fn on_signal(sig: libc::c_int) {
		if ARMED.load(Ordering::Acquire) {
			let modes = MODES.load(Ordering::Acquire);
			let reset = super::mode_reset(modes & 1 != 0, modes & 2 != 0);
			// SAFETY: write and tcsetattr are async-signal-safe; `SAVED` was
			// initialized before `ARMED` was set.
			unsafe {
				libc::write(1, reset.as_ptr().cast(), reset.len());
				libc::tcsetattr(0, libc::TCSANOW, (*SAVED.0.get()).as_ptr());
			}
		}
		// SAFETY: signal and raise are async-signal-safe.
		unsafe {
			libc::signal(sig, libc::SIG_DFL);
			libc::raise(sig);
		}
	}

	impl Raw {
		pub(super) fn enter() -> io::Result<Self> {
			let mut termios = MaybeUninit::<libc::termios>::uninit();
			// SAFETY: tcgetattr fills the termios when it succeeds.
			if unsafe { libc::tcgetattr(0, termios.as_mut_ptr()) } != 0 {
				return Err(io::Error::last_os_error());
			}
			// SAFETY: initialized by the successful tcgetattr.
			let saved = unsafe { termios.assume_init() };
			let mut raw = saved;
			raw.c_iflag &= !(libc::IGNBRK
				| libc::BRKINT
				| libc::PARMRK
				| libc::ISTRIP
				| libc::INLCR
				| libc::IGNCR
				| libc::ICRNL
				| libc::IXON);
			raw.c_lflag &= !(libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN);
			raw.c_cflag &= !(libc::CSIZE | libc::PARENB);
			raw.c_cflag |= libc::CS8;
			raw.c_cc[libc::VMIN] = 1;
			raw.c_cc[libc::VTIME] = 0;
			// SAFETY: not armed, so no handler reads SAVED while it is written.
			unsafe { (*SAVED.0.get()).write(saved) };
			ARMED.store(true, Ordering::Release);
			let mut previous = Vec::with_capacity(SIGNALS.len());
			for sig in SIGNALS {
				// SAFETY: a zeroed sigaction is valid; sigaction fills `old`.
				unsafe {
					let mut action: libc::sigaction = std::mem::zeroed();
					action.sa_sigaction = on_signal as extern "C" fn(libc::c_int) as usize;
					libc::sigemptyset(&mut action.sa_mask);
					let mut old: libc::sigaction = std::mem::zeroed();
					if libc::sigaction(sig, &action, &mut old) != 0 {
						let err = io::Error::last_os_error();
						let mut state = Self { saved, previous };
						let _ = state.leave();
						return Err(err);
					}
					previous.push((sig, old));
				}
			}
			let mut state = Self { saved, previous };
			// SAFETY: restoration is armed before this valid termios is applied.
			if unsafe { libc::tcsetattr(0, libc::TCSANOW, &raw) } != 0 {
				let err = io::Error::last_os_error();
				let _ = state.leave();
				return Err(err);
			}
			Ok(state)
		}

		#[allow(clippy::unused_self, reason = "the Windows version reads through its handle")]
		pub(super) fn read(
			&self,
			buf: &mut [u8],
			timeout: Option<Duration>,
			wake: &Wake,
		) -> io::Result<Option<usize>> {
			let ms = timeout
				.map_or(-1, |t| libc::c_int::try_from(t.as_millis()).unwrap_or(libc::c_int::MAX));
			let mut fds = [libc::pollfd { fd: 0, events: libc::POLLIN, revents: 0 }, libc::pollfd {
				fd:      wake.read,
				events:  libc::POLLIN,
				revents: 0,
			}];
			// SAFETY: two valid pollfds.
			let n = unsafe { libc::poll(fds.as_mut_ptr(), 2, ms) };
			if n < 0 {
				let err = io::Error::last_os_error();
				return if err.kind() == io::ErrorKind::Interrupted {
					Ok(None)
				} else {
					Err(err)
				};
			}
			if fds[1].revents != 0 {
				wake.drain();
			}
			if n == 0 || fds[0].revents == 0 {
				return Ok(None);
			}
			// SAFETY: reads at most buf.len() bytes into buf.
			let got = unsafe { libc::read(0, buf.as_mut_ptr().cast(), buf.len()) };
			if got < 0 {
				let err = io::Error::last_os_error();
				return match err.kind() {
					io::ErrorKind::Interrupted | io::ErrorKind::WouldBlock => Ok(None),
					_ => Err(err),
				};
			}
			Ok(Some(got as usize))
		}

		pub(super) fn leave(&mut self) -> io::Result<()> {
			// SAFETY: saved is the termios tcgetattr returned.
			let result = if unsafe { libc::tcsetattr(0, libc::TCSANOW, &self.saved) } == 0 {
				Ok(())
			} else {
				Err(io::Error::last_os_error())
			};
			ARMED.store(false, Ordering::Release);
			MODES.store(0, Ordering::Release);
			for (sig, old) in self.previous.drain(..) {
				// SAFETY: restores the disposition sigaction gave us.
				unsafe { libc::sigaction(sig, &old, std::ptr::null_mut()) };
			}
			result
		}
	}
}

#[cfg(windows)]
mod sys {
	use std::{io, time::Duration};

	use windows_sys::Win32::{
		Foundation::{CloseHandle, FALSE, HANDLE, WAIT_OBJECT_0},
		System::{
			Console::{
				CONSOLE_SCREEN_BUFFER_INFO, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT,
				ENABLE_PROCESSED_INPUT, ENABLE_PROCESSED_OUTPUT, ENABLE_VIRTUAL_TERMINAL_INPUT,
				ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetConsoleScreenBufferInfo,
				GetStdHandle, INPUT_RECORD, KEY_EVENT, PeekConsoleInputW, ReadConsoleInputW,
				ReadConsoleW, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, SetConsoleMode,
			},
			Threading::{CreateEventW, INFINITE, SetEvent, WaitForMultipleObjects},
		},
	};

	/// An auto-reset event that interrupts a console wait.
	#[derive(Debug)]
	pub(super) struct Wake {
		/// The event handle.
		event: HANDLE,
	}

	// SAFETY: an event handle may be signaled and waited on from any thread.
	unsafe impl Send for Wake {}
	// SAFETY: as above; `SetEvent` and waits are thread-safe.
	unsafe impl Sync for Wake {}

	impl Wake {
		pub(super) fn new() -> io::Result<Self> {
			// SAFETY: default security, auto-reset, initially unsignaled, unnamed.
			let event = unsafe { CreateEventW(std::ptr::null(), FALSE, FALSE, std::ptr::null()) };
			if event.is_null() {
				return Err(io::Error::last_os_error());
			}
			Ok(Self { event })
		}

		/// Signals the event; a wait consumes it.
		pub(super) fn signal(&self) {
			// SAFETY: a valid event handle.
			unsafe { SetEvent(self.event) };
		}
	}

	impl Drop for Wake {
		fn drop(&mut self) {
			// SAFETY: the handle is owned and closed once.
			unsafe { CloseHandle(self.event) };
		}
	}

	/// UTF-16 units one console read takes at most.
	const WIDE: usize = 2048;

	/// Raw mode on the console, with the previous modes to restore.
	#[derive(Debug)]
	pub(super) struct Raw {
		/// The console input handle.
		input:    HANDLE,
		/// The console output handle.
		output:   HANDLE,
		/// The input mode before.
		in_mode:  u32,
		/// The output mode before.
		out_mode: u32,
		/// A high surrogate the last read ended on, awaiting its low half.
		high:     Option<u16>,
	}

	/// The console mode of `handle`, when it is a console.
	fn mode(handle: HANDLE) -> Option<u32> {
		let mut mode = 0;
		// SAFETY: GetConsoleMode writes a u32.
		(unsafe { GetConsoleMode(handle, &mut mode) } != 0).then_some(mode)
	}

	pub(super) fn is_tty() -> bool {
		// SAFETY: GetStdHandle has no preconditions.
		let (input, output) =
			unsafe { (GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE)) };
		mode(input).is_some() && mode(output).is_some()
	}

	pub(super) fn stdout_is_tty() -> bool {
		// SAFETY: GetStdHandle has no preconditions.
		mode(unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }).is_some()
	}

	pub(super) fn columns() -> Option<u16> {
		// SAFETY: a zeroed buffer info is valid; the call fills it.
		unsafe {
			let mut info: CONSOLE_SCREEN_BUFFER_INFO = std::mem::zeroed();
			if GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &mut info) == 0 {
				return None;
			}
			u16::try_from(info.srWindow.Right - info.srWindow.Left + 1).ok()
		}
	}

	pub(super) const fn set_modes(_paste: bool, _kitty: bool) {}

	impl Raw {
		pub(super) fn enter() -> io::Result<Self> {
			// SAFETY: GetStdHandle has no preconditions.
			let (input, output) =
				unsafe { (GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE)) };
			let in_mode = mode(input).ok_or_else(io::Error::last_os_error)?;
			let out_mode = mode(output).ok_or_else(io::Error::last_os_error)?;
			let raw_in = (in_mode & !(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT))
				| ENABLE_VIRTUAL_TERMINAL_INPUT;
			let raw_out = out_mode | ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
			// SAFETY: valid console handles and modes.
			unsafe {
				if SetConsoleMode(input, raw_in) == 0 {
					return Err(io::Error::last_os_error());
				}
				if SetConsoleMode(output, raw_out) == 0 {
					let err = io::Error::last_os_error();
					SetConsoleMode(input, in_mode);
					return Err(err);
				}
			}
			Ok(Self { input, output, in_mode, out_mode, high: None })
		}

		/// Whether a key press is queued; other console events are discarded,
		/// since reading bytes would block on them.
		fn key_ready(&self) -> io::Result<bool> {
			loop {
				let mut record = INPUT_RECORD::default();
				let mut n = 0;
				// SAFETY: one record buffer.
				if unsafe { PeekConsoleInputW(self.input, &mut record, 1, &mut n) } == 0 {
					return Err(io::Error::last_os_error());
				}
				if n == 0 {
					return Ok(false);
				}
				// SAFETY: EventType says which union field is set.
				let key_down = u32::from(record.EventType) == KEY_EVENT
					&& unsafe {
						let key = record.Event.KeyEvent;
						key.bKeyDown != 0
							&& (key.uChar.UnicodeChar != 0
								|| matches!(key.wVirtualKeyCode,
								0x08 | 0x09 | 0x0d | 0x1b | 0x20..=0x28 | 0x2d | 0x2e | 0x70..=0x87))
					};
				if key_down {
					return Ok(true);
				}
				// SAFETY: one record buffer.
				if unsafe { ReadConsoleInputW(self.input, &mut record, 1, &mut n) } == 0 {
					return Err(io::Error::last_os_error());
				}
			}
		}

		pub(super) fn read(
			&mut self,
			buf: &mut [u8],
			timeout: Option<Duration>,
			wake: &Wake,
		) -> io::Result<Option<usize>> {
			let ms =
				timeout.map_or(INFINITE, |t| u32::try_from(t.as_millis()).unwrap_or(INFINITE - 1));
			let handles = [self.input, wake.event];
			// SAFETY: two valid handles.
			if unsafe { WaitForMultipleObjects(2, handles.as_ptr(), FALSE, ms) } != WAIT_OBJECT_0 {
				return Ok(None);
			}
			if !self.key_ready()? {
				return Ok(None);
			}
			// The text comes as UTF-16 (`ReadConsoleW`), handed on as UTF-8:
			// bytes (`ReadFile`) come in the console's input code page, which
			// loses what it lacks and turns the rest of a multi-byte one such
			// as GBK into no UTF-8 at all (a Chinese input method's single
			// committed character never arrived).
			// A unit takes at most 3 UTF-8 bytes, a held high surrogate with
			// its low half 4.
			let room = (buf.len() / 3).saturating_sub(1).clamp(1, WIDE);
			let mut wide = [0u16; WIDE];
			let mut got = 0;
			// SAFETY: reads at most `room` UTF-16 units into `wide`.
			if unsafe {
				ReadConsoleW(
					self.input,
					wide.as_mut_ptr().cast(),
					u32::try_from(room).unwrap_or(u32::MAX),
					&mut got,
					std::ptr::null(),
				)
			} == 0
			{
				return Err(io::Error::last_os_error());
			}
			let n = super::utf16_to_utf8(&mut self.high, &wide[..(got as usize).min(room)], buf);
			// Half a pair alone hands on nothing yet (0 would mean the input
			// closed).
			Ok((n > 0).then_some(n))
		}

		pub(super) fn leave(&mut self) -> io::Result<()> {
			// SAFETY: valid console handles and the modes they had.
			unsafe {
				let input = SetConsoleMode(self.input, self.in_mode);
				let input_error = (input == 0).then(io::Error::last_os_error);
				let output = SetConsoleMode(self.output, self.out_mode);
				if let Some(err) = input_error {
					return Err(err);
				}
				if output == 0 {
					return Err(io::Error::last_os_error());
				}
			}
			Ok(())
		}
	}
}