Debian Codegraph @

Xtermina/src/terminal.rs

raw symbols SCIP
1 //! Terminal handles and platform-neutral terminal operations.
2 //!
3 //! [`PlatformTerminal`] opens the process terminal for the current target. It implements
4 //! [`Terminal`], which combines byte output, raw/cooked mode switching, terminal dimensions,
5 //! synchronous event reads, polling, and panic-hook cleanup. Termina does not enter alternate
6 //! screen with [`DecPrivateModeCode::ClearAndEnableAlternateScreen`], enable
7 //! [`DecPrivateModeCode::BracketedPaste`], or enable mouse tracking modes such as
8 //! [`DecPrivateModeCode::MouseTracking`] for you. Those are protocol choices the application
9 //! writes explicitly with [`crate::escape`].
10 //!
11 //! # Examples
12 //!
13 //! ```no_run
14 //! use std::{io, time::Duration};
15 //!
16 //! use termina::{
17 //! event::{Event, KeyEventKind},
18 //! PlatformTerminal, Terminal,
19 //! };
20 //!
21 //! fn main() -> io::Result<()> {
22 //! let mut terminal = PlatformTerminal::new()?;
23 //! terminal.enter_raw_mode()?;
24 //!
25 //! if terminal.poll(|_| true, Some(Duration::from_millis(250)))? {
26 //! let event = terminal.read(|event| {
27 //! matches!(event, Event::Key(key) if key.kind == KeyEventKind::Press)
28 //! })?;
29 //! if let Event::Key(key) = event {
30 //! println!("received {:?}", key.code);
31 //! }
32 //! }
33 //!
34 //! terminal.enter_cooked_mode()
35 //! }
36 //! ```
37
38 #[cfg(unix)]
39 mod unix;
40
41 #[cfg(windows)]
42 mod windows;
43
44 use std::{io, time::Duration};
45
46 #[cfg(unix)]
47 pub use unix::*;
48
49 #[cfg(windows)]
50 pub use windows::*;
51
52 use crate::{Event, EventReader, WindowSize};
53
54 #[cfg(doc)]
55 use crate::escape::csi::{DecPrivateModeCode, Keyboard};
56
57 /// The terminal implementation for the current platform.
58 ///
59 /// On Unix this aliases `UnixTerminal`. On Windows this aliases `WindowsTerminal`.
60 #[cfg(unix)]
61 pub type PlatformTerminal = UnixTerminal;
62 #[cfg(windows)]
63 pub type PlatformTerminal = WindowsTerminal;
64
65 /// The output handle type passed to panic hooks on the current platform.
66 ///
67 /// The hook receives this lower-level handle instead of `PlatformTerminal` so cleanup code can
68 /// write terminal reset sequences even while the higher-level terminal value is unwinding.
69 #[cfg(unix)]
70 pub type PlatformHandle = FileDescriptor;
71 #[cfg(windows)]
72 pub type PlatformHandle = OutputHandle;
73
74 /// Platform-agnostic terminal I/O surface.
75 ///
76 /// The trait is implemented by the Unix and Windows backends and also requires [`io::Write`], so a
77 /// terminal value is both an output sink and an input/event source. `enter_raw_mode` and
78 /// `enter_cooked_mode` only manage the platform terminal mode. Application-level terminal features
79 /// such as alternate screen, bracketed paste, focus tracking, mouse tracking, and keyboard
80 /// protocol flags are CSI/OSC writes and remain the caller's responsibility. See
81 /// [`DecPrivateModeCode::ClearAndEnableAlternateScreen`],
82 /// [`DecPrivateModeCode::BracketedPaste`], [`DecPrivateModeCode::FocusTracking`],
83 /// [`DecPrivateModeCode::MouseTracking`], and [`Keyboard`] for the typed escape values.
84 ///
85 /// `poll` and `read` use filters because the terminal stream may include responses that the caller
86 /// is not currently waiting for. Rejected events stay buffered in [`EventReader`] so later reads
87 /// can still observe them.
88 ///
89 /// # Implementation Notes
90 ///
91 /// This trait is based on [termwiz's terminal API], but Termina keeps feature setup outside the
92 /// terminal type and mirrors crossterm's synchronous event-reader shape for `poll` and `read`.
93 ///
94 /// [termwiz's terminal API]: https://docs.rs/termwiz/latest/termwiz/terminal/index.html
95 pub trait Terminal: io::Write {
96 /// Enters raw mode for the platform terminal.
97 ///
98 /// Raw mode disables line buffering and other terminal-driver processing, so key presses and
99 /// escape sequences can reach the application without waiting for Enter. Use
100 /// [`Self::enter_cooked_mode`] before returning control to a normal shell.
101 fn enter_raw_mode(&mut self) -> io::Result<()>;
102
103 /// Enters cooked mode for the platform terminal.
104 ///
105 /// Cooked mode is the normal shell-facing mode for a terminal device. The terminal driver
106 /// handles echo, line editing, and Enter-delimited input before passing data to the
107 /// application. On Unix, this restores the termios state captured when the terminal was opened.
108 /// On Windows, this switches the console input flags back to cooked behavior, but leaves other
109 /// captured state, such as code pages and virtual-terminal flags, for drop-time cleanup.
110 fn enter_cooked_mode(&mut self) -> io::Result<()>;
111
112 /// Reads the current terminal window dimensions.
113 fn get_dimensions(&self) -> io::Result<WindowSize>;
114
115 /// Returns a cloneable event reader backed by the terminal input handle.
116 fn event_reader(&self) -> EventReader;
117
118 /// Checks if there is an [`Event`] available.
119 ///
120 /// Returns `Ok(true)` if an [`Event`] is available or `Ok(false)` if one is not available.
121 /// If `timeout` is `None`, this blocks until a matching event is available.
122 fn poll<F: Fn(&Event) -> bool>(&self, filter: F, timeout: Option<Duration>)
123 -> io::Result<bool>;
124
125 /// Reads a single [`Event`] from the terminal.
126 ///
127 /// This function blocks until an [`Event`] is available. Use [`Self::poll`] first to guarantee
128 /// that the read won't block.
129 fn read<F: Fn(&Event) -> bool>(&self, filter: F) -> io::Result<Event>;
130 /// Installs a panic hook that can write terminal cleanup sequences.
131 ///
132 /// Depending on how your application handles panics, you may want to eagerly reset
133 /// application-level terminal state before the process exits. Use this hook for cleanup such as
134 /// disabling [`DecPrivateModeCode::BracketedPaste`] or returning from
135 /// [`DecPrivateModeCode::ClearAndEnableAlternateScreen`] to the main screen.
136 ///
137 /// The hook receives a [`PlatformHandle`] for stdout or the platform console output. After the
138 /// hook runs, Termina restores the platform mode as if [`Self::enter_cooked_mode`] had run.
139 fn set_panic_hook(&mut self, f: impl Fn(&mut PlatformHandle) + Send + Sync + 'static);
140 }