uncurses/terminal/handle.rs
1//! [`Terminal`] — a typed input/output handle with raw-mode state.
2//!
3//! A `Terminal<I, O>` bundles a readable input half, a writable output half,
4//! an [`Env`], and one optional saved raw-mode [`State`]. It implements
5//! [`Read`] and [`Write`] by delegating to those halves, so it can be used
6//! directly for byte-level terminal control or split into halves for a
7//! renderer and an event source.
8//!
9//! ## Raw-mode ownership
10//!
11//! `Terminal` is not `Copy` because it owns the saved state used by
12//! [`restore`](Terminal::restore). [`make_raw`](Terminal::make_raw) stores the
13//! pre-raw state inside the handle and returns a clone to the caller.
14//! [`restore`](Terminal::restore) applies and clears that cached state. There
15//! is no `Drop` restoration; callers must restore explicitly.
16//!
17//! ## Choosing handles
18//!
19//! [`Terminal::stdio`] uses inherited stdin/stdout. [`Terminal::open`] opens
20//! the controlling terminal directly, which keeps terminal I/O available when
21//! stdio is redirected. For custom handles, [`Terminal::new`] pairs any
22//! platform terminal input/output types with an explicit environment.
23//!
24//! ```rust,ignore
25//! use std::io::Write;
26//! use uncurses::buffer::TextBuffer;
27//! use uncurses::event::EventSource;
28//! use uncurses::terminal::Terminal;
29//! use uncurses::text::Encode;
30//!
31//! let mut term = Terminal::open()?;
32//! let _saved = term.make_raw()?;
33//! let size = term.get_window_size()?;
34//! let mut frame = TextBuffer::new(size.col, size.row);
35//! let mut source = EventSource::new(term.input())?;
36//!
37//! // Paint `frame`, read events from `source`.
38//! frame.encode(&mut term.output())?;
39//! term.restore()?;
40//! # Ok::<(), std::io::Error>(())
41//! ```
42
43use std::io::{self, Read, Write};
44
45#[cfg(unix)]
46use std::os::fd::{AsFd, BorrowedFd};
47#[cfg(windows)]
48use std::os::windows::io::{AsHandle, BorrowedHandle};
49
50use super::AsTerminalHandle;
51use super::env::{Env, ProcessEnv};
52use super::raw::{self, State};
53use super::size::{Winsize, get_window_size};
54use super::stdio::{Stdin, Stdout, stdin, stdout};
55use super::tty::{TtyInput, TtyOutput, open_tty};
56
57/// Owned terminal handle pairing input, output, environment, and raw-mode
58/// state.
59///
60/// `Terminal` implements [`Read`] from `I` and [`Write`] to `O`. The handle is
61/// generic so callers can use inherited stdio, the controlling terminal, or
62/// test doubles, while sharing one raw-mode and window-size API on supported
63/// platforms.
64///
65/// [`EventSource`]: crate::event::EventSource
66pub struct Terminal<I, O> {
67 input: I,
68 output: O,
69 /// State captured by the most recent [`make_raw`](Self::make_raw),
70 /// applied (and cleared) by [`restore`](Self::restore).
71 saved: Option<State>,
72 env: Box<dyn Env>,
73}
74
75impl Terminal<Stdin, Stdout> {
76 /// Create a terminal over inherited standard input and output.
77 ///
78 /// The returned handle uses [`stdin`] for input, [`stdout`] for output, and
79 /// [`ProcessEnv`] for its environment. Use this when the
80 /// process is expected to be connected directly to the terminal.
81 ///
82 /// # Returns
83 ///
84 /// A `Terminal<Stdin, Stdout>` with no saved raw-mode state.
85 ///
86 /// # Errors and panics
87 ///
88 /// This constructor does not fail or intentionally panic.
89 ///
90 /// # Usage note
91 ///
92 /// If stdin or stdout may be redirected, prefer [`Terminal::open`] to open
93 /// the controlling terminal directly.
94 pub fn stdio() -> Self {
95 Self::new(stdin(), stdout(), ProcessEnv)
96 }
97}
98
99impl Terminal<TtyInput, TtyOutput> {
100 /// Open the controlling terminal directly.
101 ///
102 /// On Unix this opens `/dev/tty` for both input and output. On Windows it
103 /// opens `CONIN$` for input and `CONOUT$` for output. The returned
104 /// `Terminal` reads the live process environment through [`ProcessEnv`].
105 ///
106 /// # Returns
107 ///
108 /// A `Terminal<TtyInput, TtyOutput>` backed by the controlling terminal.
109 ///
110 /// # Errors
111 ///
112 /// Returns the error from `open_tty` if the process has no controlling
113 /// terminal or if the platform device cannot be opened.
114 ///
115 /// # Panics
116 ///
117 /// This function does not intentionally panic.
118 pub fn open() -> io::Result<Self> {
119 let (input, output) = open_tty()?;
120 Ok(Self::new(input, output, ProcessEnv))
121 }
122}
123
124impl<I, O> Terminal<I, O> {
125 /// Build a terminal directly from its parts, without touching any fd.
126 ///
127 /// Test-only constructor used to assemble a [`Terminal`] over in-memory
128 /// or non-tty handles (for example a `Vec<u8>` output) where the
129 /// fd-bound [`new`](Self::new) cannot apply. No raw-mode state is
130 /// captured.
131 #[cfg(test)]
132 pub(crate) fn from_parts(input: I, output: O, env: impl Env + 'static) -> Self {
133 Self {
134 input,
135 output,
136 saved: None,
137 env: Box::new(env),
138 }
139 }
140
141 /// Return the terminal's environment.
142 ///
143 /// Whether lookups see later changes to the process environment depends on
144 /// the [`Env`] the terminal was built with.
145 ///
146 /// # Returns
147 ///
148 /// A shared reference to the terminal's [`Env`].
149 ///
150 /// # Errors and panics
151 ///
152 /// This method does not fail or intentionally panic.
153 pub fn env(&self) -> &dyn Env {
154 self.env.as_ref()
155 }
156
157 /// Look up an environment variable.
158 ///
159 /// # Parameters
160 ///
161 /// * `key` — environment variable name.
162 ///
163 /// # Returns
164 ///
165 /// The value for `key`, or `None` if it is absent.
166 ///
167 /// # Errors and panics
168 ///
169 /// This method does not fail or intentionally panic.
170 pub fn get_env(&self, key: &str) -> Option<String> {
171 self.env.get(key)
172 }
173
174 /// Return whether an environment variable is present and non-empty.
175 ///
176 /// # Parameters
177 ///
178 /// * `key` — environment variable name.
179 ///
180 /// # Returns
181 ///
182 /// `true` when `key` is present with a non-empty value.
183 ///
184 /// # Errors and panics
185 ///
186 /// This method does not fail or intentionally panic.
187 pub fn has_env(&self, key: &str) -> bool {
188 self.env.has(key)
189 }
190
191 /// Return a copy of the input half.
192 ///
193 /// This is available only when `I: Copy`, which is true for the standard
194 /// and controlling-terminal handle types provided by this module. Use it to
195 /// pass input to [`EventSource::new`](crate::event::EventSource::new) while
196 /// retaining the `Terminal` for raw-mode restoration.
197 ///
198 /// # Returns
199 ///
200 /// A copy of the input handle.
201 ///
202 /// # Errors and panics
203 ///
204 /// This method does not fail or intentionally panic.
205 pub fn input(&self) -> I
206 where
207 I: Copy,
208 {
209 self.input
210 }
211
212 /// Return a copy of the output half.
213 ///
214 /// This is available only when `O: Copy`, which is true for the standard
215 /// and controlling-terminal output types provided by this module. Use it to
216 /// pass output to a renderer such as [`TextBuffer`](crate::buffer::TextBuffer) while
217 /// retaining the `Terminal` for raw-mode restoration.
218 ///
219 /// # Returns
220 ///
221 /// A copy of the output handle.
222 ///
223 /// # Errors and panics
224 ///
225 /// This method does not fail or intentionally panic.
226 pub fn output(&self) -> O
227 where
228 O: Copy,
229 {
230 self.output
231 }
232
233 /// Consume the terminal and return its input and output halves.
234 ///
235 /// Any cached raw-mode state is dropped without being applied. Restore
236 /// before calling this method if the terminal is in raw mode.
237 ///
238 /// # Returns
239 ///
240 /// `(input, output)`.
241 ///
242 /// # Errors and panics
243 ///
244 /// This method does not fail or intentionally panic.
245 pub fn into_halves(self) -> (I, O) {
246 (self.input, self.output)
247 }
248}
249
250impl<I: Read, O> Read for Terminal<I, O> {
251 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
252 self.input.read(buf)
253 }
254}
255
256impl<I, O: Write> Write for Terminal<I, O> {
257 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
258 self.output.write(buf)
259 }
260
261 fn flush(&mut self) -> io::Result<()> {
262 self.output.flush()
263 }
264}
265
266#[cfg(unix)]
267impl<I: AsFd, O> AsFd for Terminal<I, O> {
268 /// Borrow the input descriptor.
269 ///
270 /// This exposes the input half, not the output half. Use
271 /// [`output`](Self::output) and borrow that handle when an output
272 /// descriptor is required.
273 fn as_fd(&self) -> BorrowedFd<'_> {
274 self.input.as_fd()
275 }
276}
277
278#[cfg(windows)]
279impl<I: AsHandle, O> AsHandle for Terminal<I, O> {
280 /// Borrow the input handle.
281 ///
282 /// This exposes the input half, not the output half. Use
283 /// [`output`](Self::output) and borrow that handle when an output handle is
284 /// required.
285 fn as_handle(&self) -> BorrowedHandle<'_> {
286 self.input.as_handle()
287 }
288}
289
290impl<I: AsTerminalHandle, O: AsTerminalHandle> Terminal<I, O> {
291 /// Build a terminal from input and output handles plus an [`Env`].
292 ///
293 /// The environment is stored exactly as provided and is not required to
294 /// describe the given handles. Use [`Terminal::stdio`] or
295 /// [`Terminal::open`] to use the process environment automatically.
296 ///
297 /// On Unix, the two descriptors need not refer to the same device. Raw
298 /// mode is applied to and restored from each one independently, so pairing
299 /// two different terminals configures both, and pairing a terminal with a
300 /// pipe configures only the terminal half.
301 /// On Windows, both handles must support console mode queries.
302 ///
303 /// # Parameters
304 ///
305 /// * `input` — readable terminal handle.
306 /// * `output` — writable terminal handle.
307 /// * `env` — environment this terminal reads variables from.
308 ///
309 /// # Returns
310 ///
311 /// A `Terminal` with no saved raw-mode state.
312 ///
313 /// # Errors and panics
314 ///
315 /// This constructor does not fail or intentionally panic.
316 pub fn new(input: I, output: O, env: impl Env + 'static) -> Self {
317 Self {
318 input,
319 output,
320 saved: None,
321 env: Box::new(env),
322 }
323 }
324
325 /// Put the terminal into raw mode and save the previous state.
326 ///
327 /// This calls `make_raw_mode` with the terminal's input and output
328 /// handles. The returned pre-raw [`State`] is cloned into the terminal
329 /// so [`restore`](Self::restore) can later apply it without an argument.
330 ///
331 /// # Returns
332 ///
333 /// The state that was active before raw mode was applied.
334 ///
335 /// # Errors
336 ///
337 /// Returns any error from reading the current state or applying the raw
338 /// state.
339 ///
340 /// # Panics
341 ///
342 /// This method does not intentionally panic.
343 pub fn make_raw(&mut self) -> io::Result<State> {
344 let prev = raw::make_raw_mode(&self.input, &self.output)?;
345 self.saved = Some(prev.clone());
346 Ok(prev)
347 }
348
349 /// Restore the state cached by the most recent [`make_raw`](Self::make_raw).
350 ///
351 /// If a state is cached, it is applied with `set_state` and then
352 /// cleared. If no state is cached, this is a no-op. The cache is kept when
353 /// applying fails, so a failed restore can be retried rather than losing
354 /// the only copy of the pre-raw state.
355 ///
356 /// # Returns
357 ///
358 /// `Ok(())` when no state was cached or restoration succeeded.
359 ///
360 /// # Errors
361 ///
362 /// Returns any error from applying the cached state.
363 ///
364 /// # Panics
365 ///
366 /// This method does not intentionally panic.
367 pub fn restore(&mut self) -> io::Result<()> {
368 #[cfg(windows)]
369 return self.restore_with_input(|_| {});
370
371 #[cfg(not(windows))]
372 if let Some(state) = self.saved.as_ref() {
373 raw::set_state(&self.input, &self.output, state)?;
374 self.saved = None;
375 }
376 #[cfg(not(windows))]
377 Ok(())
378 }
379
380 #[cfg(windows)]
381 pub(crate) fn restore_with_input(&mut self, on_input: impl FnOnce(u32)) -> io::Result<()> {
382 if let Some(state) = self.saved.as_ref() {
383 raw::set_state_with_input(&self.input, &self.output, state, on_input)?;
384 self.saved = None;
385 }
386 Ok(())
387 }
388
389 /// Snapshot the current terminal mode.
390 ///
391 /// This reads the terminal state without modifying the cached state used by
392 /// [`restore`](Self::restore).
393 ///
394 /// # Returns
395 ///
396 /// The current [`State`].
397 ///
398 /// # Errors
399 ///
400 /// Returns any error from `get_state`.
401 ///
402 /// # Panics
403 ///
404 /// This method does not intentionally panic.
405 pub fn get_state(&self) -> io::Result<State> {
406 raw::get_state(&self.input, &self.output)
407 }
408
409 /// Apply a previously snapshotted terminal mode.
410 ///
411 /// This does not update or clear the state cached by
412 /// [`make_raw`](Self::make_raw). Use it for manual state management; use
413 /// [`restore`](Self::restore) for the terminal-owned raw-mode lifecycle.
414 /// `state` should have been read from this terminal's own handles, since
415 /// a [`State`] records each half separately.
416 ///
417 /// # Parameters
418 ///
419 /// * `state` — state to apply to the terminal.
420 ///
421 /// # Returns
422 ///
423 /// `Ok(())` when the state was applied.
424 ///
425 /// # Errors
426 ///
427 /// Returns any error from `set_state`.
428 ///
429 /// # Panics
430 ///
431 /// This method does not intentionally panic.
432 pub fn set_state(&self, state: &State) -> io::Result<()> {
433 raw::set_state(&self.input, &self.output, state)
434 }
435
436 /// Report whether the input and output halves are terminals.
437 ///
438 /// # Returns
439 ///
440 /// `(input_is_terminal, output_is_terminal)`.
441 ///
442 /// # Errors and panics
443 ///
444 /// This method does not fail or intentionally panic.
445 pub fn is_terminal(&self) -> (bool, bool) {
446 (
447 raw::is_terminal(&self.input),
448 raw::is_terminal(&self.output),
449 )
450 }
451
452 /// Query the current terminal window size.
453 ///
454 /// On Unix this tries the output descriptor first and falls back to the
455 /// input descriptor if the output query fails. If both fail, the output
456 /// descriptor's error is returned.
457 /// On Windows this queries the output console screen buffer. Pixel
458 /// dimensions are unavailable and are reported as `0`.
459 ///
460 /// # Returns
461 ///
462 /// The current window size in cells and, when reported by the platform,
463 /// pixels.
464 ///
465 /// # Errors
466 ///
467 /// Returns an OS error if the platform's size query fails.
468 ///
469 /// # Panics
470 ///
471 /// This method does not intentionally panic.
472 pub fn get_window_size(&self) -> io::Result<Winsize> {
473 let result = get_window_size(&self.output);
474 #[cfg(unix)]
475 let result = result.or_else(|e| get_window_size(&self.input).map_err(|_| e));
476 result
477 }
478}
479
480#[cfg(test)]
481mod tests {
482 use super::*;
483 use crate::terminal::EnvList;
484
485 #[test]
486 fn env_helpers_delegate_to_env() {
487 let env =
488 EnvList::from_pairs([("TERM", "xterm-256color"), ("NO_COLOR", "1"), ("EMPTY", "")]);
489 let term = Terminal::new(stdin(), stdout(), env);
490
491 assert_eq!(term.get_env("TERM").as_deref(), Some("xterm-256color"));
492 assert!(term.has_env("TERM"));
493 assert!(!term.has_env("EMPTY")); // present but empty
494 assert!(!term.has_env("MISSING"));
495 // The full environment is reachable for richer queries.
496 assert_eq!(term.env().get("NO_COLOR").as_deref(), Some("1"));
497 }
498
499 /// A restore that fails must not consume the cached state: it is the only
500 /// copy of the pre-raw attributes, and dropping it turns a transient
501 /// failure into a terminal the caller can no longer put back.
502 #[cfg(all(unix, not(target_os = "l4re")))]
503 #[test]
504 fn a_failed_restore_keeps_the_saved_state_for_a_retry() {
505 use crate::testutil::{ScriptedFd, open_pty_pair, opost, prime};
506 use std::os::fd::AsFd;
507
508 let (Some((_ma, a)), Some((_mb, b))) = (open_pty_pair(), open_pty_pair()) else {
509 return;
510 };
511 // A fresh pty's attributes are implementation-defined, so put `OPOST`
512 // where the assertions below need it rather than assuming it.
513 prime(&b, true);
514
515 // The two `make_raw` borrows land on the pty, the first restore lands on
516 // a pipe and fails, and the retry lands on the pty again.
517 let pipe = std::io::pipe().expect("pipe").0;
518 let output = ScriptedFd::new(&[&b as &dyn AsFd, &b, &pipe, &b]);
519 let mut term = Terminal::new(&a, output, EnvList::from_pairs([("TERM", "dumb")]));
520
521 term.make_raw().expect("raw mode");
522 assert!(!opost(&b), "the output half must be raw");
523
524 term.restore()
525 .expect_err("a restore through a pipe cannot succeed");
526 // Without the cached state this is a silent no-op that reports success.
527 term.restore().expect("the retry restores");
528 assert!(opost(&b), "the retry must put the output half back");
529 }
530}